diff --git a/.gitattributes b/.gitattributes index 83211371402d6ce6b019154a3d962e4280283eea..fa6887b733e0dbe14580140256f7558b9505714b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -526,3 +526,26 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torch/_export/serde/__pycache__/serialize.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torch/_functorch/__pycache__/partitioners.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/codecache.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpp_builder.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/graph.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ir.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/lowering.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/scheduler.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/common.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/pallas.cpython-312.pyc 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 diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/streams.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..63e21f66b6af249adfdd672e29e80660cfc0f489 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/streams.py @@ -0,0 +1,979 @@ +import operator +from collections.abc import Callable +from typing import Any, TYPE_CHECKING, TypeAlias + +import torch.fx +import torch.fx.traceback +import torch.utils._pytree as pytree +from torch._dynamo.graph_utils import _get_flat_args +from torch._dynamo.variables.streams import get_current_stream, new_event +from torch.fx.node import map_arg +from torch.utils._ordered_set import OrderedSet +from torch.utils._runtime_estimation import ( + _FLOAT_TYPES, + _IGNORE_OPS, + get_compute_time, + get_transfer_time, +) + + +if TYPE_CHECKING: + from .schemas import ViewAndMutationMeta + +from .indexed_dict import IndexedDict + + +aten = torch.ops.aten + +Node: TypeAlias = torch.fx.Node +Graph: TypeAlias = torch.fx.Graph +Partition: TypeAlias = bool + +FORWARD: Partition = False +BACKWARD: Partition = True +_EMPTY_LOCATIONS: frozenset[tuple[Partition, int]] = frozenset() + +_SYNC_OPS = ( + torch.ops.streams.record_event.default, + torch.ops.streams.wait_event.default, + torch.ops.streams.wait_stream.default, + torch.ops.streams.synchronize_event.default, + torch.ops.streams.synchronize_device.default, + torch.ops.streams.synchronize_stream.default, +) + + +def get_roofline_estimate(node: Node) -> float: + if node.op != "call_function": + raise AssertionError(f"non-func node in roofline estimate: {node.op}") + + def map_value(x: Any) -> Any: + return x.meta.get("value", x) if isinstance(x, Node) else x + + func = node.target + if func in _IGNORE_OPS: + return 0.0 + + mapped_args = torch.fx.map_arg(node.args, map_value) + mapped_kwargs = torch.fx.map_arg(node.kwargs, map_value) + flat_args_kwargs = [map_value(x) for x in _get_flat_args(node, {})] + flat_outs, _ = pytree.tree_flatten(node.meta.get("value", node)) + out = node.meta.get("value", node) + out_dtypes = { + t.dtype + for t in flat_outs + if isinstance(t, torch.Tensor) and t.dtype in _FLOAT_TYPES + } + + return ( + max( + get_transfer_time(flat_args_kwargs, flat_outs), + get_compute_time(func, mapped_args, mapped_kwargs, out, out_dtypes), + ) + / 1e6 + ) + + +def is_gradient_acc(node: Node) -> bool: + return node.meta.get("is_gradient_acc", False) + + +def is_bwd_node(node: Node) -> Partition: + tag = node.meta.get("partitioner_tag") + return tag == "is_backward" or tag == "must_be_in_backward" + + +def get_device(node: Node) -> torch.device: + return node.meta["val"].device + + +def get_stream(node: Node) -> int | None: + maybe_annotation = node.meta.get("custom", None) + if maybe_annotation is not None: + return node.meta["custom"].get("stream", None) + else: + return None + + +def get_stream_or_current_stream(node: Node) -> int: + ind = get_stream(node) + if ind is None: + ind = get_current_stream(get_device(node)) + return ind + + +def set_stream(node: Node, ind: int) -> None: + if "custom" in node.meta: + node.meta["custom"].update({"stream": ind}) + else: + node.meta["custom"] = {"stream": ind} + + +def insert_record_event_after_node(graph: Graph, node: Node, event_ind: int) -> Node: + with graph.inserting_after(node): + node = graph.call_function( + torch.ops.streams.record_event.default, + ( + event_ind, + get_stream_or_current_stream(node), + ), + ) + node.meta["partitioner_tag"] = "must_be_in_backward" + + return node + + +def insert_wait_event_before_node(graph: Graph, node: Node, event_ind: int) -> Node: + with graph.inserting_before(node): + node = graph.call_function( + torch.ops.streams.wait_event.default, + ( + event_ind, + get_stream_or_current_stream(node), + ), + ) + node.meta["partitioner_tag"] = "must_be_in_backward" + + return node + + +def populate_stream_timeline( + stream_to_timeline: dict[int | None, IndexedDict[Node, float]], + graph: Graph, + stream_index: int | None, +) -> IndexedDict[Node, float]: + if stream_index not in stream_to_timeline: + stream_to_timeline[stream_index] = IndexedDict() + total_time = 0.0 + for node in graph.nodes: + # mlazos: not sure if we should include forward here too but don't think it matters + if ( + node.op == "call_function" + and is_bwd_node(node) + and get_stream(node) == stream_index + ): + total_time += get_roofline_estimate(node) + stream_to_timeline[stream_index][node] = ( + total_time # NB: total time includes the node's runtime + ) + + return stream_to_timeline[stream_index] + + +# NB: we start all estimates at 0, estimating the total runtime of each stream with timestamps at each node +# we then try and use these timestamps to estimate when to deallocate tensors used in side streams +# See https://docs.pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html#torch.Tensor.record_stream +# for details on the problem being addressed. Rather than using the automatic memory management approach of record_stream +# we attempt to find the point which to deallocate based on the estimated timestamps. +def handle_synced_deallocation( + graph: Graph, + stream_to_exec_trace: dict[int | None, IndexedDict[Node, float]], + node: Node, + last_usage: Node, +) -> None: + if not is_bwd_node(node): + raise AssertionError( + "synced allocations should only be handled on backward nodes" + ) + if not is_bwd_node(last_usage): + raise AssertionError( + "synced allocations should only be handled on backward nodes" + ) + allocating_stream = get_stream(node) + side_stream = get_stream(last_usage) + if allocating_stream == side_stream: + raise AssertionError( + "allocating and side stream should be different for synced deallocations" + ) + if not torch.accelerator.is_available(): + # fallback to record_stream in this case + with graph.inserting_after(node): + rs = graph.call_function( + torch.ops.streams.record_stream.default, + ( + node, + get_stream_or_current_stream(last_usage), + ), + {}, + ) + rs.meta["partitioner_tag"] = "must_be_in_backward" + + allocating_stream_trace = populate_stream_timeline( + stream_to_exec_trace, graph, allocating_stream + ) + side_stream_trace = populate_stream_timeline( + stream_to_exec_trace, graph, side_stream + ) + + alloc_ptr = node + target_side_stream_time = side_stream_trace[last_usage] + # linear search from first usage of tensor to a point in time after the side stream has finished + while alloc_ptr is not None: + alloc_time = allocating_stream_trace[alloc_ptr] + + if alloc_time >= target_side_stream_time: + break + elif alloc_time < target_side_stream_time: + next_ptr = allocating_stream_trace.next_key(alloc_ptr) + if next_ptr is not None: + alloc_ptr = next_ptr + else: + break + + wait_event = new_event() + record_node = insert_record_event_after_node(graph, last_usage, wait_event) + with graph.inserting_after(max(alloc_ptr, record_node)): + sd = graph.call_function( + torch.ops.streams.sync_dealloc.default, + (wait_event, get_stream_or_current_stream(alloc_ptr), node), + {}, + ) + sd.meta["partitioner_tag"] = "must_be_in_backward" + + +def insert_sync( + graph: Graph, + consumer: Node, + producer: Node, + node_to_wait_event_ind: dict[Node, int], +) -> None: + if producer not in node_to_wait_event_ind: + node_to_wait_event_ind[producer] = new_event() + + insert_record_event_after_node( + graph, producer, node_to_wait_event_ind[producer] + ) + insert_wait_event_before_node(graph, consumer, node_to_wait_event_ind[producer]) + + +def assign_backward_streams(gm: torch.fx.GraphModule) -> None: + """Assigns backward streams to gradient accumulation nodes""" + + # NB: iterate in reverse order to more closely match eager + # the user node stream will be populated first + for node in reversed(list(gm.graph.nodes)): + if is_gradient_acc(node): + # Accumulation stream selection. Follow the rules from top to bottom to determine the accumulation stream: + # 1. Match first stream assignment of the first user with a stream + # 2. Match first stream assignment encountered in the args from left to right + # This differs from eager in some cases: + # Specifically the eager code uses the autograd node to determine the stream, + # crucially this does not necessarily correspond to the FX graph node. For example, + # in the backward for an add node with a constant we will passthrough and during backward tracing, + # no op will be added to the FX graph, so our stream assignment will differ in this case. + gradients = _get_flat_args(node, {}) + users = list(node.users.keys()) + + # All gradients will be on same device, they will be coerced if they were not with a .to() node + for neighbor in users + gradients: + ind = get_stream(neighbor) + if ind is not None: + set_stream(node, ind) + break + + +def insert_backward_syncs(gm: torch.fx.GraphModule) -> None: + """Inserts stream syncs for backward nodes if consumer and producer are on different streams""" + node_to_wait_event_ind: dict[Node, int] = {} + for node in gm.graph.nodes: + if node.op == "call_function" and is_bwd_node(node): + flat_args = _get_flat_args(node, {}) + cur_node_stream = get_stream(node) + + for arg in flat_args: + if arg.op == "call_function" and is_bwd_node(arg): + arg_stream = get_stream(arg) + if arg_stream != cur_node_stream and get_device(arg).type != "cpu": + insert_sync(gm.graph, node, arg, node_to_wait_event_ind) + + +def sync_deallocations(gm: torch.fx.GraphModule) -> None: + """Handles https://docs.pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html#torch.Tensor.record_stream""" + # Note: this is only needed if the last usage of a tensor is on a stream other than + # the stream the tensor was allocated on + + # an estimated timestamp from the beginning of graph execution (assuming 0 CPU overhead) + # I think this is fine because you should have large tensors if you're using streams + # although perhaps I could add a constant 10us per op ahead of the first stream op? + # a trace of all the nodes running in a given stream + stream_to_exec_trace: dict[int | None, IndexedDict[Node, float]] = {} + for node in gm.graph.nodes: + if node.op == "call_function" and is_bwd_node(node): + allocating_stream = get_stream(node) + users = list(node.users.keys()) + if not users: + continue + last_user = max(user for user in users) + if last_user.op == "output": + continue + side_stream = get_stream(last_user) + if allocating_stream != side_stream: + handle_synced_deallocation( + gm.graph, stream_to_exec_trace, node, last_user + ) + + +def assign_epilogue_copy_streams(gm: torch.fx.GraphModule) -> None: + for epi_copy in gm.graph.find_nodes(op="call_function", target=aten.copy_.default): + arg_stream = get_stream(epi_copy.args[1]) + copy_stream = get_stream(epi_copy) + if arg_stream != copy_stream: + set_stream(epi_copy, get_stream_or_current_stream(epi_copy.args[1])) + + +def populate_fw_metadata_with_stream_indices( + gm: torch.fx.GraphModule, fw_metadata: "ViewAndMutationMeta" +) -> None: + """ + Populates fw_metadata.mutated_inp_stream_indices with stream indices from the compiled graph. + + The forward graph outputs are structured as: + (*mutated_inputs, *user_outputs, *intermediate_bases, *saved_tensors, *saved_symints) + + We extract the stream index for each mutated input from the graph's output node. + """ + + num_mutated_inps = fw_metadata.num_mutated_inp_runtime_indices + if num_mutated_inps == 0: + fw_metadata.mutated_inp_stream_indices = [] + return + + # Find the output node in the graph + output_node = None + for node in gm.graph.find_nodes(op="output"): + output_node = node + break + + if output_node is None: + raise AssertionError( + "No output node found in the graph when extracting stream indices" + ) + + # The output node's args[0] is a tuple/list of all outputs + output_args = output_node.args[0] + + # Extract stream indices for the first num_mutated_inps outputs + stream_indices = [] + for i in range(num_mutated_inps): + if i < len(output_args): + output_arg = output_args[i] + # Get the stream index from the node metadata + stream_idx = ( + get_stream(output_arg) + if isinstance(output_arg, torch.fx.Node) + else None + ) + stream_indices.append(stream_idx) + else: + stream_indices.append(None) + + fw_metadata.mutated_inp_stream_indices = stream_indices + + +def _expand_dict_returning_deps( + deps: list[Node], + visited: set[Node], + graph: torch.fx.Graph, + sync_node: Node, +) -> list[Node]: + """Expand triton_kernel_wrapper_functional dict deps into per-key getitems. + + ``triton_kernel_wrapper_functional`` returns a flat ``dict[str, Tensor]``. + If such a node is threaded through ``control_deps`` as a pass-through + value, ``decompose_triton_kernel_wrapper_functional`` later replaces it + with a raw Python dict, corrupting every user that expected an FX Node. + + To avoid this, we insert ``operator.getitem`` nodes *before* the sync for + each after-sync getitem user, so that only tensor-valued nodes are passed + through ``control_deps``. The dict node may still appear in + ``additional_deps`` (ordering-only) which is safe since that tuple is + never decomposed. + """ + expanded: list[Node] = [] + for dep in deps: + if not ( + dep.op == "call_function" + and dep.target is torch.ops.higher_order.triton_kernel_wrapper_functional + ): + expanded.append(dep) + continue + + after_sync_getitems = [ + user + for user in dep.users + if user not in visited + and user.op == "call_function" + and user.target is operator.getitem + ] + if not after_sync_getitems: + expanded.append(dep) + continue + + with graph.inserting_before(sync_node): + for old_gi in after_sync_getitems: + key = old_gi.args[1] + new_gi = graph.call_function(operator.getitem, args=(dep, key)) + new_gi.meta.update(old_gi.meta) + if isinstance(new_gi.meta.get("val"), dict): + raise AssertionError( + f"nested dict in triton kernel output for key {key}" + ) + visited.add(new_gi) + expanded.append(new_gi) + old_gi.replace_all_uses_with(new_gi) + graph.erase_node(old_gi) + + return expanded + + +def _wrap_sync_node( + gm: torch.fx.GraphModule, + sync_node: Node, + deps_before_sync: list[Node], + visited: set[Node], + partition_scoped_deps: set[Node] | None = None, +) -> tuple[Node, list[Node]]: + """ + Core logic: wrap a single sync node in control_deps. + + Returns (control_deps_node, passthrough_getitems) where passthrough_getitems + are the getitem nodes that thread dependencies through the control_deps node. + ``visited`` is the set of nodes at or before the sync node in graph order, + used to distinguish pre-sync vs post-sync users. + """ + from torch._inductor.fx_passes.control_dependencies import ( + _create_subgraph_for_node, + control_deps, + get_subgraph_name, + ) + + graph = gm.graph + if partition_scoped_deps is None: + partition_scoped_deps = set() + + sync_is_bwd = is_bwd_node(sync_node) + + def _user_rewrite_pred(dep: Node) -> Callable[[Node], bool]: + if dep in partition_scoped_deps: + + def pred(user: Node) -> bool: + if user in visited: + return False + if user.op == "output": + return sync_is_bwd + return is_bwd_node(user) == sync_is_bwd + + return pred + + dep_is_bwd = is_bwd_node(dep) + + def pred(user: Node) -> bool: + return user not in visited and (user.op != "output" or dep_is_bwd) + + return pred + + # Use dep.users to find deps with uses after the sync — avoids a forward walk. + deps_with_uses_after_sync = [] + for dep in deps_before_sync: + pred = _user_rewrite_pred(dep) + if any(pred(user) for user in dep.users): + deps_with_uses_after_sync.append(dep) + + # Expand dict-returning nodes (triton_kernel_wrapper_functional) into + # individual getitem outputs. Passing a dict-valued node through + # control_deps breaks post-grad passes: reinplace + decomposition replace + # the dict node with a Python dict, corrupting any user that expected an + # FX Node. Unwrapping here ensures only tensor-valued nodes flow through. + deps_with_uses_after_sync = _expand_dict_returning_deps( + deps_with_uses_after_sync, visited, graph, sync_node + ) + + # Create subgraph that executes sync and passes through only used dependencies + subgraph_module = _create_subgraph_for_node( + graph, sync_node, deps_with_uses_after_sync + ) + subgraph_attr_name = get_subgraph_name(gm, sync_node.name) + setattr(gm, subgraph_attr_name, subgraph_module) + + # Create control_deps call + # Note: sync nodes (record_event/wait_event) only take int args, no Node args. + with graph.inserting_before(sync_node): + get_subgraph = graph.get_attr(subgraph_attr_name) + control_deps_node = graph.call_function( + control_deps, + args=( + tuple(deps_before_sync), # additional_deps (all deps for ordering) + get_subgraph, # subgraph + *deps_with_uses_after_sync, # only pass through deps that are used + ), + kwargs={}, + ) + + # Propagate partitioner_tag so the partitioner can distinguish + # forward vs backward sync control_deps during graph extraction. + if "partitioner_tag" in sync_node.meta: + control_deps_node.meta["partitioner_tag"] = sync_node.meta["partitioner_tag"] + + # Mark newly created nodes as visited so subsequent syncs don't + # misclassify them as "after the sync" during replacement. + visited.add(get_subgraph) + visited.add(control_deps_node) + + # The output is (sync_result, *deps_with_uses_after_sync) + # Reuse the val the subgraph output already carries: the min-cut + # partitioner's _size_of() raises on any node without `val`, and its escape + # hatch covers only get_attr and zero-return OpOverloads, not a schema-less + # HOP. The subgraph output is unwrapped when it has no pass-through deps. + sg_val = subgraph_module.graph.output_node().meta.get("val") + control_deps_node.meta["val"] = sg_val if isinstance(sg_val, tuple) else (sg_val,) + + # Create getitem nodes only for dependencies that have uses after sync + replacements: dict[Node, Node] = {} + with graph.inserting_after(control_deps_node): + for i, dep in enumerate(deps_with_uses_after_sync): + getitem_node = graph.call_function( + operator.getitem, + args=(control_deps_node, i + 1), # +1 because index 0 is sync result + ) + getitem_node.meta.update(dep.meta) + # The getitem is a passthrough projection of an existing value, not + # a node that *produces* an unbacked symbol - the original ``dep`` + # (still inside the subgraph) is the binding site. Leaving the + # binding on the getitem trips Inductor's run_node assertion that + # ``new_unbacked_defs >= renamed_unbacked_bindings``. + getitem_node.meta.pop("unbacked_bindings", None) + replacements[dep] = getitem_node + visited.add(getitem_node) + + # Replace uses of dependencies that come after sync_node. + # Use map_arg to handle nested structures (e.g. output node's list args). + for dep, getitem_node in replacements.items(): + pred = _user_rewrite_pred(dep) + for user in list(dep.users.keys()): + if user is control_deps_node: + continue + if not pred(user): + continue + + def _replace(n: Node) -> Node: + return getitem_node if n is dep else n + + if ( + user.op == "call_function" + and user.target is torch.ops.aten.copy_.default + and user.args[0] is dep + and dep in partition_scoped_deps + ): + # AOT functionalization leaves keep_input_mutations epilogue + # copy_ as the only writer of a partition-scoped placeholder. + # Preserve the destination identity used by mutation bookkeeping. + user.args = (dep, *map_arg(user.args[1:], _replace)) + else: + user.args = map_arg(user.args, _replace) + user.kwargs = map_arg(user.kwargs, _replace) + + # Remove original sync node + sync_node.replace_all_uses_with(control_deps_node) + graph.erase_node(sync_node) + return control_deps_node, list(replacements.values()) + + +def _collect_sync_forward_deps( + graph: torch.fx.Graph, +) -> tuple[dict[Node, OrderedSet[Node]], dict[Node, OrderedSet[Node]]]: + """Collect values that must cross sync boundaries. + + ``live_inputs[partition][stream]`` tracks values whose passthrough can anchor + later work in that partition on that stream. Demand labels propagate through + producers while each producer also seeds its own execution stream. This is a + single reverse liveness traversal; the forward pass still handles sync/event + state introduced while rewriting the graph. + """ + stream_sync_deps: dict[Node, OrderedSet[Node]] = {} + full_barrier_deps: dict[Node, OrderedSet[Node]] = {} + live_inputs: dict[Partition, dict[int, OrderedSet[Node]]] = { + FORWARD: {}, + BACKWARD: {}, + } + locations: dict[Node, OrderedSet[tuple[Partition, int]]] = {} + full_barriers = ( + torch.ops.streams.synchronize_device.default, + torch.ops.streams.synchronize_event.default, + torch.ops.streams.synchronize_stream.default, + ) + + def _add_live(node: Node, partition: Partition, stream: int) -> None: + stream_inputs = live_inputs[partition].get(stream) + if stream_inputs is None: + stream_inputs = live_inputs[partition][stream] = OrderedSet() + stream_inputs.add(node) + node_locations = locations.get(node) + if node_locations is None: + node_locations = locations[node] = OrderedSet() + node_locations.add((partition, stream)) + + for node in reversed(graph.nodes): + if node.op == "call_function" and node.target in full_barriers: + deps = OrderedSet( + dep + for stream_inputs in live_inputs[is_bwd_node(node)].values() + for dep in stream_inputs + ) + if deps: + full_barrier_deps[node] = deps + continue + if ( + node.op == "call_function" + and node.target is torch.ops.streams.wait_stream.default + ): + waiting_stream: int = node.args[0] # type: ignore[assignment] + deps = live_inputs[is_bwd_node(node)].get(waiting_stream) + if deps: + stream_sync_deps[node] = deps.copy() + continue + if ( + node.op == "call_function" + and node.target is torch.ops.streams.wait_event.default + ): + waiting_stream: int = node.args[1] # type: ignore[assignment] + deps = live_inputs[is_bwd_node(node)].get(waiting_stream, ()) + graph_inputs = OrderedSet(dep for dep in deps if dep.op == "placeholder") + if graph_inputs: + stream_sync_deps[node] = graph_inputs + continue + if node.op != "call_function" or node.target in _SYNC_OPS: + continue + + inherited_locations = locations.pop(node, _EMPTY_LOCATIONS) + for partition, stream in inherited_locations: + live_inputs[partition][stream].discard(node) + execution_stream = get_stream(node) + if execution_stream is None: + execution_stream = 0 + target_locations = OrderedSet( + (*inherited_locations, (is_bwd_node(node), execution_stream)) + ) + + def _collect(n: Node) -> Node: + if "val" in n.meta: + for partition, stream in target_locations: + _add_live(n, partition, stream) + return n + + map_arg(node.args, _collect) + map_arg(node.kwargs, _collect) + return stream_sync_deps, full_barrier_deps + + +def _collect_full_barrier_deps( + stream_to_nodes: dict[int | None, list[Node]], + stream_sync_deps: dict[int | None, list[Node]], + bwd: bool = False, +) -> list[Node]: + """Collect all still-live cross-stream deps for a full CPU barrier + (synchronize_stream/device/event). + + These ops block the CPU, so a consumer is only ordered after them by an + explicit control_deps edge (nothing on the consumer's stream waits for a CPU + barrier). Includes live compute nodes (stream_to_nodes) plus the ctrl/ + passthrough nodes accumulated by prior sync ops that already cleared + stream_to_nodes (stream_sync_deps), deduped by identity preserving order. + + ``bwd`` marks a backward barrier: its accumulated sync deps are filtered to + backward nodes only, so it never depends on a forward control_deps node. + That edge would cross the fwd/bwd boundary onto a node that is neither + saveable nor recomputable, making the min-cut partitioner infeasible. + Forward compute deps (stream_to_nodes) are kept -- backward legitimately + depends on forward activations. + """ + all_deps = [n for nodes in stream_to_nodes.values() for n in nodes] + seen = set(all_deps) + for deps in stream_sync_deps.values(): + for dep in deps: + if dep in seen or (bwd and not is_bwd_node(dep)): + continue + all_deps.append(dep) + seen.add(dep) + return all_deps + + +def wrap_all_sync_nodes_with_control_deps(gm: torch.fx.GraphModule) -> None: + """ + Single-pass wrap of all sync nodes in control_deps. + + Iterates through the graph once, accumulating per-stream node lists. + When a sync node is encountered, it is wrapped using the accumulated deps + for that stream, then the deps are reset to the control_deps node + (maintaining the ordering chain for subsequent syncs on the same stream). + """ + graph = gm.graph + if len(graph.nodes) == 0: + raise RuntimeError("Expected a non-empty graph") + + stream_sync_forward_deps, full_barrier_forward_deps = _collect_sync_forward_deps( + graph + ) + + stream_to_nodes: dict[int | None, list[Node]] = {} + # Maps event_index to its latest ordering anchor: either the control_deps that + # wrapped record_event or a raw record_event with no dependencies. + event_to_anchor: dict[int, Node] = {} + # Maps event_index -> getitem nodes threaded through record_event's control_deps, + # so synchronize_event can thread them through to subsequent ops. + event_to_passthrough: dict[int, list[Node]] = {} + # Maps event_index -> stream that the event was recorded on, + # so synchronize_event can infer its stream. + event_to_stream: dict[int, int | None] = {} + # Tracks the most recent control_deps node and its passthrough + # getitems per stream. synchronize_stream/device consults this to + # depend on prior sync ops (ctrl_node for ordering) and thread + # cross-stream data through (passthrough for data edges), even + # after stream_to_nodes has been cleared by those sync ops. + stream_sync_deps: dict[int | None, list[Node]] = {} + visited: set[Node] = set() + found_sync = False + + # Walk the node linked-list manually so we can mutate the graph + # (wrapping sync nodes inserts/erases nodes) without losing our place. + node = next(iter(graph.nodes)) + while node.op != "root": + next_node = node.next + visited.add(node) + + if node.op == "call_function": + if node.target in _SYNC_OPS: + # synchronize_device and synchronize_stream block the CPU, + # so all subsequent kernel launches are host-ordered after + # them. Treat both as full barriers across all streams. + if node.target in ( + torch.ops.streams.synchronize_device.default, + torch.ops.streams.synchronize_stream.default, + ): + all_stream_deps = _collect_full_barrier_deps( + stream_to_nodes, stream_sync_deps, bwd=is_bwd_node(node) + ) + existing_deps = set(all_stream_deps) + for dep in full_barrier_forward_deps.get(node, ()): + if dep not in existing_deps: + all_stream_deps.append(dep) + existing_deps.add(dep) + if all_stream_deps: + found_sync = True + ctrl_node_sync, passthrough_sync = _wrap_sync_node( + gm, node, all_stream_deps, visited + ) + else: + ctrl_node_sync = None + passthrough_sync: list[Node] = [] + stream_to_nodes.clear() + stream_sync_deps.clear() + sync_anchor = ctrl_node_sync if ctrl_node_sync is not None else node + stream_sync_deps[None] = [sync_anchor, *passthrough_sync] + while ( + getattr(next_node, "_erased", False) and next_node.op != "root" + ): + next_node = next_node.next + node = next_node + continue + + # wait_stream(waiting, waited_on) creates a dependency on + # the waited_on stream: all prior work there must complete + # before the waiting stream proceeds. + if node.target is torch.ops.streams.wait_stream.default: + waiting_stream: int = node.args[0] # type: ignore[assignment] + waited_on_stream: int = node.args[1] # type: ignore[assignment] + deps_before_sync = list(stream_to_nodes.get(waited_on_stream, ())) + if waiting_stream != waited_on_stream: + deps_before_sync.extend(stream_to_nodes.get(waiting_stream, ())) + if None in stream_to_nodes and waited_on_stream is not None: + deps_before_sync.extend(stream_to_nodes[None]) + participating_streams = dict.fromkeys( + (waited_on_stream, waiting_stream, None) + ) + prior_syncs = list( + dict.fromkeys( + dep + for stream in participating_streams + for dep in stream_sync_deps.get(stream, ()) + ) + ) + if is_bwd_node(node): + prior_syncs = [n for n in prior_syncs if is_bwd_node(n)] + deps_before_sync.extend(prior_syncs) + # Also include inputs of subsequent waiting-stream nodes + # so they get threaded through control_deps, creating a + # forward ordering constraint (waiting-stream work must + # come after wait_stream). + existing_deps = set(deps_before_sync) + for dep in stream_sync_forward_deps.get(node, ()): + if dep not in existing_deps: + deps_before_sync.append(dep) + existing_deps.add(dep) + if deps_before_sync: + found_sync = True + ctrl_node_ws, passthrough_ws = _wrap_sync_node( + gm, node, deps_before_sync, visited + ) + else: + ctrl_node_ws = None + passthrough_ws: list[Node] = [] + wait_anchor = ctrl_node_ws if ctrl_node_ws is not None else node + # Key under both streams: the wait executes on waiting_stream + # and subsumes the waited-on work used to anchor it. + stream_sync_deps[waiting_stream] = [ + wait_anchor, + *passthrough_ws, + ] + stream_sync_deps[waited_on_stream] = [ + wait_anchor, + *passthrough_ws, + ] + stream_to_nodes[waited_on_stream] = [] + if None in stream_to_nodes: + stream_to_nodes[None] = [] + while ( + getattr(next_node, "_erased", False) and next_node.op != "root" + ): + next_node = next_node.next + node = next_node + continue + + event_index: int = node.args[0] # type: ignore[assignment] + + # synchronize_event blocks the CPU thread, so it acts + # as a barrier across all streams. Collect deps from every + # stream and reset them all afterward. If the event was + # recorded externally, thread the graph inputs through so + # that any post-sync uses depend on the synchronize. + partition_scoped_deps: list[Node] = [] + if node.target is torch.ops.streams.synchronize_event.default: + sync_stream: int | None = event_to_stream.get(event_index) + # Like synchronize_stream/device, this is a CPU-side barrier, + # so fold in still-live cross-stream data accumulated by prior + # sync ops (which cleared stream_to_nodes). + all_stream_deps = _collect_full_barrier_deps( + stream_to_nodes, stream_sync_deps, bwd=is_bwd_node(node) + ) + deps_before_sync = [ + *all_stream_deps, + *full_barrier_forward_deps.get(node, ()), + ] + else: + sync_stream = node.args[1] # type: ignore[assignment] + deps_before_sync = list(stream_to_nodes.get(sync_stream, ())) + partition_scoped_deps = ( + list(stream_sync_forward_deps.get(node, ())) + if node.target is torch.ops.streams.wait_event.default + and event_index not in event_to_anchor + else [] + ) + deps_before_sync.extend(partition_scoped_deps) + # Nodes without explicit stream annotation (custom.stream=None) + # run on the current/default stream. Include them when the sync + # op references a stream, since the unannotated nodes are + # implicitly on that stream. + if None in stream_to_nodes and sync_stream is not None: + deps_before_sync.extend(stream_to_nodes[None]) + # Order this sync op after the prior sync on its own stream + # (and after any full barrier, keyed under None). Without this, + # a record/wait whose stream_to_nodes was reset by an earlier + # sync would have no deps, stay unwrapped, and float as a bare + # side-effectful node -- capturing nothing, the same failure as + # an unanchored synchronize_stream. + prior_syncs = [ + *stream_sync_deps.get(sync_stream, ()), + *stream_sync_deps.get(None, ()), + ] + # A backward sync must anchor only on backward sync nodes: + # depending on a forward control_deps node crosses the fwd/bwd + # boundary onto a node that is neither saveable nor + # recomputable, which makes the min-cut partitioner infeasible. + if is_bwd_node(node): + prior_syncs = [n for n in prior_syncs if is_bwd_node(n)] + deps_before_sync.extend(prior_syncs) + + # For wait_event and synchronize_event, depend on the matching + # record_event's control_deps node (ordering) and thread its + # passthrough getitems through (data edge), so consumers of + # recorded values are rewired through the wait/synchronize + # and the scheduler sees the dependency. + if node.target in ( + torch.ops.streams.wait_event.default, + torch.ops.streams.synchronize_event.default, + ): + if event_index in event_to_anchor: + deps_before_sync = [ + event_to_anchor[event_index], + *deps_before_sync, + ] + if event_index in event_to_passthrough: + deps_before_sync = [ + *deps_before_sync, + *event_to_passthrough[event_index], + ] + elif ( + node.target is torch.ops.streams.record_event.default + and event_index in event_to_anchor + ): + # Re-recording replaces an event's state, but the host-side + # record operations must retain program order even when the + # new record is on an otherwise-empty stream. + deps_before_sync.insert(0, event_to_anchor[event_index]) + + # Deduplicate (preserving order): the folded stream_sync_deps and + # the event's own anchor/passthrough can overlap. + deps_before_sync = list(OrderedSet(deps_before_sync)) + + if deps_before_sync: + found_sync = True + ctrl_node, passthrough = _wrap_sync_node( + gm, + node, + deps_before_sync, + visited, + set(partition_scoped_deps) + if node.target is torch.ops.streams.wait_event.default + else None, + ) + else: + ctrl_node = None + passthrough: list[torch.fx.Node] = [] + + if node.target is torch.ops.streams.record_event.default: + event_to_stream[event_index] = sync_stream + event_to_anchor[event_index] = ( + ctrl_node if ctrl_node is not None else node + ) + event_to_passthrough[event_index] = passthrough + + sync_anchor = ctrl_node if ctrl_node is not None else node + stream_sync_deps[sync_stream] = [sync_anchor, *passthrough] + + # Reset: ops between this sync and the next will accumulate + # fresh. Ordering with prior ops is already enforced because + # their uses were rewired through getitems from control_deps. + # synchronize_event is a full barrier, so its own passthrough + # subsumes all prior per-stream data: clear then re-seed. Key the + # reseed under None (like synchronize_stream/device) so a later + # record/wait on any stream chains after it. + if node.target is torch.ops.streams.synchronize_event.default: + stream_to_nodes.clear() + stream_sync_deps.clear() + stream_sync_deps[None] = [sync_anchor, *passthrough] + else: + stream_to_nodes[sync_stream] = [] + if None in stream_to_nodes: + stream_to_nodes[None] = [] + elif "val" in node.meta: + stream = get_stream(node) + stream_to_nodes.setdefault(stream, []).append(node) + + # _wrap_sync_node may erase nodes after the sync (e.g. + # _expand_dict_returning_deps erases getitems). Skip erased nodes + # so we don't re-process a dead node into stream_to_nodes. + while getattr(next_node, "_erased", False) and next_node.op != "root": + next_node = next_node.next + node = next_node + + if found_sync: + gm.recompile() diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_codegen.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..3f31e5d29d6d6da9573fbc100dca328f9adb8974 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_codegen.py @@ -0,0 +1,623 @@ +""" +Codegen for AOTDispatchSubclassWrapper. + +Generates a Python function that replaces the data-driven +runtime_unwrap_tensor_subclasses / wrap_tensor_subclasses loop with +a straight-line function where all metadata (indices, attr names, +subclass types, symint positions) is baked in at compile time. +""" + +import functools +import keyword +from collections.abc import Callable, Iterable +from typing import cast, TYPE_CHECKING + +from torch import SymInt + +from .codegen import _compile_and_exec_source, PySourceBuilder +from .schemas import ActInputPaths, OpaqueMeta, PlainTensorMeta, SubclassCreationMeta +from .utils import import_async_collective_tensor_type + + +if TYPE_CHECKING: + from torch.distributed._functional_collectives import AsyncCollectiveTensor + + +def _is_symint_placeholder(x: None | int | SymInt) -> bool: + """Check whether a size/stride entry is symbolic and needs a runtime value. + + Works both before make_runtime_safe() (entries are SymInt) and after + (symbolic entries replaced with None, nested ints with -1). + """ + if x is None: + return True + if isinstance(x, SymInt) and not x.node.is_nested_int(): + return True + return False + + +def _compute_placeholders(outer: Iterable[None | int | SymInt]) -> list[bool]: + return [_is_symint_placeholder(s) for s in outer] + + +def _safe_attr_access(var: str, attr: str) -> str: + if attr.isidentifier() and not keyword.iskeyword(attr): + return f"{var}.{attr}" + return f"getattr({var}, {attr!r})" + + +class _OutputWrapState: + def __init__( + self, + *, + remaining_min_count: int, + remaining_max_count: int, + optional_symint_check: str, + ) -> None: + self.remaining_min_count = remaining_min_count + self.remaining_max_count = remaining_max_count + self.optional_symint_check = optional_symint_check + + def mark_required(self) -> None: + self.remaining_min_count -= 1 + self.remaining_max_count -= 1 + + def mark_optional(self) -> None: + self.remaining_max_count -= 1 + + +def _maybe_wait_async_collective_tensor( + x: object, + AsyncCollectiveTensor: type["AsyncCollectiveTensor"], +) -> object: + """Wait on ACT values and leave all other runtime inputs unchanged.""" + if isinstance(x, AsyncCollectiveTensor): + return cast("AsyncCollectiveTensor", x).trigger_wait() + return x + + +def _codegen_unwrap_subclass( + state: PySourceBuilder, + meta: SubclassCreationMeta, + var: str, + indent: int = 1, + include_symints: bool = True, + act_input_paths: set[tuple[str, ...]] | None = None, + act_wait_fn: str | None = None, +) -> None: + """Emit code to recursively unwrap a single subclass input.""" + act_input_paths = act_input_paths or set() + + def emit_plain_tensor_symints(var: str, meta: PlainTensorMeta) -> None: + if not include_symints: + return + + if any(meta.size_symbol_placeholders): + size_var = state.fresh_name("_size") + state.emit(f"{size_var} = {var}.size()", indent=indent) + for i, is_sym in enumerate(meta.size_symbol_placeholders): + if is_sym: + state.emit(f"unwrapped_args.append({size_var}[{i}])", indent=indent) + + if any(meta.stride_symbol_placeholders): + stride_var = state.fresh_name("_stride") + state.emit(f"{stride_var} = {var}.stride()", indent=indent) + for i, is_sym in enumerate(meta.stride_symbol_placeholders): + if is_sym: + state.emit( + f"unwrapped_args.append({stride_var}[{i}])", indent=indent + ) + + for attr, attr_meta in meta.attrs.items(): + attr_expr = _safe_attr_access(var, attr) + attr_act_input_paths = { + path[1:] for path in act_input_paths if path and path[0] == attr + } + match attr_meta: + case PlainTensorMeta(): + if attr_act_input_paths: + if attr_act_input_paths != {()}: + raise AssertionError( + f"ACT path for {attr} continues past a leaf meta" + ) + if act_wait_fn is None: + raise AssertionError("missing ACT wait function") + resolved_var = state.fresh_name("_resolved") + state.emit( + f"{resolved_var} = {act_wait_fn}({attr_expr})", + indent=indent, + ) + attr_expr = resolved_var + state.emit(f"unwrapped_args.append({attr_expr})", indent=indent) + emit_plain_tensor_symints(attr_expr, attr_meta) + case OpaqueMeta(): + if attr_act_input_paths: + if attr_act_input_paths != {()}: + raise AssertionError( + f"ACT path for {attr} continues past a leaf meta" + ) + if act_wait_fn is None: + raise AssertionError("missing ACT wait function") + resolved_var = state.fresh_name("_resolved") + state.emit( + f"{resolved_var} = {act_wait_fn}({attr_expr})", + indent=indent, + ) + state.emit(f"unwrapped_args.append({resolved_var})", indent=indent) + else: + state.emit( + f"unwrapped_args.append({attr_expr})", + indent=indent, + ) + case SubclassCreationMeta(): + if () in attr_act_input_paths: + raise AssertionError(f"ACT path for {attr} stops at subclass meta") + inner_var = state.fresh_name("_inner") + state.emit(f"{inner_var} = {attr_expr}", indent=indent) + _codegen_unwrap_subclass( + state, + attr_meta, + inner_var, + indent=indent, + include_symints=include_symints, + act_input_paths=attr_act_input_paths, + act_wait_fn=act_wait_fn, + ) + + if include_symints: + size_placeholders = _compute_placeholders(meta.outer_size) + stride_placeholders = _compute_placeholders(meta.outer_stride) + if any(size_placeholders) or any(stride_placeholders): + size_var = state.fresh_name("_size") + state.emit(f"{size_var} = {var}.size()", indent=indent) + for i, is_sym in enumerate(size_placeholders): + if is_sym: + state.emit(f"unwrapped_args.append({size_var}[{i}])", indent=indent) + + stride_var = state.fresh_name("_stride") + state.emit(f"{stride_var} = {var}.stride()", indent=indent) + for i, is_sym in enumerate(stride_placeholders): + if is_sym: + state.emit( + f"unwrapped_args.append({stride_var}[{i}])", indent=indent + ) + + +def _concrete_value(val: None | int | SymInt) -> int: + """Get the concrete int value for a non-symbolic size/stride entry. + + Used for entries that are NOT symbolic placeholders, meaning they are + concrete ints or nested ints (represented as -1 after make_runtime_safe). + """ + if isinstance(val, int): + return val + # Before make_runtime_safe: nested ints are SymInts; use -1 as dummy. + # After make_runtime_safe: they're already -1. + if isinstance(val, SymInt) and val.node.is_nested_int(): + return -1 + raise AssertionError(f"Expected concrete int, got {type(val)}: {val}") + + +def _is_optional_symint_output(val: object) -> bool: + return isinstance(val, (int, SymInt)) + + +def _codegen_wrap_subclass( + state: PySourceBuilder, + meta: SubclassCreationMeta, + output_state: _OutputWrapState, +) -> str: + """Emit code to reconstruct one subclass output. Returns the variable name.""" + inner_dict_var = state.fresh_name("_out_inner") + entries: list[str] = [] + attr_exprs: dict[str, str] = {} + + for attr, attr_meta in meta.attrs.items(): + match attr_meta: + case PlainTensorMeta(): + attr_expr = state.fresh_name("_out_attr") + state.emit(f"{attr_expr} = unwrapped_outs[_out_idx]") + state.emit("_out_idx += 1") + output_state.mark_required() + _emit_optional_plain_tensor_symint_skips(state, output_state, attr_meta) + case OpaqueMeta(): + attr_expr = state.fresh_name("_out_attr") + state.emit(f"{attr_expr} = unwrapped_outs[_out_idx]") + state.emit("_out_idx += 1") + output_state.mark_required() + case SubclassCreationMeta(): + attr_expr = _codegen_wrap_subclass(state, attr_meta, output_state) + attr_exprs[attr] = attr_expr + entries.append(f"{attr!r}: {attr_expr}") + + state.emit(f"{inner_dict_var} = {{{', '.join(entries)}}}") + + # Reconstruct outer_size and outer_stride + size_placeholders = _compute_placeholders(meta.outer_size) + stride_placeholders = _compute_placeholders(meta.outer_stride) + + def _build_tuple( + outer: Iterable[None | int | SymInt], placeholders: list[bool] + ) -> str: + parts: list[str] = [] + for val, is_sym in zip(outer, placeholders): + if is_sym: + sym_expr = state.fresh_name("_out_sym") + state.emit(f"{sym_expr} = unwrapped_outs[_out_idx]") + state.emit("_out_idx += 1") + output_state.mark_required() + parts.append(sym_expr) + else: + parts.append(repr(_concrete_value(val))) + if len(parts) == 1: + return f"({parts[0]},)" + return f"({', '.join(parts)})" + + def _consume_optional_placeholders(placeholders: list[bool]) -> None: + for is_sym in placeholders: + if is_sym: + _emit_optional_symint_skip(state, output_state) + + outer_size_from_attr = meta.outer_size_from_attr + outer_stride_from_attr = meta.outer_stride_from_attr + if outer_size_from_attr is not None: + size_expr = f"{attr_exprs[outer_size_from_attr]}.size()" + _consume_optional_placeholders(size_placeholders) + else: + size_expr = _build_tuple(meta.outer_size, size_placeholders) + + if outer_stride_from_attr is not None: + stride_expr = f"{attr_exprs[outer_stride_from_attr]}.stride()" + _consume_optional_placeholders(stride_placeholders) + else: + stride_expr = _build_tuple(meta.outer_stride, stride_placeholders) + + type_name = state.add_global( + state.fresh_name("_subclass_type"), + meta.original_subclass_type or type(meta.original_subclass), + ) + meta_name = state.add_global(state.fresh_name("_meta"), meta.meta) + + result_var = state.fresh_name("_out") + state.emit( + f"{result_var} = {type_name}.__tensor_unflatten__(" + f"{inner_dict_var}, {meta_name}, {size_expr}, {stride_expr})" + ) + return result_var + + +def _count_output_args( + meta: PlainTensorMeta | SubclassCreationMeta, + *, + include_subclass_symints: bool, +) -> int: + if isinstance(meta, PlainTensorMeta): + return meta.arg_count if include_subclass_symints else 1 + + total = 0 + for attr_meta in meta.attrs.values(): + if isinstance(attr_meta, OpaqueMeta): + total += 1 + else: + total += _count_output_args( + attr_meta, include_subclass_symints=include_subclass_symints + ) + + if include_subclass_symints: + total += sum(_compute_placeholders(meta.outer_size)) + total += sum(_compute_placeholders(meta.outer_stride)) + else: + if meta.outer_size_from_attr is None: + total += sum(_compute_placeholders(meta.outer_size)) + if meta.outer_stride_from_attr is None: + total += sum(_compute_placeholders(meta.outer_stride)) + return total + + +def _emit_optional_symint_skip( + state: PySourceBuilder, + output_state: _OutputWrapState, +) -> None: + remaining_var = state.fresh_name("_remaining_outs") + include_var = state.fresh_name("_include_symints") + later_min_count = output_state.remaining_min_count + later_max_count = output_state.remaining_max_count - 1 + max_fits = ( + f"{remaining_var} - 1 >= {later_min_count} and " + f"{remaining_var} - 1 <= {later_max_count}" + ) + min_fits = ( + f"{remaining_var} >= {later_min_count} and {remaining_var} <= {later_max_count}" + ) + + state.emit(f"{remaining_var} = _num_wrapped_outs - _out_idx") + state.emit( + f"{include_var} = ({max_fits}) and " + f"{output_state.optional_symint_check}(unwrapped_outs[_out_idx])" + ) + state.emit( + f"assert {include_var} or ({min_fits}), " + "'could not match output layout with optional SymInt outputs'" + ) + state.emit(f"if {include_var}:") + state.emit("_out_idx += 1", indent=2) + output_state.mark_optional() + + +def _emit_optional_plain_tensor_symint_skips( + state: PySourceBuilder, + output_state: _OutputWrapState, + meta: PlainTensorMeta, +) -> None: + for is_sym in meta.size_symbol_placeholders: + if is_sym: + _emit_optional_symint_skip(state, output_state) + for is_sym in meta.stride_symbol_placeholders: + if is_sym: + _emit_optional_symint_skip(state, output_state) + + +def _emit_output_wrapping( + state: PySourceBuilder, + out_metas: list[PlainTensorMeta | SubclassCreationMeta], + num_fw_outs_saved_for_bw: int | None, +) -> tuple[list[str], int]: + """Emit wrapping code for output metas. + + Returns (result_exprs, num_args_tallied) where result_exprs are Python + expression strings referencing each wrapped output. + """ + result_exprs: list[str] = [] + num_args_tallied = 0 + saved_for_bw = num_fw_outs_saved_for_bw or 0 + min_counts = [ + _count_output_args(meta, include_subclass_symints=False) for meta in out_metas + ] + max_counts = [ + _count_output_args(meta, include_subclass_symints=True) for meta in out_metas + ] + min_wrapped_outputs = sum(min_counts) + max_wrapped_outputs = sum(max_counts) + + optional_symint_check = ( + state.add_global( + state.fresh_name("_is_optional_symint_output"), + _is_optional_symint_output, + ) + if min_wrapped_outputs != max_wrapped_outputs + else "" + ) + state.emit("_out_idx = 0") + if saved_for_bw: + state.emit(f"_num_wrapped_outs = len(unwrapped_outs) - {saved_for_bw}") + else: + state.emit("_num_wrapped_outs = len(unwrapped_outs)") + if min_wrapped_outputs != max_wrapped_outputs: + state.emit( + "assert " + f"{min_wrapped_outputs} <= _num_wrapped_outs <= {max_wrapped_outputs}, " + f"f'expected between {min_wrapped_outputs} and {max_wrapped_outputs} " + "wrapped outputs, got {_num_wrapped_outs}'" + ) + else: + state.emit( + f"assert _num_wrapped_outs == {max_wrapped_outputs}, " + f"f'expected {max_wrapped_outputs} wrapped outputs, " + "got {_num_wrapped_outs}'" + ) + + output_state = _OutputWrapState( + remaining_min_count=min_wrapped_outputs, + remaining_max_count=max_wrapped_outputs, + optional_symint_check=optional_symint_check, + ) + for meta in out_metas: + if isinstance(meta, PlainTensorMeta): + out_expr = state.fresh_name("_out_plain") + state.emit(f"{out_expr} = unwrapped_outs[_out_idx]") + state.emit("_out_idx += 1") + output_state.mark_required() + _emit_optional_plain_tensor_symint_skips(state, output_state, meta) + result_exprs.append(out_expr) + num_args_tallied += meta.arg_count + else: + result_var = _codegen_wrap_subclass(state, meta, output_state) + result_exprs.append(result_var) + num_args_tallied += meta.arg_count + + if output_state.remaining_min_count != 0 or output_state.remaining_max_count != 0: + raise AssertionError( + "output wrapping counts did not balance: " + f"{output_state.remaining_min_count}, " + f"{output_state.remaining_max_count}" + ) + state.emit( + "assert _out_idx == _num_wrapped_outs, " + "f'wrapped {_out_idx} outputs, expected {_num_wrapped_outs}'" + ) + return result_exprs, num_args_tallied + + +def _emit_input_unwrapping( + state: PySourceBuilder, + inp_metas: list[PlainTensorMeta | SubclassCreationMeta], + frozen_inp_indices: frozenset[int] = frozenset(), + include_symints: bool = True, + act_input_paths_by_input: dict[int, set[tuple[str, ...]]] | None = None, + act_wait_fn: str | None = None, +) -> None: + """Emit unwrapping code for input metas into unwrapped_args. + + Caller must have already emitted ``unwrapped_args = []``. + """ + act_input_paths_by_input = act_input_paths_by_input or {} + for i, meta in enumerate(inp_metas): + input_act_paths = act_input_paths_by_input.get(i, set()) + if isinstance(meta, PlainTensorMeta): + if input_act_paths: + if input_act_paths != {()}: + raise AssertionError( + f"ACT path for input {i} continues past a plain meta" + ) + if act_wait_fn is None: + raise AssertionError("missing ACT wait function") + state.emit(f"unwrapped_args.append({act_wait_fn}(args[{i}]))") + else: + state.emit(f"unwrapped_args.append(args[{i}])") + elif i in frozen_inp_indices: + # Frozen by inductor freezing: constant already baked into graph. + state.emit("unwrapped_args.append(None)") + else: + if () in input_act_paths: + raise AssertionError(f"ACT path for input {i} stops at subclass meta") + inp_var = state.fresh_name("_inp") + type_name = state.add_global( + state.fresh_name("_expected_type"), + meta.original_subclass_type or type(meta.original_subclass), + ) + state.emit(f"{inp_var} = args[{i}]") + state.emit( + f"assert type({inp_var}) is {type_name}, " + f"f'expected {{{type_name}}}, got {{type({inp_var})}}'", + ) + _codegen_unwrap_subclass( + state, + meta, + inp_var, + indent=1, + include_symints=include_symints, + act_input_paths=input_act_paths, + act_wait_fn=act_wait_fn, + ) + + +def _codegen_subclass_wrapper_source( + inp_metas: list[PlainTensorMeta | SubclassCreationMeta], + out_metas: list[PlainTensorMeta | SubclassCreationMeta], + num_fw_outs_saved_for_bw: int | None, + frozen_inp_indices: frozenset[int] = frozenset(), + act_input_paths: ActInputPaths | None = None, +) -> tuple[str, dict[str, object]]: + """Generate source and globals for a subclass wrapper. + + Returns (source, globals_dict). The globals_dict will NOT contain + ``compiled_fn`` — the caller is responsible for adding it before exec. + """ + state = PySourceBuilder() + + state.emit("def inner_fn(args):", indent=0) + + act_input_paths_by_input: dict[int, set[tuple[str, ...]]] = {} + act_wait_fn = None + if act_input_paths: + AsyncCollectiveTensor = import_async_collective_tensor_type() + act_wait_fn = state.add_global( + state.fresh_name("_maybe_wait_act"), + functools.partial( + _maybe_wait_async_collective_tensor, + AsyncCollectiveTensor=AsyncCollectiveTensor, + ), + ) + for i, attr_path in act_input_paths: + act_input_paths_by_input.setdefault(i, set()).add(attr_path) + + # --- Input unwrapping --- + state.emit("unwrapped_args = []") + _emit_input_unwrapping( + state, + inp_metas, + frozen_inp_indices=frozen_inp_indices, + act_input_paths_by_input=act_input_paths_by_input, + act_wait_fn=act_wait_fn, + ) + + # Pass through any trailing args not covered by inp_metas + # (e.g. rng seed/offset added by FunctionalizedRngRuntimeWrapper). + num_inp_metas = len(inp_metas) + state.emit(f"unwrapped_args.extend(args[{num_inp_metas}:])") + state.emit("args.clear()") + + # --- Call compiled function --- + state.emit("unwrapped_outs = compiled_fn(unwrapped_args)") + + # --- Output wrapping --- + result_exprs, _ = _emit_output_wrapping(state, out_metas, num_fw_outs_saved_for_bw) + result_tuple = f"({', '.join(result_exprs)},)" if result_exprs else "()" + if num_fw_outs_saved_for_bw is not None: + state.emit( + f"_activation_start = len(unwrapped_outs) - {num_fw_outs_saved_for_bw}" + ) + state.emit(f"return {result_tuple} + tuple(unwrapped_outs[_activation_start:])") + else: + state.emit(f"return {result_tuple}") + + source = state.getvalue() + return source, state.globals + + +def _codegen_subclass_wrap_source( + out_metas: list[PlainTensorMeta | SubclassCreationMeta], +) -> tuple[str, dict[str, object]]: + """Generate source for wrapping flat outputs into subclasses. + + Used for the backward epilogue. Shares output-wrapping logic with + _codegen_subclass_wrapper_source via _emit_output_wrapping. + """ + state = PySourceBuilder() + state.emit("def wrap_fn(unwrapped_outs):", indent=0) + result_exprs, _ = _emit_output_wrapping( + state, out_metas, num_fw_outs_saved_for_bw=None + ) + result_tuple = f"({', '.join(result_exprs)},)" if result_exprs else "()" + state.emit(f"return {result_tuple}") + source = state.getvalue() + return source, state.globals + + +def codegen_backward_subclass_fns( + grad_input_metas: list[PlainTensorMeta | SubclassCreationMeta] | None = None, +) -> tuple[Callable[..., object], Callable[..., object] | None]: + """Generate codegen'd unwrap and wrap functions for the backward pass. + + Returns (unwrap_fn, wrap_fn). unwrap_fn is used by the backward prologue + to unwrap non-tangent subclass inputs (always an identity in AOT dispatch + since the compiled forward operates on unwrapped inner tensors). wrap_fn + is used by the backward epilogue to wrap flat grad inputs back into + subclasses; it is None when grad_input_metas is None. + """ + source = "def unwrap_fn(args):\n return list(args)" + globals_dict: dict[str, object] = {} + unwrap_fn = _compile_and_exec_source( + source, globals_dict, "unwrap_fn", "backward_subclass_unwrap" + ) + + wrap_fn = None + if grad_input_metas is not None: + wrap_source, wrap_globals = _codegen_subclass_wrap_source(grad_input_metas) + wrap_fn = _compile_and_exec_source( + wrap_source, wrap_globals, "wrap_fn", "backward_subclass_wrapper" + ) + + return unwrap_fn, wrap_fn + + +def codegen_subclass_wrapper( + compiled_fn: Callable[..., object], + inp_metas: list[PlainTensorMeta | SubclassCreationMeta], + out_metas: list[PlainTensorMeta | SubclassCreationMeta], + num_fw_outs_saved_for_bw: int | None, + frozen_inp_indices: frozenset[int] = frozenset(), + act_input_paths: ActInputPaths | None = None, +) -> Callable[..., object]: + """Generate a specialized wrapper function for subclass unwrap/wrap.""" + source, globals_dict = _codegen_subclass_wrapper_source( + inp_metas, + out_metas, + num_fw_outs_saved_for_bw, + frozen_inp_indices, + act_input_paths=act_input_paths, + ) + globals_dict["compiled_fn"] = compiled_fn + return _compile_and_exec_source( + source, globals_dict, "inner_fn", "subclass_wrapper", wrapped_fn=compiled_fn + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_parametrization.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_parametrization.py new file mode 100644 index 0000000000000000000000000000000000000000..f32087850cf2d2693d1cd36bf23fe22808766b29 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_parametrization.py @@ -0,0 +1,140 @@ +from __future__ import annotations + +import dataclasses +import itertools +from typing import Any, TYPE_CHECKING + +import torch +from torch._custom_class_base import CustomClassBase +from torch._library.opaque_object import is_opaque_symbolic_type +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + +from .schemas import OpaqueMeta + + +if TYPE_CHECKING: + from collections.abc import Iterable + + +# This is technically very similar to SubclassCreatingMeta +# in aot_autograd, but we don't need all the stuff in there +# so just recreated a new dataclass. +@dataclasses.dataclass +class SubclassCreationMeta: + start_idx: int + num_tensors: int + class_type: Any + # None means the attr is a plain tensor (base case of recursion) + attrs: dict[str, SubclassCreationMeta | OpaqueMeta | None] + metadata: Any + outer_size: Iterable[None | int | torch.SymInt] + outer_stride: Iterable[None | int | torch.SymInt] + + +class UnwrapTensorSubclass(torch.nn.Module): + def forward(self, *tensors) -> torch.Tensor: # type: ignore[no-untyped-def] + todo: list[torch.Tensor | CustomClassBase] = list(tensors) + + def _unwrap_tensor_subclasses(subclass_meta, tensors, offset): # type: ignore[no-untyped-def] + if subclass_meta is None: + return tensors[offset], offset + 1 + inner_tensors = {} + for attr, meta in subclass_meta.attrs.items(): + if isinstance(meta, OpaqueMeta): + inner_tensors[attr] = tensors[offset] + offset += 1 + else: + built_tensor, offset = _unwrap_tensor_subclasses( + meta, tensors, offset + ) + inner_tensors[attr] = built_tensor + rebuilt = subclass_meta.class_type.__tensor_unflatten__( + inner_tensors, + subclass_meta.metadata, + subclass_meta.outer_size, + subclass_meta.outer_stride, + ) + return rebuilt, offset + + return _unwrap_tensor_subclasses(self.subclass_meta, todo, 0)[0] + + def right_inverse( + self, tensor: torch.Tensor + ) -> list[torch.Tensor | CustomClassBase]: + if type(tensor) is torch.Tensor: + raise AssertionError("tensor must be a subclass, not torch.Tensor") + plain_tensors: list[torch.Tensor | CustomClassBase] = [] + + def _create_subclass_meta(tensor, idx, plain_tensor_container): # type: ignore[no-untyped-def] + if type(tensor) is torch.Tensor: + plain_tensor_container.append(tensor) + return None, idx + 1 + inner_tensors_attrnames, metadata = tensor.__tensor_flatten__() # type: ignore[attr-defined] + new_idx = idx + attr_to_meta: dict[str, SubclassCreationMeta | OpaqueMeta | None] = {} + for attr in inner_tensors_attrnames: + val = getattr(tensor, attr) + match val: + case CustomClassBase(): + if not is_opaque_symbolic_type(type(val)): + raise ValueError( + f"{type(val).__name__!r} found in tensor attrs of " + f"{type(tensor).__name__}.__tensor_flatten__(). " + "Only tensors and reference-type opaques are allowed " + "in tensor attrs." + ) + attr_to_meta[attr] = OpaqueMeta() + plain_tensor_container.append(val) + new_idx += 1 + case torch.Tensor(): + subclass_meta, new_idx = _create_subclass_meta( + val, new_idx, plain_tensor_container + ) + attr_to_meta[attr] = subclass_meta + case _: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(val)}" + ) + return ( + SubclassCreationMeta( + start_idx=idx, + num_tensors=new_idx - idx, + class_type=type(tensor), + attrs=attr_to_meta, + metadata=metadata, + outer_size=tensor.size(), + outer_stride=tensor.stride(), + ), + new_idx, + ) + + self.subclass_meta = _create_subclass_meta(tensor, 0, plain_tensors)[0] + return plain_tensors + + +def unwrap_tensor_subclass_parameters(module: torch.nn.Module) -> torch.nn.Module: + """ + Model transformation that replaces all the parameters that are subclasses to plain tensors. + This reduces runtime overhead of flattening/unflattening the parameters. + + This transformation adds parametrization with `torch.nn.utils.parametrize`. + The FQNs of the subclass parameters will be changed and state_dict will become incompatible with the original model. + E.g. + Original model state_dict: {"p1": torch.testing._internal.TwoTensor} + becomes: {"parametrizations.p2.original0": torch.Tensor, "parametrizations.p2.original1": torch.Tensor} + + """ + for name, tensor in itertools.chain( + list(module.named_parameters(recurse=False)), + # pyrefly: ignore [bad-argument-type, no-matching-overload] + list(module.named_buffers(recurse=False)), + ): + if is_traceable_wrapper_subclass(tensor): + torch.nn.utils.parametrize.register_parametrization( + module, name, UnwrapTensorSubclass() + ) + + for child in module.children(): + unwrap_tensor_subclass_parameters(child) + + return module diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9361a5a8ea4dc2b9bb8daeef82fd7324b882cbb5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/subclass_utils.py @@ -0,0 +1,784 @@ +""" +This file contains utilities for tracing through __torch_dispatch__ based tensor subclasses and modes. +AOTAutograd's responsibility is to trace through all pytorch capabilities that live in the pytorch dispatcher, +and this includes tensor subclasses that implement __torch_dispatch__. +""" + +import collections +from collections.abc import Callable, Iterable, Sequence +from typing import Any, TypeGuard, TypeVar + +import torch +import torch.utils._pytree as pytree +from torch import SymInt, Tensor +from torch._custom_class_base import CustomClassBase +from torch._library.fake_class_registry import maybe_unwrap_fake_script_object +from torch._library.opaque_object import is_opaque_symbolic_type +from torch._subclasses.fake_tensor import get_plain_tensors +from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq +from torch.types import IntLikeType +from torch.utils._python_dispatch import ( + is_traceable_wrapper_subclass, + TraceableWrapperSubclass, +) + +from .descriptors import ( + AOTInput, + AOTOutput, + DummyAOTInput, + SubclassGetAttrAOTInput, + SubclassGetAttrAOTOutput, + SubclassSizeAOTInput, + SubclassSizeAOTOutput, + SubclassStrideAOTInput, + SubclassStrideAOTOutput, +) +from .schemas import ( + FakifiedFlatArgs, + FxValue, + MutationType, + OpaqueMeta, + PlainTensorMeta, + SubclassCreationMeta, + ViewAndMutationMeta, +) +from .utils import strict_zip + + +zip = strict_zip + +T = TypeVar("T", bound=torch.Tensor) + + +def requires_subclass_dispatch( + args: FakifiedFlatArgs, fw_metadata: ViewAndMutationMeta +) -> bool: + args_flattened = pytree.arg_tree_leaves(*args) + any_subclass_args = any( + is_traceable_wrapper_subclass(x) + for x in args_flattened + if isinstance(x, Tensor) + ) + from torch._functorch._aot_autograd.schemas import SubclassCreationMeta + + any_subclass_outputs = any( + type(x) is SubclassCreationMeta for x in fw_metadata.subclass_fw_graph_out_meta + ) + # This tells us whether or not we need to perform any unwrapping/wrapping of tensor subclasses at runtime. + return bool(any_subclass_args or any_subclass_outputs) + + +from .schemas import MemoryFormatMeta + + +def maybe_suggest_memory_format( + t: Tensor, with_memory_format: bool +) -> MemoryFormatMeta | None: + if not with_memory_format: + return None + + return MemoryFormatMeta.from_tensor(t) + + +def _safe_metadata_eq( + outer: Iterable[IntLikeType], + inner: Iterable[IntLikeType], +) -> bool: + return guard_or_false(sym_eq(tuple(outer), tuple(inner))) + + +def _find_attr_matching_outer_metadata( + a: Tensor, + inner_keys: Sequence[str], + *, + metadata_fn: Callable[[Tensor], Iterable[IntLikeType]], +) -> str | None: + tensor_attrs = [key for key in inner_keys if isinstance(getattr(a, key), Tensor)] + if not tensor_attrs: + return None + + outer_metadata = tuple(metadata_fn(a)) + # Only use an attr as the runtime source when every tensor attr agrees + # with the wrapper metadata; otherwise there is no single attr to trust. + if all( + _safe_metadata_eq(outer_metadata, metadata_fn(getattr(a, key))) + for key in tensor_attrs + ): + return tensor_attrs[0] + return None + + +def _symint_placeholders(lst: Iterable[IntLikeType]) -> tuple[bool, ...]: + return tuple(isinstance(s, SymInt) and not s.node.is_nested_int() for s in lst) + + +def get_subclass_typing_container( + tensor_subclass: torch.Tensor, +) -> dict[type[torch.Tensor], list[type[torch.Tensor]]]: + """ + Given a subclass, returns a recursive dictionary mapping each + inner tensors to its subclass types. + """ + + def _get_types_for_subclass(tensor_subclass: torch.Tensor) -> None: + if not is_traceable_wrapper_subclass(tensor_subclass): + return + tracker[type(tensor_subclass)].append(tensor_subclass) + inner_keys, _ = tensor_subclass.__tensor_flatten__() + for key in inner_keys: + match getattr(tensor_subclass, key): + case torch.Tensor() as inner_value: + _get_types_for_subclass(inner_value) + case CustomClassBase(): + pass + case unexpected: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(unexpected)}" + ) + + tracker: dict[Any, list[Any]] = collections.defaultdict(list) + _get_types_for_subclass(tensor_subclass) + return tracker + + +def create_subclass_metadata( + a: Any, + start_idx: int, + count_symints: bool, + with_memory_format: bool = False, +) -> tuple[Any, int]: + if not is_traceable_wrapper_subclass(a): + size_symbol_placeholders = ( + _symint_placeholders(a.size()) if count_symints else () + ) + stride_symbol_placeholders = ( + _symint_placeholders(a.stride()) if count_symints else () + ) + meta = PlainTensorMeta( + start_idx + 1, + memory_format=maybe_suggest_memory_format(a, with_memory_format), + size_symbol_placeholders=size_symbol_placeholders, + stride_symbol_placeholders=stride_symbol_placeholders, + ) + return ( + meta, + start_idx + meta.arg_count, + ) + + inner_keys, metadata = a.__tensor_flatten__() + new_start_idx = start_idx + attrs: dict[str, SubclassCreationMeta | PlainTensorMeta | OpaqueMeta] = {} + + for key in inner_keys: + inner_value = getattr(a, key) + match inner_value: + case CustomClassBase(): + # During tracing, opaques are wrapped in FakeScriptObject; + # unwrap to check the real type. + real_type = type(maybe_unwrap_fake_script_object(inner_value)) + if not is_opaque_symbolic_type(real_type): + raise RuntimeError( + f"{real_type.__name__!r} found in tensor attrs of " + f"{type(a).__name__}.__tensor_flatten__(). " + "Only tensors and reference-type opaques are allowed " + "in tensor attrs." + ) + attrs[key] = OpaqueMeta() + new_start_idx += 1 + case Tensor(): + new_subclass_meta, new_start_idx = create_subclass_metadata( + inner_value, + new_start_idx, + count_symints=count_symints, + with_memory_format=with_memory_format, + ) + attrs[key] = new_subclass_meta + case _: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(inner_value)}" + ) + + # It *must* be because is_traceable_wrapper_subclass() - but mypy is not smart. + if not isinstance(a, Tensor): + raise AssertionError(f"expected Tensor, got {type(a)}") + + new_start_idx = ( + new_start_idx + + count_symints * len(enumerate_filter_symints(a.size())) + + count_symints * len(enumerate_filter_symints(a.stride())) + ) + + return ( + SubclassCreationMeta( + flat_tensor_start_idx=start_idx, + arg_count=new_start_idx - start_idx, + included_subclass_symints=count_symints, + attrs=attrs, + meta=metadata, + outer_size=a.size(), # type: ignore[attr-defined, arg-type] + outer_stride=a.stride(), # type: ignore[arg-type] + original_subclass=a, + memory_format=maybe_suggest_memory_format(a, with_memory_format), + outer_size_from_attr=_find_attr_matching_outer_metadata( + a, inner_keys, metadata_fn=lambda t: t.size() + ), + outer_stride_from_attr=_find_attr_matching_outer_metadata( + a, inner_keys, metadata_fn=lambda t: t.stride() + ), + ), + new_start_idx, + ) + + +# Given a flat list of arguments, some of which may be tensor subclasses, +# computes metadata about "how to reconstruct the current list of subclasses, +# if we were given their flattened dense tensors instead" +def create_subclass_meta( + curr_args: list[Any] | tuple[Any, ...], + *, + count_symints: bool = True, + with_memory_format: bool = False, +) -> list[PlainTensorMeta | SubclassCreationMeta]: + idx = 0 + infos: list[PlainTensorMeta | SubclassCreationMeta] = [] + for a in curr_args: + if is_traceable_wrapper_subclass(a): + if not isinstance(a, Tensor): + raise AssertionError( + f"expected Tensor for traceable wrapper subclass, got {type(a)}" + ) + start_idx = idx + subclass_meta, _ = create_subclass_metadata( + a, + start_idx, + count_symints=count_symints, + with_memory_format=with_memory_format, + ) + infos.append(subclass_meta) + cnt = subclass_meta.arg_count + else: + infos.append( + PlainTensorMeta( + idx, + memory_format=maybe_suggest_memory_format(a, with_memory_format), + ) + ) + cnt = 1 + idx += cnt + return infos + + +def enumerate_filter_symints(lst: Iterable[IntLikeType]) -> list[tuple[int, SymInt]]: + # Capture all SymInts from the iterable. + def symint_check(s: IntLikeType) -> TypeGuard[SymInt]: + return isinstance(s, SymInt) and not s.node.is_nested_int() + + return [(i, s) for i, s in enumerate(lst) if symint_check(s)] + + +def compute_symint_placeholders(lst: Iterable[None | int | SymInt]) -> list[bool]: + # Non-nested symints are replaced with None in `make_runtime_safe()` + return [s is None for s in lst] + + +# Intended to make it easier to define function that is +# either (AOTInput -> AOTInput) or (AOTOutput -> AOTOutput) +# but not the other combos +AOTDescriptor = TypeVar("AOTDescriptor", AOTInput, AOTOutput) + + +# This function takes in a pytree of arguments and unwraps any tensor +# subclasses. +# +# NOTE: The reason for "append_symints": +# +# * At compile time: we append extra symint args when unwrapping primals +# (but not tangents, because they should always share symints with primals). +# We also append extra symints when unwrapping the subclass outputs of the +# traced function, so we can return them as extra outputs +# +# * At runtime: we similarly append subclass sizes when we unwrap subclass +# primals (but not tangents) on entry to the forward. See the runtime version of +# this function below. +def unwrap_tensor_subclasses( + wrapped_args: list[FxValue], + wrapped_args_descs: Sequence[AOTDescriptor], + *, + append_symints: bool, +) -> tuple[list[FxValue], list[AOTDescriptor]]: + def _maybe_fakeify_opaque(v: Any) -> Any: + # Registered opaque types need to be wrapped as FakeScriptObject for + # compile-time FX tracing (proxy slot tracking, hashability, etc.). + if isinstance(v, CustomClassBase): + from torch._guards import detect_fake_mode + from torch._library.fake_class_registry import maybe_to_fake_obj + from torch._library.opaque_object import is_custom_class + + fake_mode = detect_fake_mode() + if fake_mode is not None and is_custom_class(type(v)): + return maybe_to_fake_obj(fake_mode, v) + return v + + def flatten_subclass( + t: FxValue, + desc: AOTDescriptor, + *, + out: tuple[list[FxValue], list[AOTDescriptor]], + ) -> None: + # unwrap a subclass into plain tensors and their size/stride if "append_symint" + # is True + if not is_traceable_wrapper_subclass(t): + out[0].append(_maybe_fakeify_opaque(t)) + out[1].append(desc) + if ( + append_symints + and isinstance(t, Tensor) + and isinstance( + desc, (SubclassGetAttrAOTInput, SubclassGetAttrAOTOutput) + ) + ): + sizes = enumerate_filter_symints(t.size()) + strides = enumerate_filter_symints(t.stride()) + out[0].extend(s for _, s in sizes) + out[0].extend(s for _, s in strides) + if isinstance(desc, AOTInput): + out[1].extend(SubclassSizeAOTInput(desc, i) for i, _ in sizes) + out[1].extend(SubclassStrideAOTInput(desc, i) for i, _ in strides) + else: + out[1].extend(SubclassSizeAOTOutput(desc, i) for i, _ in sizes) + out[1].extend(SubclassStrideAOTOutput(desc, i) for i, _ in strides) + return + + attrs, _ = t.__tensor_flatten__() + + SubclassGetAttr: Callable[[AOTInput | AOTOutput, str], AOTDescriptor] + SubclassSize: Callable[[AOTInput | AOTOutput, int], AOTDescriptor] + SubclassStride: Callable[[AOTInput | AOTOutput, int], AOTDescriptor] + if isinstance(desc, AOTInput): + SubclassGetAttr = SubclassGetAttrAOTInput # type: ignore[bad-assignment] + SubclassSize = SubclassSizeAOTInput # type: ignore[bad-assignment] + SubclassStride = SubclassStrideAOTInput # type: ignore[bad-assignment] + else: + SubclassGetAttr = SubclassGetAttrAOTOutput # type: ignore[bad-assignment] + SubclassSize = SubclassSizeAOTOutput # type: ignore[bad-assignment] + SubclassStride = SubclassStrideAOTOutput # type: ignore[bad-assignment] + + for attr in attrs: + inner_value = getattr(t, attr) + n_desc: Any = SubclassGetAttr(desc, attr) + flatten_subclass(inner_value, n_desc, out=out) + + if append_symints: + sizes = enumerate_filter_symints(t.size()) + strides = enumerate_filter_symints(t.stride()) + out[0].extend(s for _, s in sizes) + out[0].extend(s for _, s in strides) + out[1].extend(SubclassSize(desc, i) for i, _ in sizes) + out[1].extend(SubclassStride(desc, i) for i, _ in strides) + + xs_inner: list[FxValue] = [] + descs_inner: list[AOTDescriptor] = [] + + for x, desc in zip(wrapped_args, wrapped_args_descs): + flatten_subclass(x, desc, out=(xs_inner, descs_inner)) + + return xs_inner, descs_inner + + +# subclass_metas is needed at runtime to compute which indices are symints in +# the outer_size/outer_stride +def runtime_unwrap_tensor_subclasses( + wrapped_args: list[Tensor | int], + *, + append_symints: bool, + subclass_metas: list[PlainTensorMeta | SubclassCreationMeta] | None = None, +) -> list[int | Tensor | SymInt | CustomClassBase]: + def flatten_subclass( + x: Tensor | TraceableWrapperSubclass, + subclass_meta: PlainTensorMeta | SubclassCreationMeta | OpaqueMeta | None, + *, + out: list[CustomClassBase | SymInt | Tensor | int], + ) -> list[CustomClassBase | SymInt | Tensor | int]: + def append_plain_tensor_symints(tensor: Tensor, meta: PlainTensorMeta) -> None: + size = tensor.size() + if len(size) != len(meta.size_symbol_placeholders): + raise AssertionError( + f"size length mismatch: {len(size)} != {len(meta.size_symbol_placeholders)}" + ) + out.extend( + [ + r + for (r, is_symint) in zip(size, meta.size_symbol_placeholders) + if is_symint + ] + ) + + stride = tensor.stride() + if len(stride) != len(meta.stride_symbol_placeholders): + raise AssertionError( + f"stride length mismatch: {len(stride)} != {len(meta.stride_symbol_placeholders)}" + ) + out.extend( + [ + r + for (r, is_symint) in zip(stride, meta.stride_symbol_placeholders) + if is_symint + ] + ) + + if not is_traceable_wrapper_subclass(x): + out.append(x) + if append_symints and isinstance(subclass_meta, PlainTensorMeta): + append_plain_tensor_symints(x, subclass_meta) + return out + + if not isinstance(x, Tensor): + raise AssertionError(f"expected Tensor, got {type(x)}") + if not isinstance(subclass_meta, SubclassCreationMeta): + raise AssertionError("subclass_meta should be a SubclassCreationMeta") + + attrs, _ = x.__tensor_flatten__() + + for attr in attrs: + inner_value = getattr(x, attr) + match inner_value: + case CustomClassBase(): + out.append(inner_value) + case Tensor(): + inner_meta = subclass_meta.attrs.get(attr) + flatten_subclass(inner_value, inner_meta, out=out) + case _: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(inner_value)}" + ) + + if append_symints: + # outer_size + size = x.size() + symint_placeholders = compute_symint_placeholders(subclass_meta.outer_size) + if len(size) != len(symint_placeholders): + raise AssertionError( + f"size length mismatch: {len(size)} != {len(symint_placeholders)}" + ) + out.extend( + [r for (r, is_symint) in zip(size, symint_placeholders) if is_symint] + ) + + # outer_stride + stride = x.stride() + symint_placeholders = compute_symint_placeholders( + subclass_meta.outer_stride + ) + if len(stride) != len(symint_placeholders): + raise AssertionError( + f"stride length mismatch: {len(stride)} != {len(symint_placeholders)}" + ) + out.extend( + [r for (r, is_symint) in zip(stride, symint_placeholders) if is_symint] + ) + return out + + xs_inner: list[int | Tensor | SymInt | CustomClassBase] = [] + + if append_symints: + if subclass_metas is None: + raise AssertionError( + "subclass_metas must not be None when append_symints is True" + ) + + for idx, x in enumerate(wrapped_args): + if not is_traceable_wrapper_subclass(x): + xs_inner.append(x) + continue + + if subclass_metas is None: + get_plain_tensors(x, out=xs_inner) + else: + subclass_meta = subclass_metas[idx] + if not isinstance(subclass_meta, SubclassCreationMeta): + raise AssertionError( + f"expected SubclassCreationMeta, got {type(subclass_meta)}" + ) + flatten_subclass(x, subclass_meta, out=xs_inner) + + return xs_inner + + +def unwrap_tensor_subclasses_with_indices_to_original( + wrapped_args: list[Any], +) -> tuple[list[Any], list[int]]: + ret_unwrapped = [] + ret_indices_to_original = [] + for i, a in enumerate(wrapped_args): + a_unwrapped, _ = unwrap_tensor_subclasses( + [a], [DummyAOTInput(9999)], append_symints=False + ) + ret_unwrapped.extend(a_unwrapped) + n = len(a_unwrapped) + ret_indices_to_original.extend([i] * n) + + return ret_unwrapped, ret_indices_to_original + + +def remap_unwrapped_subclass_arg_indices( + wrapped_args: list[Any], static_input_indices: list[int] +) -> list[int]: + def static_arg_slots(arg: Any, *, include_plain_tensor_symints: bool) -> list[bool]: + # Forwarded SymInts occupy flattened arg positions, but static input indices + # describe tensor/opaque slots whose value should not be copied. + if not is_traceable_wrapper_subclass(arg): + if include_plain_tensor_symints and isinstance(arg, Tensor): + num_symints = len(enumerate_filter_symints(arg.size())) + len( + enumerate_filter_symints(arg.stride()) + ) + return [True] + [False] * num_symints + return [True] + + slots = [] + attrs, _ = arg.__tensor_flatten__() + for attr in attrs: + inner_value = getattr(arg, attr) + match inner_value: + case CustomClassBase(): + slots.append(True) + case Tensor(): + slots.extend( + static_arg_slots(inner_value, include_plain_tensor_symints=True) + ) + case _: + raise AssertionError( + f"expected Tensor or CustomClassBase, got {type(inner_value)}" + ) + + slots.extend( + [False] + * ( + len(enumerate_filter_symints(arg.size())) + + len(enumerate_filter_symints(arg.stride())) + ) + ) + return slots + + static_input_indices_set = set(static_input_indices) + new_ind = 0 + remapped_static_indices = [] + for i, arg in enumerate(wrapped_args): + slots = ( + static_arg_slots(arg, include_plain_tensor_symints=False) + if is_traceable_wrapper_subclass(arg) + else [True] + ) + + for is_static_arg_slot in slots: + if i in static_input_indices_set and is_static_arg_slot: + remapped_static_indices.append(new_ind) + + new_ind += 1 + + return remapped_static_indices + + +# Turns a flattened list of tensor arguments into (maybe) subclass tensors. +# This function is used both at trace time and runtime, so we have an is_runtime flag telling us which context we're in. +def wrap_tensor_subclasses( + unwrapped_args: Sequence[Any], + *, + subclass_metas: list[PlainTensorMeta | SubclassCreationMeta], + num_fw_outs_saved_for_bw: int | None = None, + included_subclass_symints: bool = False, + is_runtime: bool = False, + make_subclass_override: Callable[..., Any] | None = None, +) -> tuple[Any, ...]: + # pyrefly: ignore [implicit-any] + wrapped_args = [] + num_args_tallied = 0 + for subclass_meta in subclass_metas: + if isinstance(subclass_meta, PlainTensorMeta): + wrapped_args.append(unwrapped_args[subclass_meta.unwrapped_idx]) + num_args_tallied += subclass_meta.arg_count + else: + if not isinstance(subclass_meta, SubclassCreationMeta): + raise AssertionError( + f"expected SubclassCreationMeta, got {type(subclass_meta)}" + ) + if subclass_meta.included_subclass_symints != included_subclass_symints: + raise AssertionError( + f"included_subclass_symints mismatch: {subclass_meta.included_subclass_symints} != {included_subclass_symints}" + ) + + if make_subclass_override: + wrapped_args.append( + make_subclass_override(subclass_meta, is_runtime, unwrapped_args) + ) + else: + wrapped_args.append( + subclass_meta.creation_fn( + unwrapped_args, + is_runtime=is_runtime, + ) + ) + num_args_tallied += subclass_meta.arg_count + + # Note: [Partitioner handling for Subclasses, Part 2] + # At the beginning of AOTAutograd, we collect metadata on the inputs and outputs of the user fw, + # to figure out which inputs/outputs are subclasses, and how to reconstruct the subclasses after flattening them. + # + # When this function is called at runtime in the forward, + # we have been passed a list of (flattened) dense-tensor fw-outs, and need to reconstruct any subclass fw outs. + # + # One reasonable question that you should ask: when should the dense_tensor -> subclass_tensor wrapping happen? + # Answer: we do it **inside of our compiled autograd.Function**. + # This seems like morally the right place: autograd happens above subclass desugaring, + # so autograd should see actual tensor subclasses at runtime, and not flattened dense tensors. + # + # This causes a tricky interaction though: when we run the min-cut partitioner to divvy up the joint graph + # into a forward and backward graph, we end up with some activations that show up as extra outputs + # in the compiled forward graph, that are **not** user outputs. + # These activations are not visible to the user, and so there's no need for us to wrap them back into subclasses. + # + # On top of that, when we first computed subclass metadata (in `run_functionalized_fw_and_collect_metadata`), + # we computed subclass metadata on every forward output, but this did **not** include activations + # created by the partitioner. + # as a result, `unwrapped_args` here will correspond to (*unwrapped_user_fw_outs, *activations), + # but `subclass_metas` will only correspond to subclass metadata on `user_fw_outs`. + # We then need to make sure that we return (*wrapped_user_fw_outs, *activations). + if num_fw_outs_saved_for_bw is not None: + if len(unwrapped_args) != num_args_tallied + num_fw_outs_saved_for_bw: + raise AssertionError( + f"Expected the number actual unwrapped-subclass outputs {len(unwrapped_args)} to equal " + f"the number of args calculated from subclasses ({num_args_tallied}) plus the number of " + f"additional activations saved for the backward pass ({num_fw_outs_saved_for_bw})" + ) + activations = unwrapped_args[num_args_tallied:] + if isinstance(wrapped_args, tuple) and isinstance(activations, tuple): + return wrapped_args + activations + return tuple(list(wrapped_args) + list(activations)) + else: + if len(unwrapped_args) != num_args_tallied: + raise AssertionError( + f"Expected {len(unwrapped_args)} == {num_args_tallied}" + ) + return tuple(wrapped_args) + + +# Given a bunch of "dense" tensor arguments, this function (potentially) wraps them into tensor subclasses. +# This function carefully handles the inference vs. joint cases: +# - when is_joint_structure is True, args is (primals, tangents) +# - when is_joint_structure is False, args is [*primals] +def wrap_tensor_subclasses_maybe_joint( + unwrapped_args: Sequence[Any], + *, + is_joint_structure: bool, + meta: ViewAndMutationMeta, +) -> tuple[Any, ...]: + # Since this function is reused for both inference and joint graphs, + if is_joint_structure: + if not (isinstance(unwrapped_args, tuple) and len(unwrapped_args) == 2): + unwrapped_len = ( + len(unwrapped_args) + if isinstance(unwrapped_args, (tuple, list)) + else "N/A" + ) + raise AssertionError( + f"expected tuple of length 2 for joint structure, " + f"got {type(unwrapped_args)} with length {unwrapped_len}" + ) + if not ( + isinstance(unwrapped_args[0], (tuple, list)) + and isinstance(unwrapped_args[1], (tuple, list)) + ): + raise AssertionError( + f"expected primals and tangents to be tuple or list, got {type(unwrapped_args[0])} and {type(unwrapped_args[1])}" + ) + primals, tangents = unwrapped_args[0], unwrapped_args[1] + wrapped_primals = wrap_tensor_subclasses( + primals, + subclass_metas=meta.subclass_inp_meta, + included_subclass_symints=True, + ) + wrapped_tangents = wrap_tensor_subclasses( + tangents, + subclass_metas=meta.subclass_tangent_meta, + included_subclass_symints=False, + ) + return (wrapped_primals, wrapped_tangents) + else: + wrapped_args = wrap_tensor_subclasses( + unwrapped_args, + subclass_metas=meta.subclass_inp_meta, + included_subclass_symints=True, + ) + return wrapped_args + + +def compute_inner_mutated_inp_indices_from_subclass_meta( + fw_metadata: ViewAndMutationMeta, + inner_metadata: ViewAndMutationMeta, +) -> list[int]: + # Note: [Recomputing subclass mutation handling] + # + # Generally, if a subclass requires grad, its components will not require grad. + # But for the purposes of tracking returned tensors, we should treat those component + # tensors as if they require grad. + # + # For example, if the subclass tensor requires grad and will be mutated in a way that + # requires us to handle the mutation outside of the graph, we need to return it + # from the forward graph. The inner_meta data won't consider the component tensors + # as if they need to be returned, because they don't require grad; but really, we + # should handle those tensors the same way we handle the subclass tensor itself; i.e. + # if we'd include the subclass tensor as part of the outputs, then we should also + # include the component tensors. + # + # To do this, we patch num_mutated_inp_runtime_indices below by expanding the inputs + # from the outer subclass tensors and propagating + + updated_input_info = [] + inner_idx = 0 + if not fw_metadata.subclass_inp_meta: + # Sometimes we don't have subclass info, e.g. synthetic_base codepaths + return inner_metadata.mutated_inp_runtime_indices + if len(fw_metadata.subclass_inp_meta) != len(fw_metadata.input_info): + raise AssertionError( + f"subclass_inp_meta length ({len(fw_metadata.subclass_inp_meta)}) != input_info length ({len(fw_metadata.input_info)})" + ) + for outer_idx, inp_meta in enumerate(fw_metadata.subclass_inp_meta): + if isinstance(inp_meta, PlainTensorMeta): + if outer_idx >= len(fw_metadata.input_info): + raise AssertionError( + f"outer_idx ({outer_idx}) >= len(fw_metadata.input_info) ({len(fw_metadata.input_info)})" + ) + if inner_metadata is not None: + if inner_idx >= len(inner_metadata.input_info): + raise AssertionError( + f"inner_idx ({inner_idx}) >= len(inner_metadata.input_info) ({len(inner_metadata.input_info)})" + ) + if ( + inner_metadata.input_info[inner_idx] + != fw_metadata.input_info[outer_idx] + ): + raise AssertionError( + f"input_info mismatch at inner_idx={inner_idx}, outer_idx={outer_idx}: " + f"{inner_metadata.input_info[inner_idx]} != {fw_metadata.input_info[outer_idx]}" + ) + updated_input_info.append(fw_metadata.input_info[outer_idx]) + inner_idx += 1 + else: + if inp_meta.original_subclass is None: + raise AssertionError( + "inp_meta.original_subclass must not be None for SubclassCreationMeta" + ) + for _ in range(inp_meta.arg_count): + updated_input_info.append(fw_metadata.input_info[outer_idx]) + inner_idx += 1 + if inner_metadata is not None: + if len(inner_metadata.input_info) != len(updated_input_info): + raise AssertionError( + f"inner_metadata.input_info length ({len(inner_metadata.input_info)}) " + f"!= updated_input_info length ({len(updated_input_info)})" + ) + + return [ + i + for i, inp in enumerate(updated_input_info) + if inp.mutation_type == MutationType.MUTATED_OUT_GRAPH + ] diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/to_standalone_python.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/to_standalone_python.py new file mode 100644 index 0000000000000000000000000000000000000000..218897c1c1be34f7c0f2983ed2eaed22776736be --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/to_standalone_python.py @@ -0,0 +1,999 @@ +"""Lower a GraphModule to a self-contained Python module via AOTAutograd + Inductor. + +This is the AOT half of the backend contract behind ``torch.compiler.precompile``: + + python_code, cache = compile_to_python(gm, example_inputs) + +``inductor.compile_to_python`` produces only the inner Inductor ``call`` (kernels +for the post-AOTAutograd dense graph). This module wraps that with the prelude / +epilogue (input-mutation reflection, output-alias regen, subclass wrap/unwrap, +...) by COMPOSING AOTAutograd's own codegen'd runtime-wrapper source -- captured +during compile -- rather than reimplementing it. Every wrapper is spliced verbatim as a +real top-level ``def``, with its closed-over globals hoisted to module-scope assignments, +so the module reads as ordinary code. These nest in the SAME order the runtime builds: +the INNER chain wrappers (subclass / functionalized-RNG) wrap the inner ``call`` and are +composed inside the orchestration, while the OUTER ``CompilerWrapper``s (dedup / synthetic +base) wrap the orchestration itself (via a single-arg adapter over it). Cross-wrapper references, the inner ``call`` chain, +public helpers, and baked metadata objects (reconstructed as source -- see +``_emit_value``) are wired by name; a guard rejects the rare case where a wrapper def +name or hoisted global would collide with another top-level name (a sibling wrapper or +an inner-module binding) rather than silently rebinding one. +The result is a standalone module exposing ``call(flat_inputs) -> outputs`` that +runs on its own (JIT-compiling kernels); ``cache`` is an opaque acceleration (or +None). + +Baked metadata is emitted as plain Python source (no pickle / base64 blobs), so the +generated module is fully auditable and exec'ing it never invokes ``pickle.loads``. +A leaf that cannot be expressed as source raises NotImplementedError rather than +falling back to an opaque embedding. + +Contract note: the standalone ``call`` deliberately substitutes ``nullcontext`` / a +no-op for the runtime's first-invocation context and profiler prologue, dropping the +cold-start custom-op aliasing analysis and the profiler prologue -- both diagnostics +with no effect on numerics (see the generated-call emission site). One caveat: that +dropped first-invocation custom-op aliasing analysis can itself RAISE under +``config.error_on_custom_op_aliasing`` (default on in CI), so a graph whose custom op +violates the aliasing contract runs SILENTLY in the standalone artifact where the +eager / compiled path would error -- an intentional trade-off, not a numerics bug. +""" + +from __future__ import annotations + +import ast +import re +import threading +from typing import Any, TYPE_CHECKING + +from .codegen import capture_generated_sources, GeneratedSource +from .source_emit import _REBUILD_HELPER, emit_value + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Sequence + + from torch.fx import GraphModule + + +# Serializes compile_to_python: the wrapper-source capture is thread-local, but the +# AOTAutograd capture pass and the inner inductor compile swap process-global cache state +# (see the THREADING note on compile_to_python), so concurrent compiles must not overlap. +# An RLock (not a +# plain Lock) because this entry point is re-entrant on a single thread: a custom +# backend or inductor pass invoked while the lock is held may call back into this +# lowering to compile a subgraph on the SAME thread, and a plain Lock would +# self-deadlock on that re-entry. On-thread re-entry is safe here: the capture sink and +# the cache-state swap (CacheArtifactManager.with_fresh_cache) are each self-contained +# per call, so a nested compile neither corrupts the outer capture nor the outer cache +# scope. +_COMPILE_LOCK = threading.RLock() + + +# ====================================================================== +# WHAT IS GOING ON HERE: composing AOTAutograd's runtime wrappers as source +# ====================================================================== +# +# AOTAutograd does not hand back a single flat function. The dense graph Inductor +# compiles (the inner ``call``) is only the arithmetic core; around it AOTAutograd +# wraps a prelude/epilogue that does what the core cannot express: reflecting input +# mutations back onto the caller's tensors, regenerating outputs that alias an input +# or each other, wrapping/unwrapping tensor subclasses, de-duplicating aliased +# inputs, and threading functionalized RNG state. At runtime AOTAutograd emits each +# wrapper as Python *source*, exec's it (the chokepoint is _compile_and_exec_source +# in codegen.py), and the resulting function runs while closing over a +# globals dict supplied in-process -- i.e. a wrapper is (source text) + +# ({local_name: live_object}). +# +# The objects a wrapper closes over come in a few kinds: +# - public runtime helpers the codegen'd source references (e.g. increment_version, +# gen_alias_from_base, _unwrap_tensoralias, mark_dynamo_propagated_dynamic_indices, +# the CUDARngStateHelper staticmethods) -- ordinary importable objects; +# - the inner Inductor ``call`` that the chain ultimately invokes; +# - sibling captured wrappers -- the next link of the runtime chain (an inner subclass / +# functionalized-RNG wrapper, or an outer dedup / synthetic-base wrapper, whose body +# calls the link it wraps -- the orchestration's outer closure for the innermost outer +# wrapper), plus the orchestration's output-alias and mutation epilogue helpers, which +# it closes over directly by reference; +# - per-graph metadata baked at compile time (e.g. a ViewMetaSequence for alias +# regen, tensor-subclass metadata) -- live objects with no import path. +# +# Concretely, the module emitted for ``x.view(-1)`` (an output aliasing its input) has +# one of each (heavily trimmed; the (1)-(4) tags match the kinds listed above): +# +# from ...standalone_runtime import gen_alias_from_base # (1) public helper +# +# _inner_call = call # (2) the inner call +# _vms_0 = ViewMetaSequence._from_parts(...) # (4) metadata as source +# def _alias_fn(orig_inputs, fw_outs): # (3) sibling wrapper +# return [gen_alias_from_base(orig_inputs[0], fw_outs[0], False, _vms_0, ...)] +# _replay_aliases_ = _alias_fn # (3) orchestration's ref +# def _runtime_wrapper(_compiled_fn_, _first_ctx_, _on_before_call_, args): +# all_outs = _compiled_fn_(args) # (2) inner call invoked +# return _replay_aliases_(orig_inputs, all_outs) # (3) sibling invoked +# def call(flat_inputs): +# return _runtime_wrapper( +# _inner_call, contextlib.nullcontext, lambda: None, list(flat_inputs)) +# +# We do NOT reimplement any of this. We CAPTURE AOTAutograd's exact codegen'd wrapper +# source together with the (pre-exec) globals dict each wrapper closed over: a +# thread-local sink in codegen.py records one GeneratedSource per wrapper. +# To trigger the capture we run AOTAutograd ourselves (under no_grad, the inference path) +# with a capture-only inner compiler: it grabs the dense inner graph and returns a +# placeholder callable, so AOTAutograd still codegen's the runtime-wrapper chain AROUND +# that placeholder -- which is what the sink records. Inductor does not run in that pass; +# it runs once afterward on the captured dense graph (via inductor.compile_to_python), and +# the composer swaps the placeholder for the inner inductor ``call`` by object identity. +# +# THE COMPOSITION PROBLEM. To turn a captured wrapper into a real top-level ``def`` in +# the standalone module we splice its source verbatim. But that source refers to each +# global by the LOCAL ALIAS AOTAutograd happened to choose (e.g. ``compiled_fn`` for +# the inner call), not by any importable name. So for each ``{name: obj}`` in the +# captured globals dict we emit a top-level binding ``name = `` (see +# _emit_inline) -- except when the resolved expression already IS that module-scope +# name (an import, or ``torch``), which needs no binding. The hard part is the right- +# hand side: given only a live object, produce source that reproduces it. That requires +# RECOGNIZING what the object is, the job of _resolve_global and the id-keyed +# structures it consults, in order: +# - inner_call_id -> the inner ``call`` becomes ``_inner_call`` +# - fn_id_to_name -> a sibling wrapper's fn becomes that wrapper's own name +# - _known_helper_table() -> an importable helper becomes (import, expr) +# - anything else: reconstruct field-by-field as source (_emit_value), or raise. +# Recognition is by id() (object identity), not value-equality: for "is this the EXACT +# object the wrapper closed over," == is the wrong tool (functions don't compare by +# value, and an equal-but-different object would mis-resolve). Value-equality IS used, +# but later and for a different job -- _emit_value round-trip-checks reconstructed +# metadata (rebuilt == obj) before trusting it. Every hoisted name is _reserve'd: a +# collision with a sibling wrapper's name or an inner-module binding fails loudly +# rather than silently rebinding. +# +# WHY THIS IS SAFE ACROSS PROCESSES AND MACHINES. Every id() above is consulted ONLY +# here, during composition, in the process that just ran the compile -- where all the +# candidate objects (helpers, the inner call, sibling wrappers) are simultaneously +# alive, held by the GeneratedSource records and the captured globals dicts, so no +# address can be freed and reused mid-pass. Nothing the composer emits carries an id() +# value, a live object, or any thread-local capture state: it emits only import lines, +# ``name = expr`` bindings, and verbatim def source (the inner Inductor source is +# likewise spliced as text). Grep the GENERATED module and there is no ``id(`` to +# find. By the time the user holds the Python, all the process/thread-local state the +# composer leaned on is gone; what ships is imports + name bindings + verbatim code. +# Load it on another machine with the same torch version and the imports resolve by +# name and the bindings reconstruct -- identity was a compile-time recognition device, +# never a serialized artifact (live tensors / pickle / base64 blobs are rejected +# outright rather than embedded). +# +# So the one genuine cross-machine contract is not id() but that the *names* the +# artifact imports still resolve on load. Helpers are emitted as either ``import +# torch`` (the torch module and stable public paths, e.g. +# torch.autograd.graph.increment_version) or an import from the single small surface +# standalone_runtime.py (for the AOTAutograd-area internals -- plus CUDARngStateHelper, +# re-exported there for import-ordering -- whose locations are not themselves a stable +# contract). That file's IDENTITY CONTRACT -- re-exports must preserve object id -- +# exists purely so the COMPOSER's id-lookup keeps matching; it is a compile-time +# requirement, and the runtime artifact has no id dependency of its own. +# ====================================================================== + + +# Global objects the codegen'd wrappers close over that are reproducible as an +# import in the standalone module (rather than reconstructed field-by-field). Maps +# object id -> (import_statement, expression). Built lazily to avoid import cycles. +def _known_helper_table() -> dict[int, tuple[str, str]]: + # Generated artifacts import runtime helpers from the single stable surface + # ``standalone_runtime`` (not scattered AOTAutograd internals). + import torch + + from . import standalone_runtime as rt + + _RT = "from torch._functorch._aot_autograd.standalone_runtime import" + table: dict[int, tuple[str, str]] = { + id(torch): ("import torch", "torch"), + id(rt.normalize_as_list): (f"{_RT} normalize_as_list", "normalize_as_list"), + id(rt.mark_dynamo_propagated_dynamic_indices): ( + f"{_RT} mark_dynamo_propagated_dynamic_indices", + "mark_dynamo_propagated_dynamic_indices", + ), + id(torch.autograd.graph.increment_version): ( + "import torch", + "torch.autograd.graph.increment_version", + ), + id(rt.gen_alias_from_base): ( + f"{_RT} gen_alias_from_base", + "gen_alias_from_base", + ), + id(rt._unwrap_tensoralias): ( + f"{_RT} _unwrap_tensoralias", + "_unwrap_tensoralias", + ), + id(rt.CUDARngStateHelper.get_torch_state_as_tuple): ( + f"{_RT} CUDARngStateHelper", + "CUDARngStateHelper.get_torch_state_as_tuple", + ), + id(rt.CUDARngStateHelper.set_new_offset): ( + f"{_RT} CUDARngStateHelper", + "CUDARngStateHelper.set_new_offset", + ), + } + return table + + +_MODULE_HEADER = """\ +# Generated by torch._functorch.aot_autograd.compile_to_python -- do not edit. +# +# Self-contained, executable module exposing ``call(flat_inputs) -> outputs`` for +# the post-AOTAutograd graph. The Inductor kernels JIT-compile from the inlined +# source on first call (no cache needed). The prelude/epilogue is AOTAutograd's own +# codegen'd runtime wrappers, not reimplemented: each (the orchestration and any chain +# wrappers) is spliced as a real top-level ``def`` with its closed-over globals (inner +# ``call``, sibling wrappers, public helpers, baked metadata reconstructed as source) +# hoisted to module-scope assignments -- so results match eager. The companion opaque +# cache is only an acceleration; this module never reads it. +""" + + +def _resolve_global( + obj: object, + helper_table: dict[int, tuple[str, str]], + inner_call_id: int | None, + fn_id_to_name: dict[int, str], + imports: set[str], + orch_closure_id: int | None = None, + orch_entry_name: str | None = None, +) -> str: + """Return a Python expression (valid in the generated module) that reproduces + ``obj``, recording any needed import. Raises NotImplementedError if ``obj`` is + neither the inner call, a sibling wrapper, a known helper, nor source- + reconstructible (see ``_emit_value``).""" + if inner_call_id is not None and id(obj) == inner_call_id: + return "_inner_call" + # An OUTER wrapper (dedup / synthetic base) closes over the orchestration's outer + # closure as its inner. That closure is not a captured wrapper and has no import + # path, so wire it to the single-arg orchestration entry adapter the composer emits. + if orch_closure_id is not None and id(obj) == orch_closure_id: + if orch_entry_name is None: + raise AssertionError("expected orch_entry_name to be not None") + return orch_entry_name + if id(obj) in fn_id_to_name: + return fn_id_to_name[id(obj)] + if id(obj) in helper_table: + import_stmt, expr = helper_table[id(obj)] + if import_stmt: + imports.add(import_stmt) + return expr + # Not a wired reference (inner call / sibling wrapper / helper): emit ``obj`` as + # plain reconstruction source. Raises if it is not source-expressible. + return emit_value(obj, imports) + + +def _module_level_names(tree: ast.Module) -> set[str]: + """Names bound at module scope by a parsed module. Used to seed ``_reserve`` so an + inlined wrapper's def name or hoisted global (chain wrapper or orchestration) cannot + silently shadow a top-level name the inner Inductor module already binds.""" + names: set[str] = set() + for n in tree.body: + if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + names.add(n.name) + elif isinstance(n, ast.Assign): + # Walk each target so tuple/list/starred unpacking (``a, b = ...`` / + # ``first, *rest = ...``) is covered, not just bare-name targets. + for t in n.targets: + names.update(x.id for x in ast.walk(t) if isinstance(x, ast.Name)) + elif isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name): + names.add(n.target.id) + elif isinstance(n, (ast.Import, ast.ImportFrom)): + names.update(a.asname or a.name.split(".")[0] for a in n.names) + elif isinstance(n, ast.Delete): + # Inductor's inner module does ``async_compile = AsyncCompile()`` then + # ``del async_compile`` at module scope; a del'd name does not survive, so it + # must not be reserved (else a hoisted wrapper global of the same name would + # trip a spurious collision). Body order is assign-then-del, so removing here + # leaves only names that actually persist. + for t in n.targets: + names.difference_update( + x.id for x in ast.walk(t) if isinstance(x, ast.Name) + ) + return names + + +def _compose_standalone_module( + inner_python: str, captured: list[GeneratedSource], inner_call_obj: Any +) -> str: + """Compose the inner Inductor ``call`` with AOTAutograd's captured runtime + wrappers into one standalone module exposing ``call(flat_inputs) -> outputs``. + + Every wrapper (chain wrappers and the orchestration) is spliced as a real top-level + ``def`` with its closed-over globals hoisted to module-scope assignments (resolved + here). They are chained by name in the SAME nesting the runtime builds: the + orchestration is invoked with the INNER InductorWrapper chain head (subclass / RNG) + as its inner, and any OUTER ``CompilerWrapper`` (dedup / synthetic base, applied + AROUND the orchestration in ``graph_compile._aot_stage2c_make_inference_function``) + wraps a single-arg adapter over the orchestration. + + ``inner_call_obj`` is the placeholder the capture pass returned for the inner call; + its identity is authoritative (see the note at the inner-call site below). + """ + # The capture sink is duration-scoped over the inner inductor compile, with no + # originating-graph id at install time, so a re-entrant on-thread AOTAutograd / + # inductor lowering during that window that codegen's wrappers into THIS sink would + # append ITS wrappers here too. (A nested compile_to_python installs its OWN sink via + # capture_generated_sources, so its wrappers go there, not here -- it is not this + # case.) Each captured wrapper is tagged at append time with its TracingContext + # identity (origin_id), which separates such a foreign lowering when it ran under a + # DISTINCT TracingContext. A same-context re-entrant lowering reuses the ambient + # TracingContext via try_get() and so shares this origin_id; that case is instead + # caught by the orchestration count/wiring guards below (a second orchestration trips + # the len() != 1 check). Filter to the target graph's origin before composing. The + # target is the origin of the LAST captured orchestration wrapper: a foreign lowering + # appends its orchestration before the outer one finishes, so the final orchestration + # is always the outer/target one. + orchestrations = [ + g for g in captured if g.artifact_name == "runtime_wrapper_orchestration" + ] + if orchestrations: + # target_origin is None only without an ambient TracingContext, which the real + # precompile path never hits (capture always runs under one); in that defensive + # case the filter keeps every None-origin wrapper and the count/wiring guards + # below remain the backstop. + target_origin = orchestrations[-1].origin_id + captured = [g for g in captured if g.origin_id == target_origin] + + # Backward wrappers are out of scope for forward lowering; reject them up front. + # Every other wrapper that can appear in a composable (cacheable) forward graph is + # codegen'd as source and captured here. 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 it ever reaches composition. + unsupported = [g.artifact_name for g in captured if "backward" in g.artifact_name] + if unsupported: + raise NotImplementedError( + "aot_autograd.compile_to_python cannot yet compose these runtime " + f"wrappers into standalone source: {sorted(set(unsupported))}." + ) + + orchestration = [ + g for g in captured if g.artifact_name == "runtime_wrapper_orchestration" + ] + if len(orchestration) != 1: + raise NotImplementedError( + "aot_autograd.compile_to_python expected exactly one forward " + f"orchestration wrapper, captured {len(orchestration)}." + ) + orch = orchestration[0] + non_orch = [g for g in captured if g is not orch] + + # The generated ``call`` invokes the orchestration POSITIONALLY by its own name (see + # the bottom of this function): _runtime_wrapper(chain_head, contextlib.nullcontext, + # lambda: None, flat_inputs). That mapping is hardcoded to the codegen'd signature in + # runtime_wrappers.py (``def _runtime_wrapper(_compiled_fn_, _first_ctx_, + # _on_before_call_, args)``). Verify the captured signature still matches so a future + # rename/reorder fails loudly here instead of silently passing wrong arguments. + expected_orch_params = ["_compiled_fn_", "_first_ctx_", "_on_before_call_", "args"] + orch_def = next( + ( + n + for n in ast.walk(ast.parse(orch.source)) + if isinstance(n, ast.FunctionDef) and n.name == orch.fn_name + ), + None, + ) + args_node = orch_def.args if orch_def is not None else None + if args_node is None: + orch_params = None + else: + # Compare the FULL signature, not just positional params: the standalone call is + # purely positional, so a keyword-only / *args / **kwargs param (e.g. an added + # kw-only-with-default) would be silently dropped. Surface any such param so it + # trips this guard rather than passing. + orch_params = [a.arg for a in (*args_node.posonlyargs, *args_node.args)] + orch_params += [a.arg for a in args_node.kwonlyargs] + if args_node.vararg is not None: + orch_params.append("*" + args_node.vararg.arg) + if args_node.kwarg is not None: + orch_params.append("**" + args_node.kwarg.arg) + if orch_params != expected_orch_params: + raise NotImplementedError( + "aot_autograd.compile_to_python: the orchestration wrapper signature " + f"changed (expected {expected_orch_params}, got {orch_params}); the " + "standalone module invokes it positionally and must be updated to match." + ) + + helper_table = _known_helper_table() + # Every wrapper is inlined (below) as a real def at module scope under its OWN codegen'd + # name, so references resolve to that name. Note these names are NOT distinct in general + # -- the subclass, dedup, and debug-assert chain wrappers all codegen ``inner_fn``; what + # holds today is that at most one chain wrapper appears per composable forward graph (see + # the test note on multi-link chains), so the names don't actually clash. ``_reserve`` + # fails loudly if that ever stops holding (the old ``_wrapper_{i}`` scheme could carry + # multiple same-named wrappers in private exec namespaces; inlining deliberately cannot). + fn_id_to_name = {id(g.fn): g.fn_name for g in non_orch} + + # A chain wrapper references the inner it wraps via one of these globals + # (subclass/dedup use ``compiled_fn``; the functionalized-RNG wrapper uses + # ``_compiled_fn_``). The orchestration takes its inner as a call-time arg, not a + # global, so it is never a chain wrapper. MAINTAINERS: if AOTAutograd adds a + # forward chain wrapper that names its inner via a new global, add that name here, + # otherwise inner-call/chain-head detection silently bypasses it. + _INNER_NAMES = ("compiled_fn", "_compiled_fn_") + + def _inner_ref(g: GeneratedSource) -> Any: + for nm in _INNER_NAMES: + if nm in g.globals_dict: + return g.globals_dict[nm] + return None + + # The inner Inductor call is AUTHORITATIVE: it is the placeholder object the capture + # pass returned (threaded in as ``inner_call_obj``), NOT inferred from capture order. + # This is what lets the composer tell the inner call apart from the orchestration's + # own outer closure -- both surface as some wrapper's inner-ref yet neither is a + # captured wrapper fn -- which is precisely how INNER wrappers (subclass / RNG, + # wrapping the inner call, composed INSIDE the orchestration) are distinguished from + # OUTER wrappers (dedup / synthetic base, ``CompilerWrapper``s applied AROUND the + # orchestration in graph_compile._aot_stage2c_make_inference_function). + inner_call_id: int = id(inner_call_obj) + + # Name of the single-arg adapter emitted over the orchestration; the innermost outer + # wrapper closes over the orchestration's outer closure and is wired to this name. + _ORCH_ENTRY = "_orchestration_entry" + + # The orchestration's outer closure is the object outer wrappers wrap. The composer + # never captures it directly (the captured orchestration ``fn`` is the inner + # ``_codegen_runtime_wrapper``), so recognize it structurally: an inner-ref that is + # neither the inner call nor any captured wrapper's fn can only be that closure. + orch_closure_ids = { + id(_inner_ref(g)) + for g in non_orch + if _inner_ref(g) is not None + and id(_inner_ref(g)) != inner_call_id + and id(_inner_ref(g)) not in fn_id_to_name + } + if len(orch_closure_ids) > 1: + raise NotImplementedError( + "aot_autograd.compile_to_python: captured multiple wrappers whose inner " + "reference is neither the inner call nor a captured wrapper; cannot tell " + "which wraps the orchestration." + ) + orch_closure_id: int | None = next(iter(orch_closure_ids), None) + + # Walk the OUTER chain outward from the orchestration closure: the innermost outer + # wrapper wraps the closure, the next wraps that wrapper's fn, and so on. Everything + # else is inner-side -- the subclass / RNG chain wrappers plus the alias / mutation + # epilogue helpers the orchestration closes over (which reference no inner at all). + outer_wrappers: list[GeneratedSource] = [] + if orch_closure_id is not None: + target_id: int | None = orch_closure_id + while target_id is not None: + nxt = next( + ( + g + for g in non_orch + if g not in outer_wrappers + and _inner_ref(g) is not None + and id(_inner_ref(g)) == target_id + ), + None, + ) + if nxt is None: + break + outer_wrappers.append(nxt) + target_id = id(nxt.fn) + outer_ids = {id(g) for g in outer_wrappers} + inner_side = [g for g in non_orch if id(g) not in outer_ids] + + # Chain head passed to the orchestration: the outermost INNER InductorWrapper (last + # inner-side wrapper that wraps via an inner reference), else the inner call. Computed + # up front (a pure capture-order check) so the order-inversion guard below fires + # before the later name-uniqueness guard -- a mis-ordered chain is the more specific + # diagnosis. + chain_head = "_inner_call" + chain_head_g: GeneratedSource | None = None + for g in inner_side: + if _inner_ref(g) is not None: + chain_head = fn_id_to_name[id(g.fn)] + chain_head_g = g + + # "Last with an inner-ref == outermost" holds only when INNER capture order is + # innermost-to-outermost (it is today: subclass before functionalized-RNG). Back that + # assumption with a guard: the true outermost inner wrapper is the one NO other inner + # wrapper wraps, i.e. whose fn is not referenced as another inner wrapper's inner. If + # the chosen head is itself wrapped, capture order inverted and the chain would be + # mis-ordered -- reject rather than silently emit a wrong chain (the wiring guard + # below would not catch this, since every wrapper is still referenced somewhere). + referenced_inner_ids = { + id(_inner_ref(g)) for g in inner_side if _inner_ref(g) is not None + } + if chain_head_g is not None and id(chain_head_g.fn) in referenced_inner_ids: + raise NotImplementedError( + "aot_autograd.compile_to_python: the selected chain head is itself wrapped " + "by another captured wrapper, so capture order is not innermost-to-outermost " + "as assumed; refusing to emit a mis-ordered runtime-wrapper chain." + ) + + imports: set[str] = set() + + # Parse the inner module once: to verify it binds a module-level ``call`` (the + # inner-call contract, checked below) and to collect its top-level names so no inlined + # wrapper's def name or hoisted global can silently shadow one. + inner_tree = ast.parse(inner_python) + inner_module_names = _module_level_names(inner_tree) + + # Every runtime wrapper is inlined: its def is spliced at module scope and its + # closed-over globals hoisted to top-level assignments (no exec / private namespace). + # So every emitted top-level name -- each wrapper's def name and each hoisted global -- + # must be unique and must not shadow a name the inner Inductor module binds. This holds + # in practice because at most one chain wrapper appears per composable forward graph, so + # its def name (``inner_fn`` is shared across subclass/dedup/debug-assert wrappers) and + # the inner-ref global ``compiled_fn`` each occur once, and metadata globals are + # per-wrapper suffixed. ``_reserve`` guards it: a collision fails loudly (rename/namespace + # needed) rather than silently rebinding a name. + emitted_names = set(inner_module_names) | { + "call", + "_inner_call", + "_rebuild", + "contextlib", + _ORCH_ENTRY, + } + + def _reserve(name: str) -> None: + if name in emitted_names: + raise NotImplementedError( + "aot_autograd.compile_to_python: generated top-level name " + f"{name!r} collides with another top-level name in the composed module; " + "inlining the runtime wrappers would shadow a binding." + ) + emitted_names.add(name) + + # Reserve every wrapper def name up front (before hoists) so a hoisted global cannot + # shadow a def and two wrappers cannot share a name. + for _g in (*non_orch, orch): + _reserve(_g.fn_name) + + def _resolve_globals(globals_dict: dict[str, object]) -> list[tuple[str, str]]: + # Resolve each global a wrapper closes over to a standalone source expression. + # ``globals_dict`` is the pre-exec snapshot from codegen.py, so the + # interpreter ``__builtins__`` is absent; the skip is kept defensively in case a + # future caller hands us a post-exec live dict. + out: list[tuple[str, str]] = [] + for gname, gobj in globals_dict.items(): + if gname == "__builtins__": + continue + expr = _resolve_global( + gobj, + helper_table, + inner_call_id, + fn_id_to_name, + imports, + orch_closure_id, + _ORCH_ENTRY, + ) + out.append((gname, expr)) + return out + + def _emit_inline(source: str, globals_dict: dict[str, object]) -> str: + # Splice the wrapper's def verbatim at module scope, hoisting each closed-over global + # to a top-level assignment (skipping a name already module-available -- an imported + # helper or ``torch`` -- detected as gname == its resolved expr). No exec / private + # namespace: the def reads as ordinary code and is referenced by its own name. Each + # hoisted name is ``_reserve``'d so a collision fails loudly rather than rebinding. + hoists: list[str] = [] + for gname, expr in _resolve_globals(globals_dict): + if gname == expr: + continue # already at module scope (an import / ``torch``) + _reserve(gname) + hoists.append(f"{gname} = {expr}") + return "\n".join(hoists + [source, ""]) + + # Inner-side wrappers first (subclass / RNG chain wrappers innermost-to-outermost, + # plus the epilogue helpers), then the orchestration, then the outer wrappers -- all + # spliced as real defs. An inner wrapper's hoisted inner-ref (``compiled_fn``) + # references ``_inner_call`` / a sibling emitted earlier; an outer wrapper's inner-ref + # references the orchestration entry adapter / a sibling emitted earlier -- so order + # is satisfied. + inner_blocks = [_emit_inline(g.source, g.globals_dict) for g in inner_side] + orch_block = _emit_inline(orch.source, orch.globals_dict) + outer_blocks = [_emit_inline(g.source, g.globals_dict) for g in outer_wrappers] + + # Imports (helper table + whatever emit_value added) are emitted BEFORE the inner + # module and the wrapper blocks, so a later top-level binding of the same name -- an + # inner-module binding or a hoisted wrapper global -- would shadow the import. And + # _emit_inline skips hoisting a global whose resolved expr already equals its own name + # (an imported helper referenced as ``gname == expr``), so such a wrapper would then + # silently bind to the shadowing object instead of the helper. ``from X import Y`` + # names bind a specific (non-module) object and are the ones at risk; plain ``import + # mod`` names resolve to the same singleton module no matter who imports them, so a + # duplicate binding is benign and is left unchecked (else ``import torch`` -- which the + # inner module also emits -- would trip a spurious collision). ``_reserve`` fails loudly + # if an inner-module name or a hoisted global collides with one of these import names. + for stmt in sorted(imports): + node = ast.parse(stmt).body[0] + if isinstance(node, ast.ImportFrom): + for alias in node.names: + _reserve(alias.asname or alias.name) + + # The final ``call`` invokes the outermost outer wrapper (else the orchestration + # directly). Build that line now so the wiring guard's corpus includes it -- the + # outermost outer wrapper is referenced ONLY there. + if outer_wrappers: + outermost_name = fn_id_to_name[id(outer_wrappers[-1].fn)] + final_invoke = f" return {outermost_name}(list(flat_inputs))" + else: + final_invoke = ( + f" return {orch.fn_name}(\n" + f" {chain_head}, contextlib.nullcontext, lambda: None, " + "list(flat_inputs)\n )" + ) + + # The single-arg adapter over the orchestration (emitted only when outer wrappers + # wrap it). The outer wrappers call their inner as ``fn(args)``; this adapts the + # orchestration's positional (_compiled_fn_, _first_ctx_, _on_before_call_, args) + # signature to that. When there are no outer wrappers the orchestration is invoked + # directly in ``call`` (see final_invoke). + orch_invoke_comment = [ + " # The 2nd/3rd positional args INTENTIONALLY substitute contextlib.nullcontext", + " # for the runtime's first-invocation context (_FirstInvocationContext) and a", + " # no-op for the profiler-prologue exit. This drops two cold-start diagnostics:", + " # the first-call custom-op aliasing analysis (_AnalyzeCustomOpInputOutputMode,", + " # active when check_custom_op_aliasing is set, which can even RAISE under", + " # error_on_custom_op_aliasing) and the profiler prologue. Neither affects", + " # numerics, so this is not a bug -- the standalone artifact deliberately omits", + " # them. (See the positional-mapping note in _compose_standalone_module.)", + ] + entry_block: list[str] = [] + if outer_wrappers: + entry_block = [ + f"def {_ORCH_ENTRY}(args):", + " # Single-arg adapter so the CompilerWrappers applied AROUND the", + " # orchestration (dedup / synthetic base) can invoke it as ``fn(args)``.", + *orch_invoke_comment, + f" return {orch.fn_name}(", + f" {chain_head}, contextlib.nullcontext, lambda: None, args", + " )", + "", + ] + + # _INNER_NAMES detection is a hardcoded allowlist (see above). If AOTAutograd adds + # a forward wrapper that names its inner via an unrecognized global, that wrapper + # is captured but may never be wired into the module -- silently composing a + # structurally-wrong result. Enforce that every captured non-orch wrapper is + # actually referenced somewhere: as the inner chain head, in the final ``call`` + # (the outermost outer wrapper), or by name in another block (another wrapper's + # globals, the orchestration's epilogue helpers -- e.g. ``_alias_fn`` / + # ``_apply_mutations`` -- or the entry adapter). A wrapper whose name appears in no + # other block went unwired, so reject rather than emit a wrong module. + block_of = {id(g): b for g, b in zip(inner_side, inner_blocks)} + block_of.update({id(g): b for g, b in zip(outer_wrappers, outer_blocks)}) + other_text = "\n".join( + inner_blocks + [orch_block] + entry_block + outer_blocks + [final_invoke] + ) + for g in non_orch: + name = fn_id_to_name[id(g.fn)] + own = block_of[id(g)] + elsewhere = other_text.replace(own, "", 1) + # Whole-token match: ``name`` is a wrapper def name (e.g. ``inner_fn``); a raw + # substring test would treat ``inner_fn`` as wired whenever a longer token like + # ``inner_fn2`` is referenced, silently defeating this guard. + wired = re.search(r"\b" + re.escape(name) + r"\b", elsewhere) is not None + if name != chain_head and not wired: + raise NotImplementedError( + "aot_autograd.compile_to_python could not wire captured runtime " + f"wrapper {g.fn_name!r} into the module (an inner-call global may be " + "unrecognized; see _INNER_NAMES)." + ) + + # The module splices ``_inner_call = call`` below, relying on inner_python binding a + # module-level ``call`` entry point. Inductor emits this in one of two forms: the + # flat path defines ``def call(args):`` (FunctionDef) while the graph_partition Runner + # path binds ``call = runner.call`` (Assign with a Name target). Verify one is present + # so a future inductor codegen drift fails loudly here -- like the orchestration / + # chain / wiring guards above -- instead of surfacing as a bare NameError at exec of + # the generated module. (``inner_tree`` was parsed once up front.) + binds_call = any( + (isinstance(n, ast.FunctionDef) and n.name == "call") + or ( + isinstance(n, ast.Assign) + and any(isinstance(t, ast.Name) and t.id == "call" for t in n.targets) + ) + for n in inner_tree.body + ) + if not binds_call: + raise NotImplementedError( + "compile_to_python: inner Inductor module does not bind a module-level " + "'call' entry point (the inner-call contract); the standalone module " + "splices ``_inner_call = call`` and must be updated to match." + ) + + # Only emit the _rebuild helper if a baked value actually reconstructs through it. + needs_rebuild = any( + "_rebuild(" in b for b in (*inner_blocks, orch_block, *outer_blocks) + ) + + # ``call`` invokes the orchestration directly when nothing wraps it; when outer + # wrappers do, its body just calls the outermost of them (which drives the entry + # adapter, then the orchestration) -- so the orchestration-substitution comment lives + # on whichever site actually invokes the orchestration. + if outer_wrappers: + call_body = [ + " # Invokes the outer CompilerWrapper chain (dedup / synthetic base), which", + f" # wraps {_ORCH_ENTRY} (the orchestration adapter).", + final_invoke, + ] + else: + call_body = [ + " # AOTAutograd orchestration: disables grad, invokes the inner chain,", + " # bumps mutated-input versions, applies the output epilogue.", + " #", + *orch_invoke_comment, + final_invoke, + ] + + parts = [ + _MODULE_HEADER, + "import contextlib", + *sorted(imports), + "", + "", + *(_REBUILD_HELPER if needs_rebuild else []), + "# " + "=" * 70, + "# Inner Inductor output code (kernels + ``call``)", + "# " + "=" * 70, + inner_python, + "_inner_call = call", + "", + "# " + "=" * 70, + "# AOTAutograd runtime wrappers (codegen'd): each inlined as a real def with its", + "# closed-over globals hoisted to module scope -- inner chain wrappers first, then", + "# the orchestration, then any outer wrappers (dedup / synthetic base) that wrap it", + "# " + "=" * 70, + *inner_blocks, + orch_block, + *entry_block, + *outer_blocks, + "", + "def call(flat_inputs): # noqa: F811", + *call_body, + "", + ] + return "\n".join(parts) + + +def _find_effectful_op(gm: GraphModule, get_effect: Any) -> Any: + """Return the first effectful op target reachable from ``gm``, or None. + + The target may be an ``OpOverload`` (e.g. ``aten::_print``) or a + ``HigherOrderOperator`` -- ``call_torchbind`` / ``hop_print`` / + ``invoke_leaf_function`` are registered ``_EffectType.ORDERED`` HOPs, not + OpOverloads -- so both are checked (``get_effect`` returns None for a + non-effectful HOP like ``cond``). + + Walks the graph and descends into any child GraphModule a node references -- a + HOP (cond/while_loop/scan) holds its body as a get_attr'd submodule or passes it + directly as a node arg -- so an effect nested inside a HOP subgraph is caught, not + just effects at the top level.""" + import torch + from torch.fx import GraphModule as _GraphModule + + seen: set[int] = set() + + def _scan(g: _GraphModule) -> Any: + if id(g) in seen: + return None + seen.add(id(g)) + for node in g.graph.nodes: + if ( + node.op == "call_function" + and isinstance( + node.target, + (torch._ops.OpOverload, torch._ops.HigherOrderOperator), + ) + and get_effect(node.target) is not None + ): + return node.target + for sub in _iter_subgraphs(g, node): + found = _scan(sub) + if found is not None: + return found + return None + + def _walk_values(value: Any) -> Iterator[_GraphModule]: + # A GraphModule can appear as a direct node arg OR nested one level (or more) + # inside a list/tuple/dict arg -- some HOPs pass their branch/body callables + # inside a container -- so descend into containers before the isinstance check, + # otherwise the recursive effect scan would never enter that nested subgraph. + if isinstance(value, _GraphModule): + yield value + elif isinstance(value, (list, tuple)): + for item in value: + yield from _walk_values(item) + elif isinstance(value, dict): + for item in value.values(): + yield from _walk_values(item) + + def _iter_subgraphs(g: _GraphModule, node: Any) -> Iterator[_GraphModule]: + # A child graph reaches a node either as an attribute fetched by get_attr or + # as a (possibly container-nested) argument (the form HOPs use for their + # branch/body callables). make_fx emits FLAT get_attr targets (e.g. + # true_graph_0) since _scan recurses per-GraphModule, so a plain getattr + # suffices (no dotted walk needed here). + if node.op == "get_attr": + attr = getattr(g, node.target, None) + if isinstance(attr, _GraphModule): + yield attr + for arg in (*node.args, *node.kwargs.values()): + yield from _walk_values(arg) + + return _scan(gm) + + +def _graph_has_dynamic_shapes(gm: GraphModule) -> bool: + """True if any placeholder is itself a SymInt or carries symbolic (SymInt) size, + stride, or storage-offset metadata -- i.e. the graph was traced with dynamic dims. + Drives the shapes mode for the capture pass: dynamic graphs stay dynamic, static + graphs specialize so the composer can bake their (static) view metadata. Strides and + storage offset are checked too, not just sizes: a graph dynamic solely via symbolic + strides has static sizes, and treating it as static would silently specialize the + artifact to the example strides. (Unbacked symints appearing only in intermediates, + not on any placeholder, are still missed here, but such a graph fails loudly + downstream when emit_value rejects the still-symbolic metadata.)""" + import torch + + def _is_symbolic(v: Any) -> bool: + return isinstance(v, torch.SymInt) + + for node in gm.graph.nodes: + if node.op != "placeholder": + continue + val = node.meta.get("val") + if _is_symbolic(val): + return True + if isinstance(val, torch.Tensor) and ( + any(_is_symbolic(s) for s in val.shape) + or any(_is_symbolic(s) for s in val.stride()) + or _is_symbolic(val.storage_offset()) + ): + return True + return False + + +def compile_to_python( + gm: GraphModule, + example_inputs: Sequence[Any], + *, + options: dict[str, Any] | None = None, +) -> tuple[str, bytes | None]: + """Compile ``gm`` to ``(python_code, cache)``; see the module docstring. + + THREADING: serialized by a process-global lock (``_COMPILE_LOCK``). The wrapper-source + capture is thread-local, but the AOTAutograd pass and the inner inductor compile both + swap process-global cache state (``CacheArtifactManager.with_fresh_cache()``); a + concurrent compile on another thread would corrupt the captured wrappers or cache + artifacts, so concurrent calls (including via ``torch.compiler.precompile``) are + serialized rather than run in parallel. + """ + import copy + + import torch + from torch._higher_order_ops.effects import _get_effect + from torch._inductor import compile_to_python as _inductor_compile_to_python + from torch._inductor.compile_fx import compile_fx + from torch._inductor.standalone_compile import ( + _resolve_ignore_shape_env, + _standalone_context, + ) + from torch.fx.graph_module import _share_torchbind_and_process_group_on_deepcopy + + from .utils import make_boxed_func + + # Validate up front: this layer dereferences ``gm.graph`` (the effectful-op scan + # below) before reaching inductor's own type-check, so a non-GraphModule would + # otherwise surface as an opaque AttributeError instead of this clear contract error. + if not isinstance(gm, torch.fx.GraphModule): + raise TypeError( + "aot_autograd.compile_to_python expects a post-AOTAutograd " + f"torch.fx.GraphModule, got {type(gm)}." + ) + + # Effectful ops thread effect tokens through a calling convention the standalone + # composition does not reproduce (and their with_effects HOP is non-cacheable); + # reject them up front with a concrete reason. Not supported yet. (Detected here + # too, not only in torch.compiler.precompile's capture-time guard, so direct callers of + # this lowering get the same clear failure rather than a silently-wrong artifact.) + # Scan recursively: a HOP (cond/while_loop/scan) carries its body as a child + # GraphModule referenced by a get_attr node (or passed directly as a node arg), so + # effects nested in such a subgraph would be missed by a top-level-only scan. + effectful = _find_effectful_op(gm, _get_effect) + if effectful is not None: + raise NotImplementedError( + "aot_autograd.compile_to_python cannot lower this graph to standalone " + f"source: it contains an effectful op ({effectful}), which is not " + "supported yet." + ) + + with _COMPILE_LOCK: + # Run AOTAutograd ONCE to do two things: (1) produce the dense, decomposed, + # functionalized inner graph, and (2) codegen its runtime-wrapper chain, which the + # thread-local ``capture_generated_sources`` sink records. A capture-only inner + # compiler grabs the dense graph and returns a placeholder boxed callable, so + # AOTAutograd still builds and codegen's the wrappers AROUND it -- that codegen is + # what we capture. Inductor is NOT run in this pass; it runs exactly once below, on + # the captured dense graph, via the ``_inductor_compile_to_python`` call (which + # drives inductor's ``compile_fx_inner`` directly, not a re-entry into AOTAutograd). + # The composer swaps the placeholder (the wrappers' inner reference) for the + # inner inductor ``call`` by object identity, so the placeholder is only a + # compile-time token and never runs. + captured: list[GeneratedSource] = [] + dense: dict[str, Any] = {} + + def _capture_inner_compile(dense_gm, dense_inputs, **kwargs): + if "gm" in dense: + raise NotImplementedError( + "aot_autograd.compile_to_python does not support a graph whose " + "AOTAutograd lowering emits more than one inner forward graph." + ) + dense["gm"] = dense_gm + # Retain the placeholder's IDENTITY: it is the authoritative inner call the + # runtime-wrapper chain closes over. The composer needs it to tell the inner + # call apart from the orchestration's own outer closure (both surface as a + # wrapper's inner-ref yet neither is a captured wrapper fn), which is what + # separates INNER wrappers from the OUTER dedup / synthetic-base wrappers. + placeholder = make_boxed_func(dense_gm.forward) + dense["placeholder"] = placeholder + return placeholder + + # Drive inductor's own ``compile_fx`` (i.e. its exact AOTAutograd invocation -- + # decomposition table + aot config) but swap in the capture inner compiler so the + # dense graph is intercepted before codegen and no inductor compile happens. Using + # compile_fx (rather than calling aot_autograd directly) guarantees the dense graph + # matches what the step-2 inductor compile below expects. Pick the shapes mode from + # the graph (there is no dynamic_shapes knob): a symbolically-traced graph uses + # ``"from_graph"`` to stay dynamic, a static one ``"from_example_inputs"`` to + # specialize -- matching what the composer can bake (symbolic view metadata is + # rejected downstream). no_grad pins the inference path (one forward module). + # Deepcopy first so compile_fx cannot mutate the caller's gm (torchbind + # ProcessGroups smuggled through as shared references). Note: the raw-collective / + # torchbind rewrites are inductor-lowering prereqs and belong to the step-2 inductor + # compile, which applies them to the dense graph -- not duplicated here. + shapes_mode = ( + "from_graph" if _graph_has_dynamic_shapes(gm) else "from_example_inputs" + ) + with ( + torch.no_grad(), + _standalone_context(gm, shapes_mode, aot=False), + capture_generated_sources(captured), + ): + with _share_torchbind_and_process_group_on_deepcopy(): + gm_owned = copy.deepcopy(gm) + compile_fx( + gm_owned, + example_inputs, + # Placeholder returns a boxed callable, not a full OutputCode; AOTAutograd + # only wraps it (never inductor-post-compiles it), so this is fine at runtime. + inner_compile=_capture_inner_compile, # pyrefly: ignore[bad-argument-type] + ignore_shape_env=_resolve_ignore_shape_env(shapes_mode), + ) + if "gm" not in dense: + raise RuntimeError( + "aot_autograd.compile_to_python: AOTAutograd never reached the inner " + "forward compiler, so no dense graph was captured." + ) + + inner_python, cache = _inductor_compile_to_python( + dense["gm"], example_inputs, options=options + ) + source = _compose_standalone_module( + inner_python, captured, dense["placeholder"] + ) + return source, cache + + +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`` -- the + inverse of ``compile_to_python``: (python_code, cache) in, runnable ``call`` out. + + The composed module is self-contained -- the inductor kernels and the pure-Python + runtime wrappers are inlined -- so this delegates straight to the inductor loader: + ``python_code`` runs standalone (kernels JIT-compile on first use), and ``cache`` (the + inductor accelerator bundle this layer forwards) warms the kernel caches so exec loads + the precompiled binaries instead of recompiling. There is no separate aot-level load + step: exec'ing the module yields the aot-composed top-level ``call`` directly, and the + wrappers carry no kernels to load. + """ + from torch._inductor import load_from_python as _inductor_load_from_python + + return _inductor_load_from_python(python_code, cache) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..50e0cb5d9fed8f41f01da498ac60c639443bd775 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py @@ -0,0 +1,907 @@ +""" +Contains various utils for AOTAutograd, including those for handling collections. +""" + +import copy +import dataclasses +import logging +import operator +import sys +import warnings +from collections.abc import Callable, Sequence +from contextlib import nullcontext +from functools import partial, wraps +from typing import Any, overload, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar, TypeVarTuple, Unpack + +import torch +import torch.utils._pytree as pytree +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class_obj +from torch._logging import getArtifactLogger +from torch._subclasses.fake_tensor import is_fake_tensor +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import py_sym_types + + +_T = TypeVar("_T") +if TYPE_CHECKING: + from torch.distributed._functional_collectives import AsyncCollectiveTensor + + from .schemas import AOTConfig, ViewAndMutationMeta + + +KNOWN_TYPES = [ + torch.Tensor, + BackwardState, + int, + str, + float, + bool, + type(None), + *py_sym_types, + FakeScriptObject, + torch.ScriptObject, +] + +aot_graphs_effects_log = getArtifactLogger(__name__, "aot_graphs_effects") +annotation_log = getArtifactLogger(__name__, "annotation") + +strict_zip = partial(zip, strict=True) + + +def get_loaded_async_collective_tensor_type() -> type["AsyncCollectiveTensor"] | None: + """Return the ACT type if distributed collectives are already loaded.""" + if "torch.distributed._functional_collectives" not in sys.modules: + return None + from torch.distributed._functional_collectives import AsyncCollectiveTensor + + return AsyncCollectiveTensor + + +def import_async_collective_tensor_type() -> type["AsyncCollectiveTensor"]: + """Import and return the ACT type.""" + from torch.distributed._functional_collectives import AsyncCollectiveTensor + + return AsyncCollectiveTensor + + +def is_async_collective_tensor_type(pytype: type) -> bool: + """Whether pytype is the AsyncCollectiveTensor type (False if not loaded).""" + act = get_loaded_async_collective_tensor_type() + return act is not None and pytype is act + + +def partial_flatten_asdict(obj: object) -> Any: + if dataclasses.is_dataclass(obj): + return { + field.name: getattr(obj, field.name) for field in dataclasses.fields(obj) + } + elif isinstance(obj, (list, tuple)): + return obj.__class__([partial_flatten_asdict(item) for item in obj]) + elif isinstance(obj, dict): + return {k: partial_flatten_asdict(v) for k, v in obj.items()} + else: + return obj + + +@overload +def normalize_as_list(x: _T) -> list[_T]: ... +@overload +def normalize_as_list(x: tuple[_T, ...]) -> list[_T]: ... +@overload +def normalize_as_list(x: list[_T]) -> list[_T]: ... + + +def normalize_as_list(x: object) -> list[object]: + if isinstance(x, tuple): + return list(x) + elif isinstance(x, list): + return x + return [x] + + +def _get_autocast_states() -> list[Any]: + return [ + torch.is_autocast_enabled("cuda"), + torch.is_autocast_enabled("cpu"), + torch.get_autocast_dtype("cuda"), + torch.get_autocast_dtype("cpu"), + torch.is_autocast_cache_enabled(), + ] + + +def make_boxed_func(f: Callable[..., Any]) -> Callable[[list[Any]], Any]: + @simple_wraps(f) + def g(args: list[Any]) -> Any: + return f(*args) + + # pyrefly: ignore[missing-attribute] + g._boxed_call = True + return g + + +def make_boxed_compiler( + compiler: Callable[..., Any], +) -> Callable[..., Any]: + @wraps(compiler) + def f(fx_g: Any, inps: Any) -> Any: + out_f = compiler(fx_g, inps) + fx_g = make_boxed_func(out_f) + return fx_g + + return f + + +def call_func_at_runtime_with_args( + f: Callable[..., Any], + args: Sequence[Any], + steal_args: bool = False, + disable_amp: bool = False, +) -> list[Any]: + if not steal_args: + args = list(args) + if not isinstance(args, list): + raise AssertionError(f"args must be a list, got {type(args)}") + + context = torch._C._DisableAutocast if disable_amp else nullcontext + with context(): + if getattr(f, "_boxed_call", False): + out = normalize_as_list(f(args)) + else: + # TODO: Please remove soon + # https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670 + warnings.warn( + "Your compiler for AOTAutograd is returning a function that doesn't take boxed arguments. " + "Please wrap it with functorch.compile.make_boxed_func or handle the boxed arguments yourself. " + "See https://github.com/pytorch/pytorch/pull/83137#issuecomment-1211320670 for rationale.", + stacklevel=2, + ) + out = normalize_as_list(f(*args)) + return out + + +# Inspired by autodidax (thanks!) +class PytreeThunk: + spec: pytree.TreeSpec | None = None + # These are some kinda dumb microoptimizations that save about 3-4 us of overhead. + is_simple: bool | None = ( + None # if the output spec is a tuple/list, we won't bother unflattening it. + ) + is_really_simple: bool | None = None # if the output spec is a LeafSpec + + def set(self, spec: pytree.TreeSpec) -> None: + if not (self.spec is None or self.spec == spec): + raise AssertionError(f"spec mismatch: existing={self.spec}, new={spec}") + if spec is None: + raise AssertionError("spec must not be None") + self.spec: pytree.TreeSpec = spec + if self.spec.type in {tuple, list} and all( + child.is_leaf() for child in spec.children() + ): + self.is_simple = True + if self.spec.is_leaf(): + self.is_really_simple = True + + def unflatten(self, x: Sequence[Any]) -> Any: + if self.is_really_simple: + return x[0] + if self.is_simple: + return x + if self.spec is None: + raise AssertionError("spec must be set before calling unflatten") + return pytree.tree_unflatten(x, self.spec) + + +# Creates a function that returns flattened inputs and outputs +# Also returns the output tree spec, which is needed to recover the "unflattened" +# output tree structure later. +def create_tree_flattened_fn( + fn: Callable[..., Any], + args: Sequence[Any], + kwargs: dict[str, Any] | None = None, +) -> tuple[Callable[..., list[Any]], PytreeThunk]: + if kwargs is None: + kwargs = {} + # Save the args_spec for flat_tensor_args to unflatten while tracing + _, tensor_args_spec = pytree.tree_flatten((args, kwargs)) + out_spec = PytreeThunk() + + def flat_fn(*flat_args: Any) -> list[Any]: + # The input are flattened tensor args. Prepare the args in the + # order that original function expects. Add static args as well. + # They will appear as tensor constants in the traced graph. + nonlocal out_spec + args, kwargs = pytree.tree_unflatten(flat_args, tensor_args_spec) + tree_out = fn(*args, **kwargs) + flat_out, spec = pytree.tree_flatten(tree_out) + for i in flat_out: + is_known_type = isinstance(i, tuple(KNOWN_TYPES)) or is_custom_class_obj(i) + if not is_known_type: + raise RuntimeError( + f"Found {type(i)} in output, which is not a known type. " + "If this type holds tensors, you need to register a pytree for it. " + "See https://github.com/pytorch/functorch/issues/475 for a brief " + "explanation why. If you don't need to register a pytree, please " + "leave a comment explaining your use case and we'll make this more " + "ergonomic to deal with" + ) + out_spec.set(spec) + return flat_out + + # Can't use functools.wraps here because the wrapper has different + # calling convention + if hasattr(fn, "_orig_mod"): + # pyrefly: ignore[missing-attribute] + flat_fn._orig_mod = fn._orig_mod + + return flat_fn, out_spec + + +# This function takes in a tensor t, and returns one of t, t.view(), or t.clone(). +# When tracing the joint forward + backward, for any inputs in the graph that are mutated, +# we need to clone them first (and similarly for metadata-only mutations, we need to view them first). +# The idea is that when we trace the backward, we need to pass in the *original* primals +# to autograd.grad(), before they were mutated. +# Note: when we have synthetic base inputs, we need to clone them *before* creating views off of them. +# This means that "idx" here represents the index of the (potentially) synthetic base. +# What we need to do is: +# (1) map the current (post-synthetic-base calling convention) input argument index +# to int index pre-synthetic-base-calling-convention. +# (2) There could be multiple, if this index corresponds to a synthetic base +# that has multiple input aliases. +# (3) If any of those corresponding inputs get metadata mutations, then we clone the base. +def maybe_to_fresh_input(idx: int, t: Any, meta: "ViewAndMutationMeta") -> Any: + if not isinstance(t, torch.Tensor): + return t + if idx in meta.mutated_inp_runtime_indices: + # We only need to bother cloning mutated inputs that participate in autograd. + if meta.input_info[idx].requires_grad and meta.input_info[idx].mutates_data: + # Make sure the primal we pass to autograd.grad() + # sees the tensor before the mutation + return t.clone() + if meta.input_info[idx] and meta.input_info[idx].mutates_metadata: + # Make sure the primal we pass to autograd.grad() + # sees the tensor before the metadata mutation + return t.view(t.shape) + return t + + +def is_with_effects(node: torch.fx.Node) -> bool: + if ( + node.op == "call_function" + and node.target is torch.ops.higher_order.with_effects + ): + return True + elif ( + node.op == "call_function" + and node.target is torch.ops.higher_order.invoke_subgraph + ): + # Check if subgraph has effects by looking in the cache + 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( + f"expected InvokeSubgraphCache, got {type(invoke_subgraph_cache)}" + ) + # pyrefly: ignore[bad-argument-type] + effects = invoke_subgraph_cache.get_effects(node.args[1]) + return effects is not None + return False + + +def unlift_tokens( + fw_module: torch.fx.GraphModule, + fw_metadata: "ViewAndMutationMeta", + aot_config: "AOTConfig", + bw_module: torch.fx.GraphModule | None = None, +) -> None: + # Remove the tokens from the inputs/outputs of the graph since inductor does + # not want these extra inputs/outputs, and replace them with + # _make_token() to create a token, and _sink_tokens() to collect the + # tokens. See Note [Side-Effectful Tokens in AOTAutograd] + # Logic: + # 1. In the case of with_effects: + # Before: + # ``` + # def forward(self, token, arg1_1): + # with_effects = torch.ops.higher_order.with_effects(token, ...) + # getitem = with_effects[0] + # getitem_1 = with_effects[0] + # return (getitem, getitem_1) + # ``` + # + # After: + # ``` + # def forward(self, arg1_1): + # _make_token_default = torch.ops.prims._make_token.default() + # with_effects = torch.ops.higher_order.with_effects(_make_token_default, ...) + # getitem = with_effects[0] + # getitem_1 = with_effects[0] + # _sink_tokens_default = torch.ops.prims._sink_tokens.default([getitem]); + # return (getitem_1,) + # ``` + # + # 2. In the case of an invoke_subgraph node, we will use the + # InvokeSubgraphCache to determine if the subgraph has effects. Then we will + # turn it into a `with_effects` node. This is so that at the toplevel graph, + # the nodes will have the correct with_effects threading. We will apply this + # pass recursively to submodules so the tokens will be removed from the + # subgraph's inputs. + # + # Before: + # ``` + # def forward(self, token, arg1_1): + # repeated_subgraph0 = self.repeated_subgraph0 + # invoke_subgraph = torch.ops.higher_order.invoke_subgraph( + # repeated_subgraph0, 'subgraph_0', token, x, arg1_1) + # getitem = invoke_subgraph[0] + # getitem_1 = invoke_subgraph[1] + # return (getitem, getitem1) + # ``` + # + # After: + # ``` + # def forward(self, arg1_1): + # _make_token_default = torch.ops.prims._make_token.default() + # repeated_subgraph0 = self.repeated_subgraph0 + # with_effects_1 = torch.ops.higher_order.with_effects( + # _make_token_default, torch.ops.higher_order.invoke_subgraph, + # repeated_subgraph0, 'subgraph_0', arg1_1) + # getitem = with_effects_1[0] + # getitem_1 = with_effects_1[1]; with_effects_1 = None + # _sink_tokens_default = torch.ops.prims._sink_tokens.default([getitem]) + # return (getitem_1,) + # ``` + # + # 3. The toplevel module should have the following invariants: + # forward: + # expected_num_erased_inputs == len(fw_metadata.tokens) + # expected_num_erased_outputs == len(fw_metadata.tokens) + # backward: + # expected_num_erased_inputs == fw_metadata.num_backward_tokens + # expected_num_erased_outputs == fw_metadata.num_backward_tokens + num_forward_tokens = len(fw_metadata.tokens) + num_backward_tokens = fw_metadata.num_backward_tokens + + def replace_input_token_with_make_token( + module: torch.fx.GraphModule, node: torch.fx.Node + ) -> None: + with module.graph.inserting_before(node): + new_token_node = module.graph.call_function( + torch.ops.prims._make_token.default, () + ) + new_token_node.meta["val"] = torch.tensor([]) + new_token_node.meta["tensor_meta"] = torch.tensor([]) + node.replace_all_uses_with(new_token_node) + module.graph.erase_node(node) + + def get_output_tokens(node: torch.fx.Node) -> set[torch.fx.Node]: + output_tokens = set() + for user in list(node.users.keys()): + # Check if this is a getitem accessing index 0 (the token) + if ( + user.op == "call_function" + and user.target is operator.getitem + and len(user.args) > 1 + and user.args[1] == 0 + ): + # Check if this getitem is used in an output + for user_user in list(user.users.keys()): + if user_user.op == "output": + output_tokens.add(user) + return output_tokens + + def _unlift_tokens_from_module_helper( + module: torch.fx.GraphModule, + subgraph_str: str, + expected_num_erased: int | None, + ) -> None: + input_token_nodes = set() + output_token_nodes = set() + + for node in module.graph.nodes: + if ( + node.op == "call_function" + and node.target is torch.ops.higher_order.with_effects + ): + if node.args[0].op == "placeholder": + input_token_nodes.add(node.args[0]) + replace_input_token_with_make_token(module, node.args[0]) + + tokens_from_with_effects = get_output_tokens(node) + output_token_nodes = output_token_nodes | tokens_from_with_effects + + elif ( + node.op == "call_function" + and node.target is torch.ops.higher_order.invoke_subgraph + ): + subgraph_node, identifier, *operands = node.args + + # Check if subgraph has effects by looking in the cache + from torch._guards import InvokeSubgraphCache, TracingContext + + effects = None + 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( + f"expected InvokeSubgraphCache, got {type(invoke_subgraph_cache)}" + ) + effects = invoke_subgraph_cache.get_effects(identifier) + + if effects is not None: + # Wrap invoke_subgraph with with_effects + # Before: invoke_subgraph(subgraph, id, token, *args) -> (token_out, result) + # After: with_effects(token, invoke_subgraph, subgraph, id, *args) -> (token_out, result) + # + # Note: The subgraph itself will be unlifted separately when we iterate + # through named_modules() below. + + num_tokens = len(effects) + if num_tokens != 1: + raise AssertionError( + f"Multiple token subgraph NYI, got {num_tokens} tokens" + ) + token_args = operands[:num_tokens] + non_token_args = operands[num_tokens:] + + # Create with_effects wrapper around invoke_subgraph + # with_effects(token, op, *args) where op is invoke_subgraph + # Pass the subgraph and non-token args to invoke_subgraph + with module.graph.inserting_before(node): + new_node = module.graph.call_function( + torch.ops.higher_order.with_effects, + # pyrefly: ignore [bad-argument-type] + ( + token_args[0], # pyrefly: ignore[bad-argument-type] + torch.ops.higher_order.invoke_subgraph, + subgraph_node, + identifier, + *tuple(non_token_args), + ), + ) + node.replace_all_uses_with(new_node) + new_node.meta = node.meta + module.graph.erase_node(node) + + for token in token_args: + if token.op == "placeholder": + input_token_nodes.add(token) + replace_input_token_with_make_token(module, token) + + # Get output tokens from the new with_effects node + tokens_from_invoke_subgraph = get_output_tokens(new_node) + output_token_nodes = ( + output_token_nodes | tokens_from_invoke_subgraph + ) + + if not output_token_nodes and not input_token_nodes: + return + + output_node = next(reversed(module.graph.find_nodes(op="output"))) + if output_node is None: + raise AssertionError("output node not found in graph") + with module.graph.inserting_before(output_node): + module.graph.call_function( + torch.ops.prims._sink_tokens.default, + (list(output_token_nodes),), + ) + new_out_args = tuple( + [out for out in output_node.args[0] if out not in output_token_nodes] + ) + output_node.args = (new_out_args,) + + if expected_num_erased: + if len(input_token_nodes) != expected_num_erased: + raise AssertionError( + f"{subgraph_str} num_erased_inputs:{len(input_token_nodes)} " + f"{input_token_nodes} != expected {expected_num_erased} \n" + f"{fw_module.print_readable(print_output=False)}" + ) + if len(output_token_nodes) != expected_num_erased: + raise AssertionError( + f"{subgraph_str} num_erased_outs:{len(output_token_nodes)} " + f"{output_token_nodes} != expected {expected_num_erased} \n" + f"{fw_module.print_readable(print_output=False)}" + ) + + module.recompile() + + def unlift_tokens_from_module( + module: torch.fx.GraphModule, subgraph_str: str, expected_num_erased: int + ) -> None: + for name, m in module.named_modules(): + if isinstance(m, torch.fx.GraphModule): + if name == "": + _unlift_tokens_from_module_helper( + m, subgraph_str, expected_num_erased + ) + else: + # Subgraph -- we may or may not have effects applied + _unlift_tokens_from_module_helper(m, f"{subgraph_str}_{name}", None) + + if num_forward_tokens > 0: + if aot_config.enable_log: + from torch._dynamo.utils import lazy_format_graph_code + + aot_graphs_effects_log.debug( + "%s", + lazy_format_graph_code( + "Forward graph before unlifting tokens", + fw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + unlift_tokens_from_module( + fw_module, + "forward", + num_forward_tokens, + ) + + if bw_module is not None and num_backward_tokens > 0: + if aot_config.enable_log: + from torch._dynamo.utils import lazy_format_graph_code + + aot_graphs_effects_log.debug( + "%s", + lazy_format_graph_code( + "Backward graph before unlifting tokens", + bw_module, + aot_config.aot_id, + include_stride=True, + include_device=True, + colored=True, + ), + ) + unlift_tokens_from_module(bw_module, "backward", num_backward_tokens) + + # This is sad, but we need to update the metadata to get rid of + # the tokens. + fw_metadata.tokens = {} + fw_metadata.num_backward_tokens = 0 + + +def root_module_when_exporting_non_strict( + flat_fn: Callable[..., Any], +) -> torch.nn.Module | None: + # When exporting in non-strict mode, we wrap the root module in a specific pattern. + # See `_aot_export_non_strict` in torch.export._trace.py. + # We look for that wrapping pattern here. + if hasattr(flat_fn, "_orig_mod") and hasattr(flat_fn._orig_mod, "_export_root"): + return flat_fn._orig_mod._export_root + else: + return None + + +def _is_forward_node_with_seq_nr(node: torch.fx.Node) -> bool: + # For now, assume that if nn_module_stack_metadata is populated, this + # node is from the forward. Ignore nodes without `seq_nr`. + # TODO(future): there is likely a less brittle way to do this by walking + # the descendants of graph inputs corresponding to fwd inputs, didn't + # seem obvious at first glance on how to partition graph inputs into + # fwd vs bwd without relying on string names. + return node.meta.get("partitioner_tag") != "is_backward" and "seq_nr" in node.meta + + +def _is_backward_node_with_seq_nr(node: torch.fx.Node) -> bool: + # For now, assume that if nn_module_stack_metadata is not populated, + # this node is from the backward. Ignore nodes without `seq_nr`. + # TODO(future): there is likely a less brittle way to do this, same + # as with the forward. + return node.meta.get("partitioner_tag") == "is_backward" and "seq_nr" in node.meta + + +def _collect_fwd_nodes_from_subgraph( + fx_g: torch.fx.GraphModule, fwd_seq_nr_to_node: dict[str, torch.fx.Node] +) -> None: + """Collect forward nodes from a single subgraph into the global mapping.""" + for node in fx_g.graph.nodes: + if not _is_forward_node_with_seq_nr(node): + continue + seq_nr = node.meta["seq_nr"] + if seq_nr in fwd_seq_nr_to_node: + # If we already saw an op with the current `seq_nr`, that means + # that the current op did not create an autograd node, and there + # is no corresponding backward node, so we skip. + continue + fwd_seq_nr_to_node[seq_nr] = node + + +def _copy_metadata_to_bw_nodes_in_subgraph( + fx_g: torch.fx.GraphModule, fwd_seq_nr_to_node: dict[str, torch.fx.Node] +) -> None: + """Copy metadata from forward nodes to backward nodes in a single subgraph.""" + for node in fx_g.graph.nodes: + annotation_log.debug("node: %s", node.name) + seq_nr = node.meta.get("seq_nr") + annotation_log.debug("seq_nr: %s", seq_nr) + + if not _is_backward_node_with_seq_nr(node): + continue + + # We exclude gradient accumulation nodes from copying tags + if node.meta.get("is_gradient_acc", False): + annotation_log.debug("is_gradient_acc") + continue + + # fwd_node should always exist, but handle non-existence just in case + fwd_node = fwd_seq_nr_to_node.get(node.meta["seq_nr"]) + if fwd_node is not None: + node.meta["fwd_nn_module_stack"] = fwd_node.meta.get("nn_module_stack") + node.meta["fwd_source_fn_stack"] = fwd_node.meta.get("source_fn_stack") + # TODO: better to change to a specific field of custom? + custom = fwd_node.meta.get("custom") + if custom is not None: + # Merge rather than overwrite so bw-only keys survive + # fw keys win on conflict. + node.meta["custom"] = { + **node.meta.get("custom", {}), + **copy.deepcopy(custom), + } + + +def copy_fwd_metadata_to_bw_nodes(fx_g: torch.fx.GraphModule) -> None: + """ + Input: `fx_g` which contains the joint fwd+bwd FX graph created by + aot_autograd. + + This function walks the graph and copies over metadata from forward nodes + to backward nodes, using the `seq_nr` field as a one-to-many mapping + from forward node to backward node. This metadata is useful for performance + profiling and debugging. + + This function supports matching forward and backward nodes across different + subgraphs (e.g., in recursive submodules from HOPs), enabling backward nodes + in any submodule to match forward nodes in any submodule. + """ + + # Build a global mapping of seq_nr to forward nodes across all subgraphs + fwd_seq_nr_to_node: dict[str, torch.fx.Node] = {} + + # First pass: collect all forward nodes from all subgraphs + for submod in fx_g.modules(): + if isinstance(submod, torch.fx.GraphModule): + _collect_fwd_nodes_from_subgraph(submod, fwd_seq_nr_to_node) + + if annotation_log.isEnabledFor(logging.DEBUG): + for k, v in fwd_seq_nr_to_node.items(): + annotation_log.debug("forward:: key: %s, value: %s", k, v) + + # Second pass: copy metadata to backward nodes in all subgraphs + # using the global forward mapping + for submod in fx_g.modules(): + if isinstance(submod, torch.fx.GraphModule): + _copy_metadata_to_bw_nodes_in_subgraph(submod, fwd_seq_nr_to_node) + + +def register_buffer_assignment_hook( + mod: torch.nn.Module, assigned_buffers: dict[str, str] +) -> Any: + """ + Register a hook that intercepts buffer assignments. + This is used to detect when a buffer is assigned to, and then we can + map that buffer to the corresponding proxy node in the graph. + """ + + def _map_assigned_buffer_to_proxy( + _mod: torch.nn.Module, name: str, buffer: Any + ) -> Any: + # We intercept buffer assignments on the root module through this hook. + if _mod._buffers is mod._buffers: + # either buffer is a functional tensor, which wraps a fake tensor + if isinstance(buffer, FunctionalTensor): + buffer = buffer.from_functional() + # or buffer is a fake tensor + if not is_fake_tensor(buffer): + raise AssertionError(f"expected FakeTensor, got {type(buffer)}") + # The fake tensor in turn is associated with a proxy node. + proxy_mode = torch.fx.experimental.proxy_tensor.get_proxy_mode() + if proxy_mode is None: + raise AssertionError("proxy_mode must not be None") + proxy = torch.fx.experimental.proxy_tensor.get_proxy_slot( + buffer, proxy_mode.tracer + ).proxy.node + # We map the assigned buffer to this proxy node. + assigned_buffers[name] = proxy.name + return buffer + + return torch.nn.modules.module.register_module_buffer_registration_hook( + _map_assigned_buffer_to_proxy + ) + + +def contain_metadata_mutation_ops(module: torch.fx.GraphModule) -> bool: + """ + Checks if the module contains any metadata mutation ops. + """ + for node in module.graph.nodes: + if ( + node.op == "call_function" + and hasattr(node.target, "tags") + and torch.Tag.inplace_view in node.target.tags + ): + return True + return False + + +_GRAPHSAFE_RNG_DEVICE_TYPES: set[str] = {"cuda"} + + +def register_graphsafe_rng_device_type(device_type: str) -> None: + """Register a device type as supporting graphsafe RNG operations. + + The device backend module (``torch.``) must provide: + - ``_get_generator(device: torch.device) -> Generator``: return the default + generator for the given device. The generator must implement + ``graphsafe_get_state()``, ``graphsafe_set_state(state)``, and + ``clone_state()``. + - ``get_rng_state(device_index: int) -> Tensor``: return the current RNG + state tensor. + + Args: + device_type: The device type string (e.g. "cuda", "xpu"). + """ + from torch._prims.rng_prims import register_graphsafe_rng_dispatch + + key_name = torch._C._dispatch_key_for_device(device_type) + dispatch_key = getattr(torch._C.DispatchKey, key_name) + _GRAPHSAFE_RNG_DEVICE_TYPES.add(device_type) + register_graphsafe_rng_dispatch(dispatch_key) + + +def supports_graphsafe_rng(device: torch.device) -> bool: + """Check whether a device supports graphsafe RNG operations.""" + return device.type in _GRAPHSAFE_RNG_DEVICE_TYPES + + +def get_default_generator(device: torch.device) -> Any: + """Get the default RNG generator for a device. + + Calls ``torch.._get_generator(device)``. + """ + device_mod = getattr(torch, device.type, None) + if device_mod is None or not hasattr(device_mod, "_get_generator"): + raise AssertionError( + f"Device type '{device.type}' does not implement _get_generator. " + f"Registered graphsafe RNG types: {sorted(_GRAPHSAFE_RNG_DEVICE_TYPES)}." + ) + return device_mod._get_generator(device) + + +def get_device_rng_state(device: torch.device) -> torch.Tensor: + """Get the RNG state tensor for a device.""" + device_mod = getattr(torch, device.type, None) + if device_mod is not None and hasattr(device_mod, "get_rng_state"): + idx = device.index if device.index is not None else 0 + return device_mod.get_rng_state(idx) + return torch.get_rng_state() + + +def top_saved_tensors_hooks() -> Any: + return torch._C._autograd._top_saved_tensors_default_hooks(True) + + +def saved_tensors_hooks_are_inlineable(hooks: Any) -> bool: + if not hooks: + return False + pack, unpack = hooks + return isinstance(pack, torch.fx.GraphModule) and isinstance( + unpack, torch.fx.GraphModule + ) + + +_P = ParamSpec("_P") +_T = TypeVar("_T") +_S = TypeVar("_S") + + +def without_output_descs(f: Callable[_P, tuple[_T, _S]]) -> Callable[_P, _T]: + @wraps(f) + @simple_wraps(f) + def inner(*args: _P.args, **kwargs: _P.kwargs) -> _T: + return f(*args, **kwargs)[0] + + return inner + + +_P2 = ParamSpec("_P2") +_R = TypeVar("_R") +_R2 = TypeVar("_R2") + + +def simple_wraps( + f: Callable[_P, _R], +) -> Callable[[Callable[_P2, _R2]], Callable[_P2, _R2]]: + # NB: omit ('__module__', '__name__', '__qualname__') for ease of + # debugging + return wraps(f, assigned=("__doc__", "__annotations__", "__type_params__")) + + +_Ts = TypeVarTuple("_Ts") + + +def call_and_expect_output_descs( + fn: Callable[[*_Ts], tuple[Any, Any]], args: tuple[Unpack[_Ts]] +) -> tuple[Any, Any]: + from .descriptors import AOTOutput + + outs_pair = fn(*args) + if not (isinstance(outs_pair, tuple) and len(outs_pair) == 2): + raise AssertionError( + f"expected tuple of length 2, got {type(outs_pair)} with value {outs_pair}" + ) + outs, outs_descs = outs_pair + # The Tensor tests protects against the test when there are no outputs + out_vals, out_spec = pytree.tree_flatten(outs) + out_desc_vals, out_desc_spec = pytree.tree_flatten(outs_descs) + if out_spec != out_desc_spec: + raise AssertionError( + f"output spec mismatch: {fn_wrappers(fn)}, outs={outs}, outs_descs={outs_descs}, " + f"out_spec={out_spec}, out_desc_spec={out_desc_spec}" + ) + if any(isinstance(x, AOTOutput) for x in out_vals): + raise AssertionError( + f"unexpected AOTOutput in out_vals: {fn_wrappers(fn)}, outs={outs}, " + f"outs_descs={outs_descs}, out_vals={out_vals}" + ) + if not all( + isinstance(d, AOTOutput) + for (x, d) in zip(out_vals, out_desc_vals) + if isinstance(x, (torch.Tensor, torch.SymInt)) or type(x) is int + ): + raise AssertionError( + f"expected all descriptors to be AOTOutput: {fn_wrappers(fn)}, outs={outs}, " + f"outs_descs={outs_descs}, out_vals={out_vals}, out_desc_vals={out_desc_vals}" + ) + return outs_pair + + +def fn_wrappers(fn: Callable[..., Any]) -> list[Callable[..., Any]]: + fns = [fn] + f = fn + while hasattr(f, "__wrapped__"): + f = f.__wrapped__ + fns.append(f) + return fns + + +def _is_primal(node: torch.fx.Node) -> bool: + return ( + node.op == "placeholder" + and "tangents" not in str(node.target) + and not _is_bwd_seed_offset(node) + and not _is_fwd_seed_offset(node) + ) + + +def _is_tangent(node: torch.fx.Node) -> bool: + return node.op == "placeholder" and "tangents" in str(node.target) + + +def _is_bwd_seed_offset(node: torch.fx.Node) -> bool: + return node.op == "placeholder" and ( + "bwd_seed" in str(node.target) or "bwd_base_offset" in str(node.target) + ) + + +def _is_fwd_seed_offset(node: torch.fx.Node) -> bool: + return node.op == "placeholder" and ( + "fwd_seed" in str(node.target) or "fwd_base_offset" in str(node.target) + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/aot_autograd.py b/.venv/lib/python3.12/site-packages/torch/_functorch/aot_autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..a160ab80542ba34c5249f462eb554e5dccdce2f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/aot_autograd.py @@ -0,0 +1,1971 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import itertools +import time +from contextlib import nullcontext +from functools import wraps +from typing import Any, cast, Literal, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar +from unittest.mock import patch + +import torch +import torch._dynamo.logging +import torch.nn as nn +import torch.utils._pytree as pytree +import torch.utils.dlpack +from torch import Tensor +from torch._decomp.decompositions_for_rng import PhiloxStateTracker, rng_decompositions +from torch._dispatch.python import enable_python_dispatcher +from torch._dynamo import compiled_autograd +from torch._dynamo.utils import ( + CompileEventLogger, + dynamo_timed, + preserve_rng_state, + set_feature_use, +) +from torch._guards import detect_fake_mode +from torch._inductor.codecache import resolve_pre_grad_pass_timing + +# Runtime annotation consumers still resolve BoxedBool from module globals. +from torch._subclasses import FakeTensorMode +from torch._subclasses.fake_tensor import maybe_get_fake_mode +from torch.export._tree_utils import reorder_kwargs +from torch.fx.experimental.proxy_tensor import make_fx + +from . import config +from ._aot_autograd import autograd_cache +from ._aot_autograd.autograd_cache import ( + AOTAutogradCache, + should_use_local_autograd_cache, + should_use_remote_autograd_cache, +) +from ._aot_autograd.collect_metadata_analysis import ( + run_functionalized_fw_and_collect_metadata, +) +from ._aot_autograd.descriptors import ( + AOTInput, + BufferAOTInput, + DifferentiableAOTInput, + ParamAOTInput, + PlainAOTInput, +) +from ._aot_autograd.frontend_utils import ( + _detect_attribute_assignment, + _try_get_metadata_from_dynamo, + construct_fake_mode, + process_inputs, +) +from ._aot_autograd.functional_utils import ( # noqa: F401 + _check_if_mutation_can_be_in_graph, + are_all_mutations_hidden_from_autograd, + are_all_mutations_under_no_grad_or_inference_mode, + assert_functional_graph, + from_fun, + gen_alias_from_base, + has_data_mutation, + has_metadata_mutation, + is_fun, + sync_functional_tensor, + to_fun, +) +from ._aot_autograd.graph_capture_wrappers import ( # noqa: F401 + aot_dispatch_subclass, + create_functional_call, + create_functionalized_fn, + create_functionalized_rng_ops_wrapper, + create_joint, + fn_input_mutations_to_outputs, + fn_prepped_for_autograd, +) +from ._aot_autograd.graph_compile import ( + aot_stage1_graph_capture, + aot_stage2_compile, + aot_stage2_export, +) +from ._aot_autograd.input_output_analysis import ( # noqa: F401 + compute_overlapping_inputs, + create_graph_signature, + create_synthetic_base_metadata, + remove_dupe_metadata, +) +from ._aot_autograd.logging_utils import ( # noqa: F401 + callback_set, + describe_input, + format_guard_bug_msg, + get_aot_compilation_context, + get_aot_graph_name, + get_graph_being_compiled, + graph_being_compiled, + model_name, + nth_graph, + set_model_name, + setup_stacktrace_preservation_hooks, + track_graph_compiling, +) +from ._aot_autograd.runtime_wrappers import ( # noqa: F401 + AOTDedupeWrapper, + AOTSyntheticBaseWrapper, + SerializableCompiledFunction, +) +from ._aot_autograd.schemas import ( # noqa: F401 + ActInputPath, + AOTConfig, + AOTDispatchCompiler, + AOTGraphCapture, + AOTState, + BackwardSignature, + FakifiedFlatArgs, + FQN, + GraphInputName, + GraphOutputName, + GraphSignature, + InputAliasInfo, + JointWithDescriptors, + MutationType, + OpaqueMeta, + OutputAliasInfo, + OutputType, + SerializableAOTDispatchCompiler, + SubclassCreationMeta, + SubclassMeta, + TensorAlias, + ViewAndMutationMeta, +) +from ._aot_autograd.subclass_utils import ( # noqa: F401 + requires_subclass_dispatch, + unwrap_tensor_subclasses, + unwrap_tensor_subclasses_with_indices_to_original, + wrap_tensor_subclasses, + wrap_tensor_subclasses_maybe_joint, +) +from ._aot_autograd.to_standalone_python import ( # noqa: F401 + compile_to_python, + load_from_python, +) +from ._aot_autograd.utils import ( # noqa: F401 + _get_autocast_states, + call_func_at_runtime_with_args, + create_tree_flattened_fn, + KNOWN_TYPES, + make_boxed_compiler, + make_boxed_func, + maybe_to_fresh_input, + normalize_as_list, + partial_flatten_asdict, + PytreeThunk, + root_module_when_exporting_non_strict, + simple_wraps, + strict_zip, +) +from .partitioners import default_partition + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from torch._inductor.compile_fx import CompilerConfigExtra + from torch._inductor.output_code import OutputCode + from torch._inductor.utils import InputType + from torch._ops import OpOverload + from torch.fx.experimental.symbolic_shapes import ShapeEnv + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +zip = strict_zip + +# This global counter increments every time we compile a graph with +# AOTAutograd. You can use this to correlate runtime error messages +# with compile time (e.g., if you get an error at runtime saying +# compiled graph 3 failed, you can set a breakpoint at compile time +# for this graph number to investigate further at compile time.) +# +# NB: this is different from get_aot_compilation_context, which tracks +# each underlying graph that is compiled. In contrast, AOT_COUNTER +# corresponds to top-level invocations of aot_module/aot_function; +# one counter is allocated per entire compiled block (but this block +# may involve compiling multiple subgraphs; e.g., for forwards/backwards) +AOT_COUNTER = itertools.count() + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# AOT Autograd contains a pretty non-trivial amount of logic to handle edge cases around aliasing and mutation +# that are external to the graph (they show up as side effects in some way when you run the graph). +# +# Take a look at `test_aotdispatch.py TestAOTAutograd.test_input_mutation*` tests for some examples functions +# and what they're compiled graphs looks like. +# Below is a very long comment detailing several edge cases, and showing how AOT Autograd handles them. +# +# Note [AOT Autograd: input data mutations] +# +# If we compile a function that mutates inputs, then those input mutations are real side effects +# that a user expects to see after running the compiled graph. +# However, the graph that we want to send to a backend needs to be *entirely* functional. +# The way we reconcile this difference is that we remove the mutations completely from the graph that we compile +# but we update the graph to return (updated_inputs, user_outputs). +# In the epilogue that runs after the compiled graph is executed, we copy the updated inputs back to the originals. +# +# Example: original user code: +# def f(x): +# x.mul_(2) +# out = x.mul(3) +# return out +# +# After AOT Autograd compiles, we end up with a: +# (a) compiled graph +# (b) autograd.Function.forward() method, that executes the compiled graph +# (c) wrapper function, that calls the autograd.Function.forward() and performs the epilogue +# +# The output of (a, b, c) are all written below. +# +# def compiled_forward_graph(x): +# x_updated = x.mul(2) +# out = x_updated.mul(3) +# return x_updated, out +# +# # x_updated gets a gradient in the compiled backward +# def compiled_backward_graph(grad_x_updated, grad_out): +# grad_x = ... +# return grad_x +# +# def autograd.Function.forward(x): +# x_updated, out = compiled_forward_graph(x) +# return x_updated, out +# +# def compiled_wrapper(x): +# x_updated, out = autograd.Function.apply(x) +# x.copy_(x_updated) +# return out +# +# Another important thing to note is that updated inputs (due to data mutations) *do* participate +# in the compiled backward graph! Since the compiled forward graph gets N extra outputs +# (due to updated inputs showing up as graph outputs), +# The compiled backward gets an additional N inputs. +# That way, during the x.copy_(x_updated) bit in the epilogue, gradients will flow from the updated input +# back to the original input. + + +# Note [AOT Autograd: input metadata mutations] +# +# For the same reason as input mutations, we also don't put input metadata mutations in the graph. +# Instead, we return the updated version of the input (a view), and mutate the input's metadata outside of the graph +# +# Example: original user code: +# def f(x): +# x.t_() +# out = x.mul(3) +# return out +# +# AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function): +# def compiled_forward_graph(x): +# x_updated = x.t() +# out = x_updated.mul(3) +# return x_updated, out +# +# # x_updated does *not* get a gradient in the compiled backward +# def compiled_backward_graph(grad_out): +# grad_x = ... +# return grad_x +# +# def autograd.Function.forward(x): +# x_updated, out = compiled_forward_graph(x) +# return x_updated, out +# +# def compiled_wrapper(x): +# x_updated, out = autograd.Function.apply(x) +# x.as_strided_(x_updated) +# return out + + +# Note [AOT Autograd: outputs aliasing inputs or intermediates!] +# +# AOT Autograd needs special handling for outputs that alias graph inputs or intermediates! +# Why? +# (1) autograd.Function.forward() has a limitation, where views that returned in the forward cannot later be mutated. +# (2) views don't need to be compiled in the graph anyway - it's cheap to generate them outside of the compiled graph, +# in an epilogue. +# For outputs that alias inputs, we do the following: +# (a) *still* return the aliased output as a graph output +# (b) In the AOT Autograd wrapper/epilogue, we don't return that aliased output. Instead, we use it to regenerate the output. +# +# For outputs that alias *intermediates*, we do the following: +# (a) Return the output in the compiled forward, **and** return it's ._base (a graph intermediates) as an output in the forward +# (b) Use (output, graph_intermediate) to regenerate the alias, and return that to the user (instead of the compiled fw output). +# You might wonder why we return the aliased output directly in the graph (and making the graph compute it), +# only to not return it and instead generate a fresh alias off of the intermediate, +# instead of (say) just storing metadata about the size/stride of the output somewhere to generate the alias. There are two reasons: +# (1) Getting the actual alias tensor allows us to use view-replay to generate the alias, instead of an as_strided() call +# (2) Inductor (and other backends) are free to change the memory format of graph outputs, if it results in better performance. +# This can result in problems if a user later tries to .view() that output expecting it to have one set of strides, +# when it has a different set of strides. +# By including the view op directly in the graph, inductor takes that into account when deciding what memory format +# the graph intermediate should be. +# +# Another important thing to note is how our traced backward() graph handles aliases. +# (this applies to outputs aliasing inputs, outputs aliasing intermediates, +# *and* updated inputs returned in the compiled forward due to metadata-only mutations). +# Any outputs that alias (either inputs or intermediates) do NOT participate in the compiled backward graph +# It would be wasteful to include them in the compiled backward(), because we regenerate them eagerly +# at the end of the forward. +# +# Example: original user code: +# def f(x): +# out1 = x.t() +# intermediate = x.mul(2) +# out2 = intermediate.view(-1) +# return out1, out2 +# +# AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function): +# def compiled_forward_graph(x): +# out1 = x.t() +# intermediate = x.mul(2) +# out2 = intermediate.view(-1) +# # the compiled graph also returns the intermediate +# return out1, out2, intermediate +# +# # intermediate gets a gradient in the compiled backward. +# # both output aliases (out1 and out2) do not. +# def compiled_backward_graph(grad_intermediate): +# grad_x = ... +# return grad_x +# +# def autograd.Function.forward(x): +# out1, out2, intermediate = compiled_forward_graph(x) +# return out1, out2, intermediate +# +# def compiled_wrapper(x): +# out1, out2, intermediate = autograd.Function.apply(x) +# # regenerate out1 from the input +# out1_regenerated = out1._view_func(x) +# # regenerate out1 from the intermediate +# out2_regenerated = out2._view_func(intermediate) +# return out1_regenerated, out2_regenerated + + +# Note [AOT Autograd: mutations to inputs that alias other inputs] +# +# Another edge case that is (only partially) handled today is when an input is mutated, but itself aliases another input. +# AOT Autograd needs to **ensure** that functionalization knows that the two inputs are aliased to each other. +# That way, when the aliased input is accessed later in the graph, functionalization knows to "update" the alias +# given the mutation that occurred. +# +# This is handled by updating the calling convention: we create a "synthetic base" that becomes a new input +# in the compiled function, and we regenerate the original (aliased) inputs directly off of the base +# inside of the compiled function. +# +# This logic is fully encapsulated in aot_wrapper_synthetic_base() +# +# Example: original user code: +# def f(x, x_view): +# x.mul_(2) +# out = x * x_view +# return out +# f(x, x.view(-1)) +# +# AOT Autograd output (compiled graph, autograd.Function.forward(), wrapper function): +# def compiled_forward_graph(base) +# x = generate_x(base) +# x_view = generate_x_view(base) +# x_updated = x.mul(2) +# x_view_updated = x_updated.view(-1) +# out = x_updated * x_view_updated +# return x_updated, out +# +# # The calling convention change from (aliases) -> (base) happens +# # *outside* of the autograd.Function.forward(). +# # That means the forward() only has 1 input (base), +# # and the backward() only has 1 output (grad_base) +# def compiled_backward_graph(grad_out): +# grad_base = ... +# return grad_base +# +# def autograd.Function.forward(base): +# x_updated, out = compiled_forward_graph(base) +# return x_updated, out +# +# # The compiled wrapper is where we create synthetic bases. +# # The info on which inputs are mutated is also tracked *before* synthetic base creation. +# def compiled_wrapper(x, x_view): +# base = merge_view_inputs(x, x_view) +# x_updated, out = autograd.Function.apply(base) +# # x and x_view are aliased in eager mode, so this mutation to x will automatically affect x_view. +# x.copy_(x_updated) +# return out + + +# Note [AOT Autograd: Views to avoid tangents aliasing inputs] +# +# We view every forward output when creating out tangent tensors to handle the problematic +# case in which a subclass does extra aliasing between graph outputs/inputs in a way that +# is not visible above the subclass. +# +# Ordinarily, when constructing the joint function that we want to trace in AOTAutograd, +# we're guaranteed that the tangent tensors that we pass +# into the joint are distinct tensors from the primals. This is because when +# decide which forward outputs to create tangents for, we only create tangents +# for forward outputs that are not aliases of inputs (See Note +# [AOT Autograd: outputs aliasing inputs or intermediates!]). +# +# However, when wrapper tensor subclasses enter the picture, it is possible +# to have an output of the forward that is a subclass that is not an +# input / alias of an input, but one of its inner tensors is an alias! +# NestedTensor is an example: Performing an out-of-place pointwise op on a +# NestedTensor constructs a fresh NestedTensor that holds onto the input's +# offsets tensor directly. +# +# Having tangent tensors that are the same as the (primal) forward inputs, +# can cause problems during tracing as make_fx() will specialize on our +# duplicate inputs: If we passed in the same tensor for primals_1 and +# tangents_1 during tracing, make_fx() will happily sub out all usages of +# tangents_1 with primals_1 in the graph, which is not what we want. +# +# To work around this, we view every forward output when creating out tangent +# tensors so that tangents can never be the same as forward inputs even if +# forward inputs alias forward outputs. + +# Note [Side-Effectful Tokens in AOTAutograd] +# +# We allow some side-effectful operators in +# the post-AOTAutograd (functional) graph, such as prints and torchbind operations. +# To ensure that these side-effects are compatible to future graph passes that +# assume that the graph is functional, we will thread "effect tokens" to show +# data dependence between these side-effectful operators. Practically speaking, +# effect tokens are just dummy values (torch.tensor([])). The graph would look +# like the following: +# +# def gm(self, token0, reader): +# token1, frame = with_token(ordered_effect_op, (reader,), token0) +# frame = frame * 2 +# token2, frame2 = with_token(ordered_effect_op, (reader,), token1) +# frame2 = frame2 * 2 +# return token2, frame, frame2 +# +# We will pass the token as an input to the graph, thread it through +# side-effectful operators using the `with_effects` high order operator, and then +# return the updated token as an output. +# So the signature of the graph input would look something like +# (*tokens, *params_buffers, *user_inputs), and the signature of the graph +# output would look something like (*tokens, *outputs). +# +# However, Inductor does not want the concept of tokens in the final generated +# code's input and output. Since changing the graph signature inside of inductor +# is difficult, after generating the forward graph, we will run a pass to +# remove the tokens from the input and generate the following graph for Inductor, where +# the tokens are created and sunk within the graph, rather than as inputs and +# outputs: +# +# def gm(self, reader): +# token0 = torch.ops.prims._make_token() +# token1, frame = with_token(ordered_effect_op, (reader,), token0) +# frame = frame * 2 +# token2, frame2 = with_token(ordered_effect_op, (reader,), token1) +# frame2 = frame2 * 2 +# sink_token = torch.ops.prims._sink_tokens([token2]) +# return frame, frame2 + +# +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +aot_autograd_decompositions: dict[OpOverload, Callable[..., Any]] = {} + + +def create_aot_state( + stack: contextlib.ExitStack, + flat_fn: Callable[_P, _R], + fake_flat_args: FakifiedFlatArgs, + flat_args_descs: list[AOTInput], + aot_config: AOTConfig, + fake_mode: FakeTensorMode, + shape_env: ShapeEnv | None, +) -> AOTState: + """ + Traces the forward and backward graphs of the attr:`flat_fn` to generate a + joint graph. The joint graph is an Fx graph with Aten ops. Please refer to + the tracing mechanism to understand the graph capturing details. + + The joint graph is then passed through attr:`partition_fn` to isolate the + forward and backward portions, which are then respectively compiled via the + provided attr:`fw_compiler` and attr:`bw_compiler`. + + The resulting compiled forward and backward graphs are then wrapped up in a + ``torch.autograd.Function`` object. + + The calling convention here is that the first aot_config.num_params_buffers + inputs in flat_args are parameters and buffers, and the rest are inputs. + + We use this to assume that parameters/buffer's shapes don't change. + """ + + # Old name for now to avoid messing with stats. Also, note this is pushed + # on the stack, so it extends BEYOND this function + stack.enter_context( + dynamo_timed("create_aot_dispatcher_function", log_pt2_compile_event=True) + ) + + # This is the main entry point. + # TODO: Chillee argues that dynamo itself should pass in fake tensors to + # the list of arguments when compiling; at the moment we do not do this + + decompositions = aot_config.decompositions or {} + decompositions = { + **aot_autograd_decompositions, + **decompositions, + } + + if config.functionalize_rng_ops: + # Update the decompositions with functionalized random decompositions + decompositions = { + **rng_decompositions, + **decompositions, + } + + aot_config = dataclasses.replace( + aot_config, + decompositions=cast("dict[OpOverload, Callable[..., Any]]", decompositions), + ) + + # Check flat_args to see if they're already fake. If so, use that fake + # mode instead. + + python_dispatcher_mode = ( + enable_python_dispatcher() if shape_env is not None else nullcontext() + ) + + # See NOTE: [Deferring tensor pack/unpack hooks until runtime] + # If any saved tensor hooks are active, we **don't** want to trace them. + # Instead, we'll let them run at runtime, around the custom autograd.Function + # that we generate in torch.compile. + stack.enter_context(torch.autograd.set_multithreading_enabled(False)) + stack.enter_context(preserve_rng_state()) + stack.enter_context(fake_mode) + stack.enter_context(python_dispatcher_mode) + stack.enter_context(PhiloxStateTracker()) + stack.enter_context( + torch._dynamo.utils._disable_saved_tensors_hooks_during_tracing() + ) + + from torch._library.fake_class_registry import FakeScriptObject, maybe_to_fake_obj + from torch._library.opaque_object import is_custom_class + + # Tracing may mutate the states the fake script object, + # so we need to duplicate the fake script objects so that subsequent tracing + # won't be affected. + def _dup_fake_script_obj(fake_flat_args: FakifiedFlatArgs) -> list[Any]: + return [ + maybe_to_fake_obj(detect_fake_mode(fake_flat_args), arg.real_obj) + if isinstance(arg, FakeScriptObject) or is_custom_class(type(arg)) + else arg + for arg in fake_flat_args + ] + + needs_autograd = any( + x.requires_grad for x in fake_flat_args if isinstance(x, Tensor) + ) + + with enable_python_dispatcher(): + # Patch set_rng_state as set_rng_state with fake tensors is + # nonsensical. This does not affect the collection of metadata. + with patch("torch.cuda.set_rng_state", lambda *args: None): + mod = root_module_when_exporting_non_strict(flat_fn) + if mod is not None: + ctx = _detect_attribute_assignment(mod) + else: + ctx = nullcontext() + + if torch._functorch.config.fake_tensor_propagate_real_tensors: + # Running dynamo_timed causes fake tensor issues when + # propagate real tensor is switched on. + dynamo_timed_ctx = nullcontext() + else: + dynamo_timed_ctx = dynamo_timed( + "aot_collect_metadata", log_pt2_compile_event=True + ) + + with ( + dynamo_timed_ctx, + ctx, + torch._dynamo.eval_frame._use_eager_on_nested_compile(), + ): + fw_metadata = run_functionalized_fw_and_collect_metadata( + flat_fn, + flat_args_descs=flat_args_descs, + static_input_indices=aot_config.static_input_indices, + keep_input_mutations=aot_config.keep_inference_input_mutations, + pre_dispatch=aot_config.pre_dispatch, + )(*_dup_fake_script_obj(fake_flat_args)) + + req_subclass_dispatch = requires_subclass_dispatch( + fake_flat_args, fw_metadata + ) + CompileEventLogger.try_add_pt2_compile( + "backend_compile", requires_subclass_dispatch=req_subclass_dispatch + ) + + output_and_mutation_safe = not any( + x.requires_grad + # view-type operations preserve requires_grad even in no_grad. + # Do not count aliases of inputs with requires_grad as reason to make a training graph, + # as AOTAutograd will perform view-replay to regenerate the view outputs at runtime, + # setting their grad_fn properly. + and not ( + x.output_type in (OutputType.alias_of_input, OutputType.is_input) + and x.base_idx is not None + and fw_metadata.input_info[x.base_idx].requires_grad + ) + for x in fw_metadata.output_info + ) and not any( + x.requires_grad + and x.mutates_data + and not x.mutations_under_no_grad_or_inference_mode + and not x.mutations_hidden_from_autograd + for x in fw_metadata.input_info + ) + + if needs_autograd and output_and_mutation_safe: + # We realized that none of the outputs require grad, + # and none of the inputs that require grad are mutated. + # so we actually have an inference graph. + needs_autograd = False + + if fw_metadata.num_intermediate_bases > 0: + if req_subclass_dispatch: + raise AssertionError(f"""\ +torch.compile is currently being used with tensor subclass inputs. +We are attempting to a compile a graph with two graph outputs +that alias one another, specifically output indices: + + {[i for i, x in enumerate(fw_metadata.output_info) if x.output_type == OutputType.alias_of_intermediate]} + +ANY output aliasing (even for regular tensors) is currently unsupported if +there are any subclass outputs. If you run into this, please file a github +issue""") + + if aot_config.is_export: + # aot_export: ban input metadata mutations for now to keep shared code paths simpler. + # Keeping .resize_() in the graph will require some work + # Allowing it but keeping the graph functional will require some calling convention changes. + if len([x for x in fw_metadata.input_info if x.mutates_metadata]) != 0: + raise RuntimeError( + f"""\ +Found an input that received a metadata mutation, through e.g. a call to `.resize_()` or `.transpose_()`. +This is currently banned in the aot_export workflow. If you need this functionality, please file a github issue. + +fw_metadata={str(fw_metadata)}""" + ) + # In export, banning data mutations on inputs that require grad for now. + # This should be rare, and is tricky to get right. When we trace the backward, + # we currently trace with autograd.grad instead of .backward(), which makes it difficult + # to ensure that we run autograd all the way through the input **before** it saw the mutation. + if ( + len( + [ + x + for x in fw_metadata.input_info + if x.requires_grad and x.mutates_data + ] + ) + != 0 + and aot_config.export_trace_joint + ): + raise RuntimeError( + f"""\ +Found a graph input that requires gradients, and received a mutation. +This is currently banned in the aot_export workflow. If you need this functionality, please file a github issue. + +fw_metadata={str(fw_metadata)}""" + ) + if req_subclass_dispatch: + raise RuntimeError( + """\ +aot_export is not currently supported with traceable tensor subclass. +If you need this feature, please comment on """ + ) + + # Need to decide on a strategy for functionalized RNG: toggling via global config seems bad, + # and turning it on will require a non-trivial calling convention change for any export runtime. + if config.functionalize_rng_ops: + raise RuntimeError( + """\ +Functionalized RNG is not currently supported in the aot_export workflow. Please file a github issue, +or otherwise set torch._functorch.config.functionalize_rng_ops = False.""" + ) + + return AOTState( + needs_autograd=needs_autograd, + flat_args=_dup_fake_script_obj(fake_flat_args), + flat_args_descs=flat_args_descs, + fw_metadata=fw_metadata, + # Packaging this just for later use + aot_config=aot_config, + stack=stack, + fake_mode=fake_mode, + ) + + +def aot_function( + fn: Callable[_P, _R], + fw_compiler: AOTDispatchCompiler, + bw_compiler: AOTDispatchCompiler | None = None, + partition_fn: Callable[..., Any] = default_partition, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, + num_params_buffers: int = 0, + keep_inference_input_mutations: bool = False, + inference_compiler: AOTDispatchCompiler | None = None, + *, + # Whether or not to trace with dynamic shapes + dynamic: bool = False, + enable_log: bool = True, + disable_functionalization: bool = False, + _disable_torch_fn_metadata_mode: bool = False, +) -> Callable[_P, Any]: + """ + Traces the forward and backward graph of :attr:`fn` using torch dispatch + mechanism, and then compiles the generated forward and backward graphs + through :attr:`fw_compiler` and :attr:`bw_compiler`. + + :func:`aot_function` traces the forward and backward graph ahead of time, + and generates a joint forward and backward graph. :attr:`partition_fn` is + then used to separate out forward and backward graphs. The partitioner + function can be used to perform optimizations such as recomputation. One can + set `decompositions` dictionary to decompose the operators into a sequence + of core or simpler operators supported by the backend compilers. + + .. warning:: + This API is experimental and likely to change. + + Args: + fn (Callable): A Python function that takes one or more arguments. Must + return one or more Tensors. + fw_compiler (Callable): A Python function that accepts an Fx graph with + Aten ops and input args, and returns a Callable that semantically is + equivalent to the input Fx graph. + bw_compiler (Optional[Callable]): A Python function that accepts an + Fx graph with Aten ops and input args, and returns a Callable that + semantically is equivalent to the input Fx graph. Default: None + (when None, it defaults to the :attr:`fw_compiler`) + partition_fn (Callable): A Python function that takes a joint forward + and backward graph, and partitions it into separate forward and + backward graphs. + decompositions (Dict): A dictionary to define the decomposition of + larger Aten ops into simpler or core Aten ops. + inference_compiler (Optional[Callable]): A Python function that accepts an + Fx graph with Aten ops and input args, and returns a Callable that + semantically is equivalent to the input Fx graph. inference_compiler is invoked + if no autograd is needed. Default: None + (when None, it defaults to the :attr:`fw_compiler`) + Returns: + Returns a ``Callable`` that retains the eager behavior of the original + :attr:`fn`, but with forward and backward graph compiled via + :attr:`fw_compile` and :attr:`bw_compile`. + + A simple example usage of :func:`aot_function` is as follows. This example + will print the forward and backward graphs of the function ``fn`` + + >>> fn = lambda x: x.sin().cos() + >>> def print_compile_fn(fx_module, args): + >>> print(fx_module) + >>> return fx_module + >>> aot_fn = aot_function(fn, print_compile_fn) + >>> x = torch.randn(4, 5, requires_grad=True) + >>> aot_fn(x) + """ + + aot_config = AOTConfig( + fw_compiler=None, + bw_compiler=None, + inference_compiler=None, + partition_fn=None, + decompositions=decompositions, + num_params_buffers=num_params_buffers, + aot_id=next(AOT_COUNTER), + keep_inference_input_mutations=keep_inference_input_mutations, + dynamic_shapes=dynamic, + aot_autograd_arg_pos_to_source=None, + is_export=False, + no_tangents=False, + enable_log=enable_log, + disable_functionalization=disable_functionalization, + _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode, + ) + cached_res = None + + @wraps(fn) + def returned_function(*args: _P.args, **kwargs: _P.kwargs) -> Any: + nonlocal cached_res + # Now flatten the tensor args + flat_args = pytree.arg_tree_leaves(*args, **kwargs) + + # Compile the function and save it in the cache + if cached_res is None: + flat_fn, out_spec = create_tree_flattened_fn(fn, args, kwargs) + (fake_mode, shape_env) = construct_fake_mode(flat_args, aot_config) + fake_flat_args: FakifiedFlatArgs + fake_flat_args, act_input_paths = process_inputs( + flat_args, aot_config, fake_mode, shape_env + ) + # TODO: We actually could use the pytree path to make better descs. + # Also, the descs here are bad if you do aot_module. + fake_flat_args_descs: list[AOTInput] = [ + PlainAOTInput(i) for i in range(len(fake_flat_args)) + ] + with contextlib.ExitStack() as stack: + aot_state = create_aot_state( + stack, + flat_fn, + fake_flat_args, + fake_flat_args_descs, + aot_config, + fake_mode, + shape_env, + ) + aot_state.fw_metadata.act_input_paths = act_input_paths + aot_graph_capture = aot_stage1_graph_capture(aot_state, flat_fn) + compiled_fn, _ = aot_stage2_compile( + aot_state, + aot_graph_capture, + partition_fn, + fw_compiler, + bw_compiler, + inference_compiler, + ) + cached_res = (compiled_fn, out_spec) + + cached_fn, out_spec = cached_res + out = cached_fn(flat_args) + return out_spec.unflatten(out) + + return returned_function + + +def aot_module(mod: nn.Module, *args: Any, **kwargs: Any) -> nn.Module: + """ + Traces the forward and backward graph of :attr:`mod` using torch dispatch + tracing mechanism. It is wrapper function, that underneath uses + :func:`aot_function` to perform tracing and compilation. + + :func:`aot_module` lifts the parameters and buffers of ``nn.Module`` as inputs + to a new callable which is then compiled through :func:`aot_function`. + + .. warning:: + This API is experimental and likely to change. + + Args: + mod (Callable): A ``nn.Module`` module. + args : args to be passed to :func:`aot_function` + kwargs : kwargs to be passed to :func:`aot_function` + + Returns: + Returns a ``nn.Module`` that retains the eager behavior of the original + :attr:`mod`, but with forward and backward graph compiled. + + """ + # See Note: [Fake Modules and AOTAutograd] + torch._dynamo.utils.assert_no_fake_params_or_buffers(mod) + + def functional_call( + named_params: dict[str, torch.nn.Parameter], + named_buffers: dict[str, torch.Tensor], + *args: Any, + **kwargs: Any, + ) -> Any: + params_and_buffers = {**named_params, **named_buffers} + return torch.func.functional_call(mod, params_and_buffers, args, kwargs) + + named_params = dict(mod.named_parameters(remove_duplicate=False)) + named_buffers = dict(mod.named_buffers(remove_duplicate=False)) + num_params_buffers = len(named_params) + len(named_buffers) + compiled_f = aot_function( + functional_call, + *args, + # pyrefly: ignore[bad-keyword-argument] + num_params_buffers=num_params_buffers, + **kwargs, + ) + + class AOTModule(nn.Module): + def __init__(self) -> None: + super().__init__() + self.orig_module = mod + + def forward(self, *args: Any, **kwargs: Any) -> Any: + return compiled_f( + named_params, + named_buffers, + *args, + **kwargs, + ) + + return AOTModule() + + +def autograd_cache_key( + graph, + example_inputs, + ignore_shape_env: bool, + decompositions, + compiler_config_extra: CompilerConfigExtra, + keep_inference_input_mutations: bool = False, + disable_functionalization: bool = False, +): + ( + _params_buffers_flat, + _params_spec, + _buffers_spec, + full_args, + _full_args_descs, + aot_config, + ) = prepare_aot_config( + graph, + example_inputs, + decompositions, + keep_inference_input_mutations, + ignore_shape_env, + force_non_lazy_backward_lowering=config.force_non_lazy_backward_lowering, + disable_functionalization=disable_functionalization, + ) + + fake_mode, shape_env = construct_fake_mode(full_args, aot_config) + fake_flat_args, act_input_paths = process_inputs( + full_args, aot_config, fake_mode, shape_env, ignore_shape_env + ) + + return autograd_cache.autograd_cache_key( + graph, fake_flat_args, aot_config, compiler_config_extra, act_input_paths + ) + + +def prepare_aot_config( + mod: nn.Module, + args: Iterable[Any], + decompositions: dict[OpOverload, Callable[..., Any]] | None, + keep_inference_input_mutations: bool, + ignore_shape_env: bool, + *, + force_non_lazy_backward_lowering: bool = False, + disable_functionalization: bool = False, + _disable_torch_fn_metadata_mode: bool = False, +) -> tuple[ + list[torch.nn.Parameter | Tensor], + list[str], + list[str], + list[Any], + list[Any], + AOTConfig, +]: + # TODO: There's something a bit suspicious here; typically simplified + # module shouldn't actually have any parameters... + params = dict(mod.named_parameters(remove_duplicate=False)) + buffers = dict(dict(mod.named_buffers(remove_duplicate=False))) + + params_flat, params_spec = list(params.values()), list(params.keys()) + params_len = len(params_flat) + + buffers_flat, buffers_spec = list(buffers.values()), list(buffers.keys()) + buffers_len = len(buffers_flat) + + params_buffers = {**params, **buffers} + params_buffers_flat = params_flat + buffers_flat + + full_args = [*params_flat, *buffers_flat, *args] + + # OK, set up the descs + + full_args_descs: list[DifferentiableAOTInput] = [] + full_args_descs.extend(ParamAOTInput(fqn) for fqn in params_spec) + full_args_descs.extend(BufferAOTInput(fqn) for fqn in buffers_spec) + + # TODO: These tracing_context fields should become unnecessary once we + # always maintain sources on all arguments + if tracing_context := torch._guards.TracingContext.try_get(): + # NB: TracingContext misnames this, the "params" here also contains + # buffers + tracing_context.params_flat = params_buffers_flat + ( + tracing_context.params_flat_unwrap_subclasses, + tracing_context.params_unwrapped_to_flat_index, + ) = unwrap_tensor_subclasses_with_indices_to_original(params_buffers_flat) + + # TODO: Might be nice to hold on to the Dynamo source here in full_args_descs! + ( + aot_autograd_arg_pos_to_source, + static_input_indices, + ) = _try_get_metadata_from_dynamo( + mod, params_buffers.keys(), len(full_args), full_args_descs + ) + + dynamic_shapes = False + for x in full_args: + fake_mode = maybe_get_fake_mode(x) + if fake_mode is not None: + dynamic_shapes = fake_mode.shape_env is not None + break + + aot_config = AOTConfig( + fw_compiler=None, + bw_compiler=None, + inference_compiler=None, + partition_fn=None, + decompositions=decompositions, + num_params_buffers=params_len + buffers_len, + aot_id=next(AOT_COUNTER), + keep_inference_input_mutations=keep_inference_input_mutations, + dynamic_shapes=dynamic_shapes, + # pyrefly: ignore[bad-argument-type] + aot_autograd_arg_pos_to_source=aot_autograd_arg_pos_to_source, + static_input_indices=static_input_indices, + is_export=False, + no_tangents=False, + cache_info=None, + ignore_shape_env=ignore_shape_env, + precompile_backend_id=getattr(mod, "_backend_id", None), + force_non_lazy_backward_lowering=force_non_lazy_backward_lowering, + disable_functionalization=disable_functionalization, + _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode, + ) + + return ( + params_buffers_flat, + params_spec, + buffers_spec, + full_args, + full_args_descs, + aot_config, + ) + + +def prepare_aot_module_simplified( + mod: nn.Module, + args: Iterable[Any], + kwargs: dict[str, Any] | None, + decompositions: dict[OpOverload, Callable[..., Any]] | None, + keep_inference_input_mutations: bool, + ignore_shape_env: bool, + flatten: bool, + *, + force_non_lazy_backward_lowering: bool = False, + disable_functionalization: bool = False, + _record_nn_module_stack: bool = False, + _disable_torch_fn_metadata_mode: bool = False, +) -> tuple[ + Any, + list[torch.nn.Parameter | Tensor], + list[str], + list[str], + FakifiedFlatArgs, + list[Any], + AOTConfig, + FakeTensorMode, + ShapeEnv | None, + pytree.TreeSpec | None, + PytreeThunk | None, + list[ActInputPath], +]: + if not flatten: + if kwargs is not None: + raise AssertionError("kwargs must be None when flatten=False") + elif kwargs is None: + kwargs = {} + + ( + params_buffers_flat, + params_spec, + buffers_spec, + full_args, + full_args_descs, + aot_config, + ) = prepare_aot_config( + mod, + args, + decompositions, + keep_inference_input_mutations, + ignore_shape_env, + force_non_lazy_backward_lowering=force_non_lazy_backward_lowering, + disable_functionalization=disable_functionalization, + _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode, + ) + + params_buffers_spec = params_spec + buffers_spec + + # NB: This doesn't change the in/out convention, except adding the + # parameters as explicit arguments + functional_call = create_functional_call( + mod, + params_buffers_spec, + aot_config.num_params_buffers, + strict_out_tuple=not flatten, + # We need this for export to run ModuleStackTracer + # instead of PythonKeyTracer + store_orig_mod=_record_nn_module_stack, + ) + + in_spec, out_spec = None, None + if flatten: + functional_call, out_spec = create_tree_flattened_fn( + functional_call, full_args, kwargs + ) + full_args, in_spec = pytree.tree_flatten((full_args, kwargs)) + + # TODO: it would be better to put pytree information in here + full_args_descs.extend( + PlainAOTInput(i) for i in range(len(full_args) - len(full_args_descs)) + ) + + fake_mode, shape_env = construct_fake_mode(full_args, aot_config) + # NB: full_args_descs not needed here, fake_flat_args is 1:1 with full_args + fake_flat_args, act_input_paths = process_inputs( + full_args, aot_config, fake_mode, shape_env, ignore_shape_env + ) + + return ( + functional_call, + params_buffers_flat, + params_spec, + buffers_spec, + fake_flat_args, + full_args_descs, + aot_config, + fake_mode, + shape_env, + in_spec, + out_spec, + act_input_paths, + ) + + +def aot_module_simplified( + mod: torch.fx.GraphModule | torch._dynamo.utils.GmWrapper, + args: Sequence[Any], + fw_compiler: AOTDispatchCompiler, + bw_compiler: AOTDispatchCompiler | None = None, + partition_fn: Callable[..., Any] = default_partition, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, + keep_inference_input_mutations: bool = False, + inference_compiler: AOTDispatchCompiler | None = None, + # TODO: This doesn't seem to be used in any nontrivial way, check if it's + # actually needed + compiler_config_extra: CompilerConfigExtra | None = None, + ignore_shape_env: bool = False, + disable_functionalization: bool = False, + # Optional callback to run passes on the module at the start of AOT autograd. + pre_grad_passes: Callable[ + [torch.fx.GraphModule, Sequence[InputType]], torch.fx.GraphModule + ] + | None = None, + compile_region_name: str | None = None, +) -> Callable[..., Any]: + """ + This is the simplified or low overhead version of aot_module. For frontends + like TorchDynamo, the input functions/modules to AOT are static and have + unpacked inputs/outputs. This gives us an opportunity to remove the + (1) pytree overhead to parse inputs/outputs, + (2) AOT Autograd cache, + (3) Reading of params/buffers in every forward call + + :func:`aot_module_simplified` removes these overheads. + """ + + pre_grad_pass_timing: Literal["early", "late"] = resolve_pre_grad_pass_timing() + + if ( + pre_grad_pass_timing == "early" + and pre_grad_passes + and isinstance(mod, torch.fx.GraphModule) + ): + mod = pre_grad_passes(mod, args) + + with contextlib.ExitStack() as stack: + ( + functional_call, + params_buffers_flat, + _params_spec, + _buffers_spec, + fake_flat_args, + full_args_descs, + aot_config, + fake_mode, + shape_env, + _in_spec, + _out_spec, + act_input_paths, + ) = prepare_aot_module_simplified( + mod, + args, + None, + decompositions, + keep_inference_input_mutations, + ignore_shape_env, + flatten=False, + force_non_lazy_backward_lowering=config.force_non_lazy_backward_lowering, + disable_functionalization=disable_functionalization, + ) + + compiled_fn = None + + if ( + isinstance(fw_compiler, SerializableAOTDispatchCompiler) + or torch._functorch.config.force_autograd_cache + ): + local = should_use_local_autograd_cache() + remote = should_use_remote_autograd_cache() + if local or remote: + set_feature_use("aot_autograd_remote_cache", remote) + compiled_fn, aot_config = AOTAutogradCache.try_load( + mod, + fake_flat_args, + aot_config, + compiler_config_extra, + local, + remote, + act_input_paths, + compile_region_name=compile_region_name, + ) + + if compiled_fn is None: + if ( + pre_grad_pass_timing == "late" + and pre_grad_passes + and isinstance(mod, torch.fx.GraphModule) + ): + mod = pre_grad_passes(mod, args) + + stack.enter_context(compiled_autograd._disable()) + aot_state = create_aot_state( + stack, + functional_call, + fake_flat_args, + full_args_descs, + aot_config, + fake_mode, + shape_env, + ) + aot_state.fw_metadata.act_input_paths = act_input_paths + aot_graph_capture = aot_stage1_graph_capture(aot_state, functional_call) + compiled_fn, _ = aot_stage2_compile( + aot_state, + aot_graph_capture, + partition_fn, + fw_compiler, + bw_compiler, + inference_compiler, + ) + if compiled_fn is None: + raise AssertionError("compiled_fn must not be None") + if isinstance(mod, torch._dynamo.utils.GmWrapper): + # This function is called by the flatten_graph_inputs wrapper, which boxes + # the inputs so that they can be freed before the end of this scope. + # For overhead reasons, this is not the default wrapper, see comment: + # https://github.com/pytorch/pytorch/pull/122535/files#r1560096481 + @simple_wraps(compiled_fn) + def forward(runtime_args: list[Any]) -> Any: + flat_args = [] + flat_args.extend(params_buffers_flat) + flat_args.extend(runtime_args) + runtime_args.clear() + if compiled_fn is None: + raise AssertionError("compiled_fn must not be None") + return compiled_fn(flat_args) + + else: + # TODO: There is something deeply wrong here; compiled_fn running with + # the boxed calling convention, but aot_module_simplified somehow + # historically returned a function that was not the boxed calling + # convention. This should get fixed... + # NB: GraphModule/nn.Module rely on the non-boxed calling convention here + @simple_wraps(compiled_fn) + def forward(*runtime_args: tuple[Any]) -> Any: + full_args = [] + full_args.extend(params_buffers_flat) + # pyrefly: ignore[bad-argument-type] + full_args.extend(runtime_args) + if compiled_fn is None: + raise AssertionError("compiled_fn must not be None") + return compiled_fn(full_args) + + # Just for convenience + forward.zero_grad = mod.zero_grad # type: ignore[attr-defined] + forward.named_parameters = mod.named_parameters # type: ignore[attr-defined] + forward.named_buffers = mod.named_buffers # type: ignore[attr-defined] + + # Add a serialize function + def grab_serialize_fn(fn: Any) -> Callable[..., Any] | None: + if isinstance(fn, SerializableCompiledFunction): + return fn.serialize_fn + elif hasattr(fn, "__wrapped__"): + return grab_serialize_fn(fn.__wrapped__) + else: + return None + + forward.serialize = grab_serialize_fn(forward) # type: ignore[attr-defined] + return forward + + +def boxed_nop_preserve_node_meta( + gm: torch.fx.GraphModule, example_inputs: Sequence[InputType] +) -> Any: + def run(args: list[Any]) -> OutputCode: + with torch.fx.traceback.preserve_node_meta(): + return torch.fx.Interpreter(gm).boxed_run(args) + + run._boxed_call = True # type: ignore[attr-defined] + return run + + +def aot_export_joint_with_descriptors( + stack: contextlib.ExitStack, + mod: nn.Module, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, + keep_inference_input_mutations: bool = False, + ignore_shape_env: bool = False, + disable_functionalization: bool = False, + _record_nn_module_stack: bool = False, + _disable_torch_fn_metadata_mode: bool = False, +) -> JointWithDescriptors: + """ + This API captures the joint graph for an nn.Module. However, unlike + aot_export_joint_simple or aot_export_module(trace_joint=True), the + calling convention of the produced joint graph follows no fixed positional + schema; for example, you cannot rely on the second argument of the traced + joint graph to correspond to the second argument of the module you traced. + However, the inputs and outputs of the traced graph are schematized + with **descriptors**, annotated on meta['desc'] on the placeholder and + return FX nodes, which you can use to determine the meaning of arguments. + + The major benefit of using this export rather than aot_export_joint_simple + is that we have feature parity with all situations that torch.compile + supports (via aot_module_simplified), including handling for more + complicated cases such as multiple differentiable outputs, input mutations + that must be handled outside of the graph, tensor subclasses, etc. + + What can you do with one of these joint graphs with descriptors? The + motivating use case (autoparallel) involves taking the joint graph, doing + optimizations on it, and then turning it back into a callable so it can be + torch.compile'd at a later point in time. This cannot be done as a + traditional torch.compile joint graph pass for two reasons: + + 1. The sharding of parameters must be decided before parameter + initialization / checkpoint load, far before torch.compile would + ordinarily run. + + 2. We need to change the meaning of parameters (e.g., we might replace + a replicated parameter with a sharded version of it, changing its + input size). torch.compile is ordinarily semantics preserving, and + not allowed to change the meaning of inputs. + + Some descriptors can be quite exotic, so we recommend thinking carefully + if there is a safe fallback you can apply to descriptors you don't understand. + For example, you should have some way to handle not finding a particular + input exactly as is in the final FX graph inputs. + + Note: When using this API, you must create and enter an ExitStack context + manager, which will be passed into this function. This context manager + must remain active if you call the compile function to finish compilation. + (TODO: We may relax this requirement by having AOTAutograd keep track of + how to reconstruct all the context managers at a later point in time.) + + NB: You're not obligated to do a /full/ compile in stage2; instead you can + leave the forward/backward compilers unspecified in which case the + partitioned FX graphs will directly run. The overall autograd Function + can be allowed in graph so you can reprocess it in the context of a + (potentially larger) compiled region later. + + NB: These APIs do NOT hit cache, as we only ever cache the final compile results, + not the intermediate export result. + + NB: If the passed nn.Module has parameters and buffers on it, we will + generate extra implicit parameter/buffer arguments and assign ParamAOTInput + and BufferAOTInput descriptors to them. However, if you generate the input + nn.Module from a mechanism like Dynamo, you will NOT get these descriptors + (because Dynamo will already have taken care of lifting the parameters/buffers + into arguments!) In that case, it would be necessary to analyze the Sources + of the inputs to determine if inputs are parameters and their FQNs. + """ + + ( + functional_call, + _params_buffers_flat, + params_spec, + buffers_spec, + fake_flat_args, + full_args_descs, + aot_config, + fake_mode, + shape_env, + in_spec, + out_spec, + act_input_paths, + ) = prepare_aot_module_simplified( + mod, + args, + kwargs, + # In contrast, decompositions are needed at this stage. + decompositions, + keep_inference_input_mutations, + ignore_shape_env, + flatten=True, + # Without this, we will attempt to "compile" the backward lazily + # at runtime, but this is pointless because it's just boxed_nop, + # it's trivial. But this will get Inductor confused about scoping + # Metric(s) {'is_forward'} have already been set in the current + # context. + force_non_lazy_backward_lowering=True, + disable_functionalization=disable_functionalization, + _record_nn_module_stack=_record_nn_module_stack, + _disable_torch_fn_metadata_mode=_disable_torch_fn_metadata_mode, + ) + + # TODO: Maybe this should be in create_aot_state? Not sure, that would + # increase its scope + stack.enter_context(compiled_autograd._disable()) + + aot_state = create_aot_state( + stack, + functional_call, + fake_flat_args, + full_args_descs, + aot_config, + fake_mode, + shape_env, + ) + aot_state.fw_metadata.act_input_paths = act_input_paths + + # NB: no cache lookup! + aot_graph_capture = aot_stage1_graph_capture(aot_state, functional_call) + + if out_spec is None or out_spec.spec is None: + raise AssertionError("out_spec and out_spec.spec must not be None") + if in_spec is None: + raise AssertionError("in_spec must not be None") + return JointWithDescriptors( + _aot_state=aot_state, + _aot_graph_capture=aot_graph_capture, + params_spec=params_spec, + buffers_spec=buffers_spec, + in_spec=in_spec, + out_spec=out_spec.spec, + ) + + +def aot_compile_joint_with_descriptors( + jd: JointWithDescriptors, + *, + partition_fn: Callable[..., Any] = default_partition, + fw_compiler: AOTDispatchCompiler = boxed_nop_preserve_node_meta, + bw_compiler: AOTDispatchCompiler | None = boxed_nop_preserve_node_meta, + serializable: bool = False, +) -> Callable[..., Any]: + """ + Companion function for aot_export_joint_with_descriptors which compiles the joint + graph into a callable function that follows a standard calling convention. + params_flat all are arguments. + + Note: We do NOT instantiate the module; this gives you the flexibility to subclass it and + customize its behavior without having to worry about FQN rebinding. + + Args: + serializable: If True, configures the compilation to produce a serializable + callable by leveraging AOTAutogradCache machinery. This sets up the + necessary cache_info and patches config options required for serialization. + When True, this function will always return a BundledAOTAutogradSerializableCallable. + """ + # TODO: Consider if we should allow_in_graph the result by default. + from torch._dynamo.aot_compile_types import ( + BundledAOTAutogradSerializableCallable, + SerializableCallable, + ) + from torch._functorch._aot_autograd.schemas import AOTAutogradCacheInfo + from torch._guards import detect_fake_mode + from torch._inductor.output_code import OutputCode + + fw_compiler = SerializableAOTDispatchCompiler(OutputCode, fw_compiler) + + cache_ctx = nullcontext() + if serializable: + jd._aot_state.aot_config = dataclasses.replace( + jd._aot_state.aot_config, + cache_info=AOTAutogradCacheInfo( + jd.cache_hash(), + time.time_ns(), + forward_symints=[], + ), + ) + cache_ctx = torch._functorch.config.patch( + { + "strict_autograd_cache": True, + "bundled_autograd_cache": True, + "force_non_lazy_backward_lowering": True, + "bypass_autograd_cache_key": True, + } + ) + + # Set up a TracingContext if one isn't already available. + # This is needed for compilers (like regional_inductor) that call + # standalone_compile with dynamic_shapes="from_tracing_context". + tracing_context = torch._guards.TracingContext.try_get() + if tracing_context is None: + fake_mode = detect_fake_mode(jd._aot_state.flat_args) + if fake_mode is not None: + tracing_context = torch._guards.TracingContext(fake_mode) + tracing_ctx = torch._guards.tracing(tracing_context) + else: + tracing_ctx = nullcontext() + else: + tracing_ctx = nullcontext() + + with cache_ctx, tracing_ctx: + compiled_fn, _ = aot_stage2_compile( + jd._aot_state, + jd._aot_graph_capture, + partition_fn, + fw_compiler, + bw_compiler, + ) + + if not isinstance(compiled_fn, SerializableCallable) and hasattr( + compiled_fn, "serialize" + ): + compiled_fn = BundledAOTAutogradSerializableCallable(compiled_fn) + + # Cribbed from torch/export/pt2_archive/_package.py + @simple_wraps(compiled_fn) + @torch._dynamo.nonstrict_trace # allow recursive compilation + def unflattened_compiled_fn(*args: Any, **kwargs: Any) -> Any: + flat_inputs = pytree.tree_flatten((args, reorder_kwargs(kwargs, jd.in_spec)))[0] + # TODO: do I need to filter? I hope not! + flat_outputs = compiled_fn(flat_inputs) + return pytree.tree_unflatten(flat_outputs, jd.out_spec) + + return unflattened_compiled_fn + + +def aot_export_module( + mod: nn.Module, + args: Iterable[Any], + *, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, + # If true, we'll return a joint forward-backward graph, + # As well as metadata on the loss + gradients in the backward. + trace_joint: bool, + # If trace_joint is True, we expect your module to return a scalar loss. + # Your module can return multiple outputs, so you must specify which output the loss is. + output_loss_index: int | None = None, + pre_dispatch: bool = False, + # If None, will be inferred from inputs and mod.graph.nodes if mod is a graph module, but the inferred result might be wrong. + dynamic_shapes: bool | None = None, + kwargs: dict[str, Any] | None = None, +) -> tuple[Callable[..., Any] | torch.fx.GraphModule, GraphSignature]: + """ + This function takes in a module, and returns: + (1) an FX graph that can be exported + (2) some metadata about the graph + + If `trace_joint=True` we will return a joint graph of the forward + backward. + + The traced FX graph will have the following properties compared to the original module: + (1) Inputs and outputs to the module will be pytree-flattened + (2) Parameters and buffers on the module will be lifted into graph inputs, + graph_inputs = (*parameters, *buffers, *user_inputs) + (3) The graph will be fully functionalized + (4) Any input mutations will be converted into additional outputs in the graph, + meaning whoever calls this graph is responsible for applying the mutations + back to the original inputs. + (5) If is_joint is provided the graph will return parameter gradients in addition to user outputs. + The graph output will look like: + graph_outputs = (*updated_inputs, *user_outputs, *param_gradients) + + There are also several restrictions on what modules can use this API. In particular: + (1) If trace_joint is specified, we expect the loss function to be **fused** + into the module forward. One of the outputs to the forward must be a scalar loss, + which is specified with `output_loss_index`. + All other outputs to the forward are presumed to not require gradients. + (2) This API cannot capture optimizers (although in theory we could build an API for this). + (3) Metadata mutations on params/buffers/inputs are banned. + (4) Data mutations on anything that requires gradients are banned (parameters) + (5) If an input is mutated, it is not allowed to alias any other inputs. + (6) Parameters must not be duplicated. + """ + if pre_dispatch and trace_joint: + raise RuntimeError("pre_dispatch is not supported when trace_joint is True.") + named_parameters = dict(mod.named_parameters(remove_duplicate=False)) + named_buffers = dict(mod.named_buffers(remove_duplicate=False)) + + params_and_buffers = { + **dict(named_parameters), + **dict(named_buffers), + } + params_and_buffers_flat, params_spec = pytree.tree_flatten(params_and_buffers) + params_and_buffers_flat = tuple(params_and_buffers_flat) + params_len = len(params_and_buffers_flat) + + kwargs = kwargs or {} + + functional_call = create_functional_call( + mod, params_spec, params_len, store_orig_mod=True + ) + + num_fw_outs = None + + if trace_joint: + # This helper effectively just adds some extra asserts about what the backward will look like: + # Outputs must include a scalar loss, that we compute gradients w.r.t. + # We don't compute gradients w.r.t. anything else: so just in case we detach() + # and other output tensors. + def fn_to_trace(*args: Any) -> Any: + nonlocal num_fw_outs + out = functional_call(*args) + if output_loss_index is None: + raise RuntimeError( + """\ +If trace_joint=Trueit is required that one of your forward outputs must be a scalar loss. +You must specify the which (index) output is the loss with output_loss_index.""" + ) + if isinstance(out, (torch.Tensor)): + out = (out,) + if not isinstance(out, (tuple, list)): + raise RuntimeError( + f"Expected forward output to be either a tensor or a list/tuple of tensors. found {type(out)}" + ) + + for i, o in enumerate(out): + # We only want to create a backward graph w.r.t. the loss that the user passed in. + # This implies that every other output should not require gradients. + # Instead of making this an error (and forcing the user to detach all other outputs + # of their forward), + # we'll automatically detach them here. + if o.requires_grad and i != output_loss_index: + raise RuntimeError( + f"""\ +Found an output of the forward that requires gradients, that was not the scalar loss. +We require all outputs to the forward that are not the scalar loss to not require gradient, +because we will only compute a backward graph against the scalar loss. +You can fix this by calling .detach() on each of your forward outputs that is not the loss. +You specified that output index {output_loss_index} is the loss, but we found that +the output at index {i} requires gradients.""" + ) + out_loss = out[output_loss_index] + num_fw_outs = len(out) + if not out_loss.requires_grad: + raise RuntimeError( + f"""\ +The output at index {output_loss_index} was marked as the loss, but it does not require gradients""" + ) + if out_loss.numel() != 1: + raise RuntimeError( + f"""\ +We require the output marked as the loss (at index {output_loss_index}) to be a scalar, but it has shape {out_loss.shape}""" + ) + return out + + ctx = nullcontext + else: + # Run under no_grad, so our tracing machinery only traces an inference graph. + # However if pre_dispatch=True, we want to correctly trace set_grad_enabled calls for training. + ctx = nullcontext if pre_dispatch else torch.no_grad + fn_to_trace = functional_call + + full_args = [] + # First, the params + # NB: It is REQUIRED that parameters come first, Inductor infers "fixed" + # parameters by looking at the difference in parameter count outside + # and inside AOTAutograd, and assumes the prefix of arguments are fixed + # arguments + full_args.extend(params_and_buffers_flat) + # Next, the input args + full_args.extend(args) + + with ctx(): + fx_g, metadata, in_spec, out_spec = _aot_export_function( + fn_to_trace, + tuple(full_args), + decompositions=decompositions, + num_params_buffers=params_len, + no_tangents=True, + pre_dispatch=pre_dispatch, + dynamic_shapes=dynamic_shapes, + trace_joint=trace_joint, + kwargs=kwargs, + ) + + # TODO: subsume this path with the aot_stage2_graph_capture path + if trace_joint: + + @wraps(functional_call) + def flattened_joint(*args: Any) -> Any: + # The idea here is that the joint graph that AOTAutograd creates has some strict properties: + # (1) It accepts two arguments (primals, tangents), and pytree_flattens them + # (2) It returns a tuple of (fw_outs, gradients) + # This is a very useful convention for anyone who wants to partition the joint graph + # into a separate forward and backward graph. + # However, + # (1) for people exporting a single joint graph, it would be preferable not to have + # any pytrees in the graph. + # (2) We are guaranteed in the aot_export_module case that the forward outputs a loss, + # and there are therefore no tangents that are needed to run the joint graph. + # (3) AOTAutograd creates a grad_input for every input in the forward, + # including None's for inputs that are not grad-requiring tensors. + # we don't want these in our export graph. + # and there are therefore no tangents that are needed to run the joint graph. + # This function "fixes" both of the above by removing any tangent inputs, + # and removing pytrees from the original FX graph. + fake_tangents = [ + None + for _ in range( + metadata.num_outputs + metadata.num_mutated_inp_runtime_indices + ) + ] + fw_outs, gradients = fx_g(args, fake_tangents) + if len(gradients) != len(args): + raise AssertionError( + f"len(gradients)={len(gradients)} != len(args)={len(args)}" + ) + output_gradients = [] + for a, grad in zip(args, gradients): + if isinstance(a, torch.Tensor) and a.requires_grad: + if grad is None: + raise AssertionError("""\ +Found a parameter that did not receive a gradient. +"This is most likely a bug, but if this needs to be supported please comment on this Github issue: +https://github.com/pytorch/pytorch/issues/101192 +""") + output_gradients.append(grad) + else: + if grad is not None: + raise AssertionError( + f"expected grad to be None for non-tensor or non-requires_grad input, got {type(grad)}" + ) + return *fw_outs, *output_gradients + + fx_g = make_fx(flattened_joint, record_module_stack=True)(*full_args) + + user_args_flat = pytree.arg_tree_leaves(*args, **kwargs) + if out_spec is None: + raise AssertionError("out_spec must not be None") + return fx_g, create_graph_signature( + # type: ignore[bad-argument-type] + fx_g, + metadata, + in_spec, + out_spec, + user_args_flat=user_args_flat, + params_and_buffers_flat=list(params_and_buffers_flat), + param_names=list(named_parameters.keys()), + buffer_names=list(named_buffers.keys()), + trace_joint=trace_joint, + num_user_fw_outs=num_fw_outs, + loss_index=output_loss_index, + ) + + +def aot_export_joint_simple( + func: Callable[..., Any], + args: tuple[Any, ...], + *, + trace_joint: bool, + # It looks like the main consequence of this API is that for dynamic shapes, + # it will assume that params/buffers are static. + # With the new inferred dynamic shapes API, maybe this doesn't matter? + num_params_buffers: int = 0, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, +) -> Callable[..., Any]: + """ + A simplified version of export. Used by higher order operators. + + This function makes a high-level "no calling convention changes" guarantee: + - If no inputs require grad (so we export an inference graph), + there are *no* calling convention change between the exported graph, and "func". + - If at least one input requires grad (so we trace out and export a joint fw-bw graph), + Then if you were partition the graph into a separate forward and backward graph, + The forward graph will have no calling convention changes compared to "func". + + The above also relies on some strong restrictions around which functions this API accepts: + (1) `args` cannot contain any pytrees (they must have been pytree_flattened already) + (2) `func` cannot mutate any inputs + (3) The outputs of `func` cannot alias any inputs. + + Note: this function is only lightly tested today. It will probably be tested more heavily by higher order ops. + """ + if trace_joint: + ctx = nullcontext + else: + # Run under no_grad, so our tracing machinery only traces an inference graph. + ctx = torch.no_grad + + with ctx(): + fx_g, metadata, in_spec, out_spec = _aot_export_function( + func, + args, + decompositions=decompositions, + trace_joint=trace_joint, + ) + in_spec, _kw_in_spec = in_spec.children() + # At this point, we can just directly return the (joint or inference graph) that we traced. + # First though: a bunch of assertions to make sure that our graph doesn't require + # any calling convention changes compared to the original function. + # These restrictions are *in addition to* the general restrictions on export. + + # No input mutations + if ( + len([x for x in metadata.input_info if x.mutates_data or x.mutates_metadata]) + != 0 + ): + raise RuntimeError( + f"aot_export_joint_simple does not support input mutations. {str(metadata)}" + ) + # No output aliasing + if ( + len([x for x in metadata.output_info if x.output_type != OutputType.non_alias]) + != 0 + ): + raise RuntimeError( + f"aot_export_joint_simple does not support outputs that alias inputs. {str(metadata)}" + ) + # No pytrees + if in_spec.is_leaf(): + raise RuntimeError( + f"aot_export_joint_simple requires inputs to be a single list/tuple. in_spec={str(in_spec)}" + ) + if not all(child.is_leaf() for child in in_spec.children()): + raise RuntimeError( + f"aot_export_joint_simple requires individual inputs not to be pytrees. in_spec={str(in_spec)}" + ) + + if out_spec is None: + raise AssertionError("out_spec must not be None") + if out_spec.is_leaf(): + raise RuntimeError( + f"aot_export_joint_simple requires outputs to be a single list/tuple. out_spec={str(out_spec)}" + ) + if not all(child.is_leaf() for child in out_spec.children()): + raise RuntimeError( + f"aot_export_joint_simple requires individual outputs not to be pytrees. out_spec={str(out_spec)}" + ) + # TODO: we might have to temporarily patch config.functionalize_rng + # so that it doesn't run when we're exporting a higher order op. + + if config.debug_assert: + # Smoke test that after partitioning, we can run the forward without any calling convention changes. + fw_module, _bw_module = default_partition( + # type: ignore[bad-argument-type] + fx_g, + args, + # type: ignore[unknown-name] + num_fwd_outputs=len(fw_metadata.output_infos), # noqa: F821 + ) + # Attempt to run the fw_module with the original user inputs + fake_mode = detect_fake_mode(args) + if fake_mode is None: + fake_mode = FakeTensorMode() + with fake_mode: + fw_module(*args) + return fx_g + + +# Private for now because we aren't providing a contract on what to return +# for joint graphs (we could when there's a clearer use case) +# In the future, we may need to add more export API's that provide their own strong guarantees. +# This is meant as a general helper function for handling various export-y use cases. +def _aot_export_function( + func: Callable[..., Any], + args: tuple[Any, ...], + *, + num_params_buffers: int = 0, + decompositions: dict[OpOverload, Callable[..., Any]] | None = None, + # If we're exporting a joint graph and we don't want any tangent inputs in the graph + # (because we are backpropping through a scalar 1 loss), + # we need to explicitly specify not to include tangents in the graph. + # It's not enough just to check that our tangent is a scalar, since we also + # need to know if it is a 1 (no need to make it a graph input), or something else + # (requiring it to be a graph input). + # We don't know this info at trace time though, so we need to make it an explicit config. + no_tangents: bool = False, + pre_dispatch: bool = False, + # If None, `dynamic_shapes` will be inferred from inputs, but the inferred result might be wrong. + dynamic_shapes: bool | None = None, + keep_input_mutations: bool = False, + # Under export, configures whether we are getting inference or training IR + trace_joint: bool = False, + kwargs: dict[str, Any] | None = None, +) -> tuple[ + Callable[..., Any], ViewAndMutationMeta, pytree.TreeSpec, pytree.TreeSpec | None +]: + kwargs = kwargs or {} + + flat_fn, out_spec = create_tree_flattened_fn(func, args, kwargs) + flat_args, in_spec = pytree.tree_flatten((args, kwargs)) + + fake_mode = None + if dynamic_shapes is None: + # Try to infer `dynamic_shapes from inputs and graph nodes + fake_mode = detect_fake_mode(flat_args) + if ( + fake_mode is None + and hasattr(func, "_orig_mod") + and isinstance(func._orig_mod, torch.fx.GraphModule) + ): + vals = [ + node.meta["val"] + for node in func._orig_mod.graph.nodes + if "val" in node.meta + ] + fake_mode = detect_fake_mode(vals) + dynamic_shapes = fake_mode is not None and fake_mode.shape_env is not None + + # The export use case doesn't care about several bits of AOTConfig + # (1) compilers (we just export the graph) + # (2) partitioners (export is only full graph, user can partition themselves) + aot_config = AOTConfig( # type: ignore[arg-type] + fw_compiler=None, + bw_compiler=None, + inference_compiler=None, + partition_fn=None, + decompositions=decompositions, + num_params_buffers=num_params_buffers, + aot_id=next(AOT_COUNTER), + keep_inference_input_mutations=keep_input_mutations, + dynamic_shapes=dynamic_shapes, + aot_autograd_arg_pos_to_source=None, + is_export=True, + no_tangents=no_tangents, + pre_dispatch=pre_dispatch, + export_trace_joint=trace_joint, + ) + if fake_mode is None: + fake_mode, shape_env = construct_fake_mode(flat_args, aot_config) + else: + shape_env = fake_mode.shape_env + fake_flat_args, act_input_paths = process_inputs( + flat_args, aot_config, fake_mode, shape_env + ) + # TODO: Improve the descs here with pytree information + fake_flat_args_descs: list[AOTInput] = [ + PlainAOTInput(i) for i in range(len(fake_flat_args)) + ] + + with contextlib.ExitStack() as stack: + aot_state = create_aot_state( + stack, + flat_fn, + fake_flat_args, + fake_flat_args_descs, + aot_config, + fake_mode, + shape_env, + ) + aot_state.fw_metadata.act_input_paths = act_input_paths + aot_graph_capture = aot_stage1_graph_capture(aot_state, flat_fn) + fx_g, meta = aot_stage2_export(aot_state, aot_graph_capture) + + return fx_g, meta, in_spec, out_spec.spec + + +compiled_function = aot_function +compiled_module = aot_module diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/apis.py b/.venv/lib/python3.12/site-packages/torch/_functorch/apis.py new file mode 100644 index 0000000000000000000000000000000000000000..e33f46cf49b51e15583db31c90ee2ca3e000ede7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/apis.py @@ -0,0 +1,510 @@ +# NOTE: We allow Dynamo to see this file (via torch/_dynamo/trace_rules.py) so that it can +# trace through functorch transforms. +# Currently, we can't allow Dynamo to see `eager_transforms.py`/`vmap.py` as that break a lot of thing +# and there isn't a mechanism to selectively expose only some functions (eg. grad) from a file +# to Dynamo. + +from __future__ import annotations + +import functools +from typing import Any, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +from torch._functorch.utils import argnums_t, exposed_in +from torch._functorch.vmap import ( + _check_out_dims_is_int_or_int_pytree, + _check_randomness_arg, + _chunked_vmap, + _process_batched_inputs, + Callable, + in_dims_t, + out_dims_t, + vmap_impl, +) + + +if TYPE_CHECKING: + from collections.abc import Iterable + + import torch + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +# functools.wraps copies __dict__, but these attrs describe the original +# compiled callable, not the transformed function wrapper. +_DYNAMO_WRAPPER_ATTRS = ( + "_torchdynamo_inline", + "_torchdynamo_orig_callable", + "_torchdynamo_wrapper_id", + "_isolate_recompiles_id", + "get_compiler_config", + "aot_compile", + "_is_torch_compile", +) + + +def _wraps_without_dynamo_attrs( + func: Callable[..., Any], +) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: + def inner(wrapper: Callable[_P, _R]) -> Callable[_P, _R]: + wrapper = functools.wraps(func)(wrapper) + for attr in _DYNAMO_WRAPPER_ATTRS: + wrapper.__dict__.pop(attr, None) + return wrapper + + return inner + + +# 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. +# +# vmap's randomness behavior differs from JAX's, which would require a PRNG key +# to be passed everywhere. + + +@exposed_in("torch.func") +def vmap( + func: Callable[_P, _R], + in_dims: in_dims_t = 0, + out_dims: out_dims_t = 0, + randomness: str = "error", + *, + chunk_size: int | None = None, +) -> Callable[_P, _R]: + """ + vmap is the vectorizing map; ``vmap(func)`` returns a new function that + maps ``func`` over some dimension of the inputs. Semantically, vmap + pushes the map into PyTorch operations called by ``func``, effectively + vectorizing those operations. + + vmap is useful for handling batch dimensions: one can write a function + ``func`` that runs on examples and then lift it to a function that can + take batches of examples with ``vmap(func)``. vmap can also be used to + compute batched gradients when composed with autograd. + + .. note:: + :func:`torch.vmap` is aliased to :func:`torch.func.vmap` for + convenience. Use whichever one you'd like. + + Args: + func (function): A Python function that takes one or more arguments. + Must return one or more Tensors. + in_dims (int or nested structure): Specifies which dimension of the + inputs should be mapped over. ``in_dims`` should have a + structure like the inputs. If the ``in_dim`` for a particular + input is None, then that indicates there is no map dimension. + Default: 0. + out_dims (int or Tuple[int]): Specifies where the mapped dimension + should appear in the outputs. If ``out_dims`` is a Tuple, then + it should have one element per output. Default: 0. + randomness (str): Specifies whether the randomness in this + vmap should be the same or different across batches. If 'different', + the randomness for each batch will be different. If 'same', the + randomness will be the same across batches. If 'error', any calls to + random functions will error. Default: 'error'. WARNING: this flag + only applies to random PyTorch operations and does not apply to + Python's random module or numpy randomness. + chunk_size (None or int): If None (default), apply a single vmap over inputs. + If not None, then compute the vmap :attr:`chunk_size` samples at a time. + Note that :attr:`chunk_size=1` is equivalent to computing the vmap with a for-loop. + If you run into memory issues computing the vmap, please try a non-None chunk_size. + + Returns: + Returns a new "batched" function. It takes the same inputs as + ``func``, except each input has an extra dimension at the index + specified by ``in_dims``. It takes returns the same outputs as + ``func``, except each output has an extra dimension at the index + specified by ``out_dims``. + + .. warning: + :func:`vmap` works best with functional-style code. Please do not + perform any side-effects in ``func``, with the exception of + in-place PyTorch operations. Examples of side-effects include mutating + Python data structures and assigning values to variables not captured + in ``func``. + + One example of using :func:`vmap` is to compute batched dot products. PyTorch + doesn't provide a batched ``torch.dot`` API; instead of unsuccessfully + rummaging through docs, use :func:`vmap` to construct a new function. + + >>> torch.dot # [D], [D] -> [] + >>> batched_dot = torch.func.vmap(torch.dot) # [N, D], [N, D] -> [N] + >>> x, y = torch.randn(2, 5), torch.randn(2, 5) + >>> batched_dot(x, y) + + :func:`vmap` can be helpful in hiding batch dimensions, leading to a simpler + model authoring experience. + + >>> batch_size, feature_size = 3, 5 + >>> weights = torch.randn(feature_size, requires_grad=True) + >>> + >>> def model(feature_vec): + >>> # Very simple linear model with activation + >>> return feature_vec.dot(weights).relu() + >>> + >>> examples = torch.randn(batch_size, feature_size) + >>> result = torch.vmap(model)(examples) + + :func:`vmap` can also help vectorize computations that were previously difficult + or impossible to batch. One example is higher-order gradient computation. + The PyTorch autograd engine computes vjps (vector-Jacobian products). + Computing a full Jacobian matrix for some function f: R^N -> R^N usually + requires N calls to ``autograd.grad``, one per Jacobian row. Using :func:`vmap`, + we can vectorize the whole computation, computing the Jacobian in a single + call to ``autograd.grad``. + + >>> # Setup + >>> N = 5 + >>> f = lambda x: x**2 + >>> x = torch.randn(N, requires_grad=True) + >>> y = f(x) + >>> I_N = torch.eye(N) + >>> + >>> # Sequential approach + >>> jacobian_rows = [torch.autograd.grad(y, x, v, retain_graph=True)[0] + >>> for v in I_N.unbind()] + >>> jacobian = torch.stack(jacobian_rows) + >>> + >>> # vectorized gradient computation + >>> def get_vjp(v): + >>> return torch.autograd.grad(y, x, v) + >>> jacobian = torch.vmap(get_vjp)(I_N) + + :func:`vmap` can also be nested, producing an output with multiple batched dimensions + + >>> torch.dot # [D], [D] -> [] + >>> batched_dot = torch.vmap( + ... torch.vmap(torch.dot) + ... ) # [N1, N0, D], [N1, N0, D] -> [N1, N0] + >>> x, y = torch.randn(2, 3, 5), torch.randn(2, 3, 5) + >>> batched_dot(x, y) # tensor of size [2, 3] + + If the inputs are not batched along the first dimension, ``in_dims`` specifies + the dimension that each inputs are batched along as + + >>> torch.dot # [N], [N] -> [] + >>> batched_dot = torch.vmap(torch.dot, in_dims=1) # [N, D], [N, D] -> [D] + >>> x, y = torch.randn(2, 5), torch.randn(2, 5) + >>> batched_dot( + ... x, y + ... ) # output is [5] instead of [2] if batched along the 0th dimension + + If there are multiple inputs each of which is batched along different dimensions, + ``in_dims`` must be a tuple with the batch dimension for each input as + + >>> torch.dot # [D], [D] -> [] + >>> batched_dot = torch.vmap(torch.dot, in_dims=(0, None)) # [N, D], [D] -> [N] + >>> x, y = torch.randn(2, 5), torch.randn(5) + >>> batched_dot( + ... x, y + ... ) # second arg doesn't have a batch dim because in_dim[1] was None + + If the input is a Python struct, ``in_dims`` must be a tuple containing a struct + matching the shape of the input: + + >>> f = lambda dict: torch.dot(dict["x"], dict["y"]) + >>> x, y = torch.randn(2, 5), torch.randn(5) + >>> input = {"x": x, "y": y} + >>> batched_dot = torch.vmap(f, in_dims=({"x": 0, "y": None},)) + >>> batched_dot(input) + + By default, the output is batched along the first dimension. However, it can be batched + along any dimension by using ``out_dims`` + + >>> f = lambda x: x**2 + >>> x = torch.randn(2, 5) + >>> batched_pow = torch.vmap(f, out_dims=1) + >>> batched_pow(x) # [5, 2] + + For any function that uses kwargs, the returned function will not batch the kwargs but will + accept kwargs + + >>> x = torch.randn([2, 5]) + >>> def fn(x, scale=4.): + >>> return x * scale + >>> + >>> batched_pow = torch.vmap(fn) + >>> assert torch.allclose(batched_pow(x), x * 4) + >>> batched_pow(x, scale=x) # scale is not batched, output has shape [2, 2, 5] + + .. note:: + vmap does not provide general autobatching or handle variable-length + sequences out of the box. + """ + from torch.compiler import is_compiling + + _check_randomness_arg(randomness) + if not (chunk_size is None or chunk_size > 0): + raise ValueError( + f"vmap: chunk_size should be None or greater than 0. (got {chunk_size})" + ) + + def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R: + # pyrefly: ignore[bad-argument-type] + return vmap_impl( + # pyrefly: ignore[bad-argument-type] + func, + in_dims, + out_dims, + randomness, + chunk_size, + *args, + **kwargs, + ) + + if not is_compiling(): + wrapped = _wraps_without_dynamo_attrs(func)(wrapped) + + return wrapped + + +def chunk_vmap( + func: Callable[_P, _R], + in_dims: in_dims_t = 0, + out_dims: out_dims_t = 0, + randomness: str = "error", + chunks: int = 2, +) -> Callable[_P, _R]: + """ + chunk_vmap is the vectorizing map (vmap) using chunks of input data. It is a mix of vmap (which vectorizes + everything) and map (which executes things sequentially). ``chunk_vmap`` vectorizes the input with number of + chunks at a time. For more details about vectorizing map, see :func:`vmap`. + + .. note:: + Please use :func:`vmap` with ``chunk_size`` argument instead of this API. + + Args: + func (function): A Python function that takes one or more arguments. + Must return one or more Tensors. + in_dims (int or nested structure): Specifies which dimension of the + inputs should be mapped over. ``in_dims`` should have a + structure like the inputs. If the ``in_dim`` for a particular + input is None, then that indicates there is no map dimension. + Default: 0. + out_dims (int or Tuple[int]): Specifies where the mapped dimension + should appear in the outputs. If ``out_dims`` is a Tuple, then + it should have one element per output. Default: 0. + randomness (str): Specifies whether the randomness in this + vmap should be the same or different across batches. If 'different', + the randomness for each batch will be different. If 'same', the + randomness will be the same across batches. If 'error', any calls to + random functions will error. Default: 'error'. WARNING: this flag + only applies to random PyTorch operations and does not apply to + Python's random module or numpy randomness. + chunks (int): Number of chunks to use to split the input data. Default is 2. + If equals to 1 then :func:`vmap` is called. + + Returns: + Returns a new "batched" function. It takes the same inputs as + ``func``, except each input has an extra dimension at the index + specified by ``in_dims``. It takes returns the same outputs as + ``func``, except each output has an extra dimension at the index + specified by ``out_dims``. + """ + _check_randomness_arg(randomness) + + if chunks == 1: + return vmap(func, in_dims=in_dims, out_dims=out_dims, randomness=randomness) + + def _get_chunk_flat_args( + flat_args_: Iterable[Any], + flat_in_dims_: Iterable[int | None], + chunks_: int, + ) -> Iterable[Any]: + flat_args_chunks = tuple( + t.chunk(chunks_, dim=in_dim) + if in_dim is not None + else [ + t, + ] + * chunks_ + for t, in_dim in zip(flat_args_, flat_in_dims_) + ) + # transpose chunk dim and flatten structure + # chunks_flat_args is a list of flatten args + chunks_flat_args = zip(*flat_args_chunks) + return chunks_flat_args + + @_wraps_without_dynamo_attrs(func) + def wrapped_with_chunks(*args: _P.args, **kwargs: _P.kwargs) -> _R: + _check_out_dims_is_int_or_int_pytree(out_dims, func) + _, flat_in_dims, flat_args, args_spec = _process_batched_inputs( + in_dims, args, func + ) + # Chunk flat arguments + chunks_flat_args = _get_chunk_flat_args(flat_args, flat_in_dims, chunks) + + # Apply vmap on chunks + return _chunked_vmap( + # pyrefly: ignore[bad-argument-type] + func, + flat_in_dims, + chunks_flat_args, + args_spec, + out_dims, + randomness, + **kwargs, + ) + + return wrapped_with_chunks + + +# TODO: Improve the return type of this function +@exposed_in("torch.func") +def grad( + func: Callable[_P, Any], argnums: argnums_t = 0, has_aux: bool = False +) -> Callable[_P, Any]: + """``grad`` operator helps computing gradients of ``func`` with respect to the + input(s) specified by ``argnums``. This operator can be nested to + compute higher-order gradients. + + Args: + func (Callable): A Python function that takes one or more arguments. + Must return a single-element Tensor. If specified ``has_aux`` equals ``True``, + function can return a tuple of single-element Tensor and other auxiliary objects: + ``(output, aux)``. + argnums (int or Tuple[int]): Specifies arguments to compute gradients with respect to. + ``argnums`` can be single integer or tuple of integers. Default: 0. + has_aux (bool): Flag indicating that ``func`` returns a tensor and other + auxiliary objects: ``(output, aux)``. Default: False. + + Returns: + Function to compute gradients with respect to its inputs. By default, the output of + the function is the gradient tensor(s) with respect to the first argument. + If specified ``has_aux`` equals ``True``, tuple of gradients and output auxiliary objects + is returned. If ``argnums`` is a tuple of integers, a tuple of output gradients with + respect to each ``argnums`` value is returned. + + Example of using ``grad``: + + >>> # xdoctest: +SKIP + >>> from torch.func import grad + >>> x = torch.randn([]) + >>> cos_x = grad(lambda x: torch.sin(x))(x) + >>> assert torch.allclose(cos_x, x.cos()) + >>> + >>> # Second-order gradients + >>> neg_sin_x = grad(grad(lambda x: torch.sin(x)))(x) + >>> assert torch.allclose(neg_sin_x, -x.sin()) + + When composed with ``vmap``, ``grad`` can be used to compute per-sample-gradients: + + >>> # xdoctest: +SKIP + >>> from torch.func import grad, vmap + >>> batch_size, feature_size = 3, 5 + >>> + >>> def model(weights, feature_vec): + >>> # Very simple linear model with activation + >>> assert feature_vec.dim() == 1 + >>> return feature_vec.dot(weights).relu() + >>> + >>> def compute_loss(weights, example, target): + >>> y = model(weights, example) + >>> return ((y - target) ** 2).mean() # MSELoss + >>> + >>> weights = torch.randn(feature_size, requires_grad=True) + >>> examples = torch.randn(batch_size, feature_size) + >>> targets = torch.randn(batch_size) + >>> inputs = (weights, examples, targets) + >>> grad_weight_per_example = vmap(grad(compute_loss), in_dims=(None, 0, 0))( + ... *inputs + ... ) + + Example of using ``grad`` with ``has_aux`` and ``argnums``: + + >>> # xdoctest: +SKIP + >>> from torch.func import grad + >>> def my_loss_func(y, y_pred): + >>> loss_per_sample = (0.5 * y_pred - y) ** 2 + >>> loss = loss_per_sample.mean() + >>> return loss, (y_pred, loss_per_sample) + >>> + >>> fn = grad(my_loss_func, argnums=(0, 1), has_aux=True) + >>> y_true = torch.rand(4) + >>> y_preds = torch.rand(4, requires_grad=True) + >>> out = fn(y_true, y_preds) + >>> # > output is ((grads w.r.t y_true, grads w.r.t y_preds), (y_pred, loss_per_sample)) + + .. note:: + Using PyTorch ``torch.no_grad`` together with ``grad``. + + Case 1: Using ``torch.no_grad`` inside a function: + + >>> # xdoctest: +SKIP + >>> def f(x): + >>> with torch.no_grad(): + >>> c = x ** 2 + >>> return x - c + + In this case, ``grad(f)(x)`` will respect the inner ``torch.no_grad``. + + Case 2: Using ``grad`` inside ``torch.no_grad`` context manager: + + >>> # xdoctest: +SKIP + >>> with torch.no_grad(): + >>> grad(f)(x) + + In this case, ``grad`` will respect the inner ``torch.no_grad``, but not the + outer one. This is because ``grad`` is a "function transform": its result + should not depend on the result of a context manager outside of ``f``. + + """ + # To avoid cyclical dependency. + import torch._functorch.eager_transforms as eager_transforms + from torch.compiler import is_compiling + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> tuple[Any, torch.Tensor]: + return eager_transforms.grad_impl(func, argnums, has_aux, args, kwargs) + + if not is_compiling(): + wrapper = _wraps_without_dynamo_attrs(func)(wrapper) + + return wrapper + + +# TODO: Improve the return type of this function +@exposed_in("torch.func") +def grad_and_value( + func: Callable[_P, Any], argnums: argnums_t = 0, has_aux: bool = False +) -> Callable[_P, tuple[Any, Any]]: + """ + Returns a function to compute a tuple of the gradient and primal, or + forward, computation. + + Args: + func (Callable): A Python function that takes one or more arguments. + Must return a single-element Tensor. If specified ``has_aux`` + equals ``True``, function can return a tuple of single-element + Tensor and other auxiliary objects: ``(output, aux)``. + argnums (int or Tuple[int]): Specifies arguments to compute gradients + with respect to. ``argnums`` can be single integer or tuple of + integers. Default: 0. + has_aux (bool): Flag indicating that ``func`` returns a tensor and + other auxiliary objects: ``(output, aux)``. Default: False. + + Returns: + Function to compute a tuple of gradients with respect to its inputs + and the forward computation. By default, the output of the function is + a tuple of the gradient tensor(s) with respect to the first argument + and the primal computation. If specified ``has_aux`` equals + ``True``, tuple of gradients and tuple of the forward computation with + output auxiliary objects is returned. If ``argnums`` is a tuple of + integers, a tuple of a tuple of the output gradients with respect to + each ``argnums`` value and the forward computation is returned. + + See :func:`grad` for examples + """ + from torch._functorch import eager_transforms + from torch.compiler import is_compiling + + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> tuple[Any, torch.Tensor]: + return eager_transforms.grad_and_value_impl( + func, argnums, has_aux, args, kwargs + ) + + if not is_compiling(): + wrapper = _wraps_without_dynamo_attrs(func)(wrapper) + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/autograd_function.py b/.venv/lib/python3.12/site-packages/torch/_functorch/autograd_function.py new file mode 100644 index 0000000000000000000000000000000000000000..ed77cd7a0158c93ee8f4adb50b0848dff97956ee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/autograd_function.py @@ -0,0 +1,935 @@ +from __future__ import annotations + +from typing import Any, NamedTuple, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +import torch +import torch.utils._pytree as pytree +from torch._C._functorch import ( + _unwrap_for_grad, + _wrap_for_grad, + current_level, + TransformType, +) +from torch._functorch.apis import vmap +from torch._functorch.utils import enable_single_level_autograd_function +from torch._functorch.vmap import ( + _add_batch_dim, + _broadcast_to_and_flatten, + restore_vmap, + unwrap_batched, + wrap_batched, +) +from torch._ops import HigherOrderOperator +from torch.autograd.forward_ad import _set_fwd_grad_enabled + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + from torch._functorch.pyfunctorch import FuncTorchInterpreter, VmapInterpreter + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +# autograd.Function technically runs before the regular PyTorch dispatcher. +# This is how features like autocast and torch_dispatch (e.g. PythonTLSSnapshot) +# work with it. One day we might decide to change this, but until then, +# we need to give the illusion that autograd.Function runs before those things. +# +# We do this by using creating a custom HigherOrderOperator that only functorch +# dispatches specially. +class CustomFunctionHigherOrderOperator(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("custom_function_call") + + def __call__( + self, + autograd_function: type[torch.autograd.Function], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> Any: + # When custom_function_call is done dispatching through functorch, + # it should just invoke the autograd.Function. This is consistent + # with the autograd.Function behavior of being invoked before the + # PyTorch dispatcher. + # + # This will lead us into trouble later down the line, but this is + # pre-existing. There is an invariant that a function traced by + # make_fx should have the same behavior when provided the same + # Tensor. However, make_fx sees autograd.Function as a composite + # (because autograd.Function happens before the Python dispatch key) + # and only traces the forward pass. + if torch._C._are_functorch_transforms_active(): + # pyrefly: ignore [missing-attribute] + return super().__call__(autograd_function, *args, **kwargs) + return autograd_function.apply(*args, **kwargs) + + +# "custom_function_call" +# This is the mechanism for an autograd.Function that works with functorch transforms. +# It wraps an autograd.Function; interactions with functorch transforms are defined +# via PyDispatcher and HigherOrderOperator rather than through the traditional PyTorch +# dispatcher. +custom_function_call = CustomFunctionHigherOrderOperator() + + +# The grad rule for custom_function_call is to construct a new _SingleLevelFunction +# (autograd.Function that only works with a single layer (level) of functorch) that: +# - unwraps the inputs +# - redispatches to custom_function_call +# - wraps the outputs +# and whose backward pass calls the original autograd.Function's backward. +# +# Why do we need to redispatch to custom_function_call? +# ----------------------------------------------------- +# This is consistent with how ATen operators work with functorch's grad transform: +# they always redispatch to the original operator. +# Consider torch.sin, and let's say we do grad0(grad1(torch.sin))(x) +# +# grad1 will: +# - set up the autograd graph +# - unwrap the inputs +# - redispatch to at::sin (*) +# - rewrap the outputs on the return +# +# On the redispatch in (*), grad0 will: +# - set up the autograd graph +# - unwrap the inputs +# - redispatch to at::sin +# - rewrap the outputs on the return +# +# To "set up the autograd graph", we generate a _SingleLevelFunction +# and apply it. +@custom_function_call.py_impl(TransformType.Grad) +@custom_function_call.py_impl(TransformType.Jvp) +def custom_function_call_grad( + interpreter: FuncTorchInterpreter, + autograd_function: type[torch.autograd.Function], + *operands: Any, +) -> Any: + Generated = generate_single_level_function(interpreter, autograd_function) + with enable_single_level_autograd_function(): + # pyrefly: ignore [missing-attribute] + flat_out = Generated.apply(*operands) + return flat_out + + +def generate_single_level_function( + interpreter: FuncTorchInterpreter, + autograd_function: type[torch.autograd.Function], +) -> type[torch.autograd.function._SingleLevelFunction]: + level = interpreter.level() + + def forward(*operands: Any) -> Any: + unwrapped_operands = pytree.tree_map_only( + torch.Tensor, lambda x: _unwrap_for_grad(x, level), operands + ) + # Both enable_grad() and _set_fwd_grad_enabled() are necessary no matter + # the transform. _SingleLevelFunction will turn off both fwd and bwd + # gradient computation and we need to turn it back on here. + with torch.enable_grad(), _set_fwd_grad_enabled(True), interpreter.lower(): + unwrapped_output = custom_function_call( + autograd_function, *unwrapped_operands + ) + + # See NOTE [mark_dirty object identity check] + def wrap_fn(output: torch.Tensor) -> torch.Tensor: + return _wrap_for_grad(output, level) + + return wrap_outputs_maintaining_identity( + unwrapped_output, unwrapped_operands, operands, wrap_fn + ) + + def setup_context(ctx: Any, inputs: Any, output: Any) -> Any: + return autograd_function.setup_context(ctx, inputs, output) + + # backward is only used if the transform is TransformType.Grad + def backward(ctx: Any, *grads: Any) -> Any: + result = autograd_function.backward(ctx, *grads) + return result + + # jvp is only used if the transform is TransformType.Jvp + def jvp(ctx: Any, *tangents: Any) -> Any: + result = autograd_function.jvp(ctx, *tangents) + return result + + # This is the sequence of magic words to dynamically generate a Subclass with + # a given name. A Tensor's .grad_fn field has a class name that is the original + # autograd.Function's name + Backward, so we do this to generate some + # meaningful name. + name = f"{autograd_function.__name__}Generated" + Generated = type( + name, + (torch.autograd.function._SingleLevelFunction,), + { + "forward": staticmethod(forward), + "backward": staticmethod(backward), + "jvp": staticmethod(jvp), + "setup_context": staticmethod(setup_context), + }, + ) + return Generated + + +# wrap_outputs_maintaining_identity handles outputs from the vmap, +# backward (vjp), and jvp staticmethod. The way it distinguishes +# between the vmap case and the {backward, jvp} case is if the out_dims +# are specified or not. +# +# NB: we cannot use out_dims=None as the deciding factor. This because +# out_dims=None can still happen in the vmap staticmethod! What the +# user is saying in that case is that their output does not have a +# dimension that is being vmapped over, which is valid. +NO_OUT_DIMS = "not specified" + + +# NOTE [mark_dirty object identity check] +# autograd.Function's ctx.mark_dirty expect a returned input +# to have the same object identity as the input. +# Mode-only functorch will greatly simplify this logic. +def wrap_outputs_maintaining_identity( + outputs: Any, + unwrapped_inputs: Any, + orig_inputs: Any, + wrap_fn: Callable[..., Any], + out_dims: Any = NO_OUT_DIMS, +) -> Any: + flat_unwrapped_inputs = pytree.arg_tree_leaves(*unwrapped_inputs) + flat_orig_inputs = pytree.arg_tree_leaves(*orig_inputs) + + unwrapped_input_to_orig_input = { + id(unwrapped): orig + for unwrapped, orig in zip(flat_unwrapped_inputs, flat_orig_inputs) + } + + flat_outputs, spec = pytree.tree_flatten(outputs) + result = [] + + out_dims_specified = out_dims != NO_OUT_DIMS + + flat_out_dims = None + if out_dims_specified: + flat_out_dims = _broadcast_to_and_flatten(out_dims, spec) + # _broadcast_to_and_flatten returns None if it is unable to broadcast. + # TODO: update following link from master to stable once that's out + if flat_out_dims is None: + raise RuntimeError( + f"The autograd.Function's vmap staticmethod returned an " + f"incompatible (output, out_dims) tuple. " + f"Expected out_dims={out_dims} " + f"to be compatible with the structure of `output`. " + f"out_dims has structure {pytree.tree_flatten(out_dims)[1]} " + f"but output has structure {spec}. " + f"For more details, please see " + f"https://pytorch.org/docs/main/notes/extending.func.html" + ) + + for i, output in enumerate(flat_outputs): + if not isinstance(output, torch.Tensor): + result.append(output) + continue + if id(output) in unwrapped_input_to_orig_input: + result.append(unwrapped_input_to_orig_input[id(output)]) + continue + if out_dims_specified: + if flat_out_dims is None: + raise AssertionError( + "flat_out_dims must not be None when out_dims is specified" + ) + result.append(wrap_fn(output, flat_out_dims[i])) + else: + result.append(wrap_fn(output)) + + return pytree.tree_unflatten(result, spec) + + +# NOTE: [functorch vjp and autograd interaction] +# There's an edge case with the functorch vjp and autograd interaction +# that will eventually be fixed by mode-only functorch. +# The TL;DR is that there's no way to unwrap a dead GradTensorWrapper, +# so we (the framework) need to do it manually. Regular PyTorch operators +# automatically do so this is consistent. +# +# class MyExp(torch.autograd.Function): +# @staticmethod +# def forward(x): +# return x.exp() +# +# @staticmethod +# def setup_context(ctx, inputs, output): +# y = output +# ctx.save_for_backward(y) +# +# @staticmethod +# def backward(gy): +# y, = ctx.saved_tensors() +# return MyMul.apply(gy, y) +# +# x = torch.randn([], requires_grad=True) +# gy = torch.randn([], requires_grad=True) +# _, vjp_fn = vjp(MySin.apply, x) +# result = vjp_fn(gy) +# +# MyMul is an autograd.Function that is not shown here. +# It saves a `y` for backward (since gy requires grad). +# +# in vjp_fn(gy), we get: +# > MyMul.apply(gy, GradTensorWrapper(y, level=dead)) +# Because the y that is saved for backward by MyExp is a GradTensorWrapper +# but is now dead since we are outside the vjp context. +# +# PyTorch dispatcher operations, upon seeing a dead GradTensorWrapper, +# will automatically unwrap the GradTensorWrapper when applied. +# But since autograd.Function technically sits above the regular PyTorch +# dispatcher, it doesn't get this treatment. So we manually do +# the unwrapping to be consistent with regular PyTorch dispatcher operations. + + +class VmapInfo(NamedTuple): + batch_size: int + randomness: str + + +def has_overridden_vmap_rule( + autograd_function: type[torch.autograd.Function], +) -> bool: + return autograd_function.vmap is not torch.autograd.Function.vmap + + +def validate_vmap_returns_tuple_of_two_elements(result: Any) -> None: + base_error_msg = ( + "Expected the vmap staticmethod to have two returns, an output " + "and out_dims with pytree structure compatible with the output. " + ) + if not isinstance(result, tuple): + raise RuntimeError(base_error_msg + f"Got a {type(result)} instead") + if not len(result) == 2: + raise RuntimeError(base_error_msg + f"Got {len(result)} returns instead") + + +@custom_function_call.py_impl(TransformType.Vmap) +def custom_function_call_vmap( + interpreter: VmapInterpreter, + autograd_function: type[torch.autograd.Function], + *operands: Any, + **kwargs: Any, +) -> Any: + if any( + isinstance(val, torch.Tensor) + for val in torch.utils._pytree.tree_flatten(kwargs)[0] + ): + raise NotImplementedError( + f"Run vmap on autograd.Function with kwarg-only Tensor args. " + f"Please do not pass kwarg-only Tensors to autograd.Function. " + f"Got: {kwargs}" + ) + + if autograd_function.generate_vmap_rule: + if has_overridden_vmap_rule(autograd_function): + # TODO: Update link to stable once that's out + # https://github.com/pytorch/pytorch/issues/92029 + raise RuntimeError( + f"You tried to vmap over {autograd_function.__name__}, but " + f"it has both generate_vmap_rule=True and an overridden vmap " + f"staticmethod. Please set generate_vmap_rule=False or delete " + f"the overridden vmap staticmethod to avoid ambiguity. " + f"For more details, please see " + f"https://pytorch.org/docs/main/notes/extending.func.html" + ) + return custom_function_call_vmap_generate_rule( + interpreter, autograd_function, *operands + ) + + if not has_overridden_vmap_rule(autograd_function): + # TODO: Update link to stable once that's out + # https://github.com/pytorch/pytorch/issues/92029 + raise RuntimeError( + f"You tried to vmap over {autograd_function.__name__}, but " + f"it does not have vmap support. Please override and implement the " + f"vmap staticmethod or set generate_vmap_rule=True. " + f"For more details, please see " + f"https://pytorch.org/docs/main/notes/extending.func.html" + ) + + return custom_function_call_vmap_helper( + interpreter, autograd_function.vmap, autograd_function, *operands, **kwargs + ) + + +def custom_function_call_vmap_helper( + interpreter: VmapInterpreter, + vmap_function: Callable[..., Any], + op: Any, + *operands: Any, + **kwargs: Any, +) -> Any: + current_level = interpreter.level() + info = VmapInfo( + batch_size=interpreter.batch_size(), + randomness=interpreter.randomness(), + ) + # We're either in the autograd.Function case (vmap staticmethod) + # or the torch.library.register_vmap case. + autograd_function_case = isinstance(op, torch.autograd.function.FunctionMeta) + + def lower_to_next() -> Any: + if autograd_function_case: + return interpreter.lower() + else: + return torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.FuncTorchBatched) + ) + + unwrapped_operands, in_dims = unwrap_batched(operands, current_level) + # If none of the tensors are batched at the current level, then we skip the + # current level. This saves the user from needing to handle this case in + # their vmap staticmethod (and is consistent with our C++ batching rule API) + if pytree.tree_all(lambda dim: dim is None, in_dims): + with lower_to_next(): + if autograd_function_case: + return custom_function_call(op, *operands) + else: + return op(*operands, **kwargs) + + with lower_to_next(): + result = vmap_function(info, in_dims, *unwrapped_operands, **kwargs) + validate_vmap_returns_tuple_of_two_elements(result) + unwrapped_output, out_dims = result + + # See NOTE [mark_dirty object identity check] + def wrap_fn(output: torch.Tensor, out_dim: int | None) -> torch.Tensor: + return ( + output + if out_dim is None + else _add_batch_dim(output, out_dim, current_level) + ) + + return wrap_outputs_maintaining_identity( + unwrapped_output, unwrapped_operands, operands, wrap_fn, out_dims=out_dims + ) + + +def unpack_outputs(outputs: tuple[Any, ...]) -> tuple[Any, Any]: + out_dims = outputs[-1] + if isinstance(out_dims, tuple): + outputs = outputs[:-1] + else: + outputs = outputs[0] + return outputs, out_dims + + +def custom_function_call_vmap_generate_rule( + interpreter: VmapInterpreter, + autograd_function: type[torch.autograd.Function], + *operands: Any, +) -> Any: + unwrapped_operands, in_dims = unwrap_batched(operands, interpreter.level()) + vmapped_function = vmapify_autograd_function( + autograd_function, + in_dims, + interpreter.batch_size(), + interpreter.randomness(), + ) + with interpreter.lower(): + outputs = custom_function_call(vmapped_function, *unwrapped_operands) + + if not isinstance(outputs, tuple): + raise AssertionError(f"expected outputs to be a tuple, got {type(outputs)}") + outputs, out_dims = unpack_outputs(outputs) + return wrap_batched(outputs, out_dims, interpreter.level()) + + +@custom_function_call.py_impl(TransformType.Functionalize) +def custom_function_call_functionalize( + interpreter: FuncTorchInterpreter, + autograd_function: type[torch.autograd.Function], + generate_vmap_rule: bool, + *operands: Any, +) -> Any: + raise RuntimeError("NYI: Functionalize rule for custom_function_call") + + +def vmapify_autograd_function( + autograd_function: type[torch.autograd.Function], + in_dims: Any, + batch_size: int, + randomness: str, +) -> type[torch.autograd.Function]: + def forward(*operands: Any) -> Any: + outputs, out_dims = restore_vmap( + autograd_function.forward, in_dims, batch_size, randomness + )(*operands) + if isinstance(outputs, torch.Tensor): + return outputs, out_dims + else: + return *outputs, out_dims + + def setup_context(ctx: Any, inputs: Any, outputs: Any) -> None: + outputs, out_dims = unpack_outputs(outputs) + key = id(Generated) + + def inner(inputs: Any, outputs: Any) -> None: + # wrapped_ctx.save_for_backward will: + # - unwrap batchedtensors into (tensor, bdim) + # - save_for_backward(*unwrapped_tensors) + # - assign the bdims to wrapped_ctx._pt_saved_tensors_bdims + wrapped_ctx = CtxCustomSave(ctx, current_level()) + autograd_function.setup_context(wrapped_ctx, inputs, outputs) + + # input_shapes are used for reductify later to reduce expanded gradients + # to the correct shape. + # See NOTE: [Why can't we rely on autograd to reduce expanded gradients?] + # for more details + input_shapes = tuple( + inp.shape if isinstance(inp, torch.Tensor) else None for inp in inputs + ) + if not hasattr(ctx, "_pt_input_shapes"): + # pyrefly: ignore [implicit-any] + ctx._pt_input_shapes = {} + ctx._pt_input_shapes.update({key: input_shapes}) + + if not hasattr(ctx, "_pt_saved_tensors_bdims_stack"): + # pyrefly: ignore [implicit-any] + ctx._pt_saved_tensors_bdims_stack = {} + ctx._pt_saved_tensors_bdims_stack.update( + {key: (wrapped_ctx._pt_saved_tensors_bdims)} + ) + + # See NOTE: [Why do we need to run setup_context under a vmap?] + restore_vmap( + inner, + (in_dims, out_dims), + batch_size, + randomness, + )(inputs, outputs) + + if not hasattr(ctx, "_pt_out_dims"): + # pyrefly: ignore [implicit-any] + ctx._pt_out_dims = {} + ctx._pt_out_dims.update({key: out_dims}) + + def jvp(ctx: Any, *tangents: Any) -> Any: + key = id(Generated) + + def jvp_no_context(saved_tensors: Any, tangents: Any) -> Any: + wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors) + return autograd_function.jvp(wrapped_ctx, *tangents) + + tangent_in_dims = get_tangents_in_dims(in_dims, tangents) + out_tangents, out_tangents_dims = restore_vmap( + jvp_no_context, + (ctx._pt_saved_tensors_bdims_stack[key], tangent_in_dims), + batch_size, + randomness, + )(ctx.saved_tensors, tangents) + + result = reductify( + out_tangents, out_tangents_dims, ctx._pt_out_dims[key], batch_size + ) + if isinstance(result, torch.Tensor): + return result, None + else: + return *result, None + + def backward(ctx: Any, *grad_outputs: Any) -> Any: + key = id(Generated) + grad_outputs_ = grad_outputs[:-1] + grad_outputs_in_dims = ctx._pt_out_dims[key] + + if not isinstance(grad_outputs_in_dims, tuple): + grad_outputs_in_dims = (grad_outputs_in_dims,) + + grad_outputs_in_dims = tuple( + in_dim if grad_output is not None else None + for grad_output, in_dim in zip(grad_outputs_, grad_outputs_in_dims) + ) + + def backward_no_context(inputs: Any) -> Any: + saved_tensors, grad_outputs = inputs + wrapped_ctx = CtxWithSavedTensors(ctx, saved_tensors) + return autograd_function.backward(wrapped_ctx, *grad_outputs) + + grad_ins, grad_ins_dims = restore_vmap( + backward_no_context, + ((ctx._pt_saved_tensors_bdims_stack[key], grad_outputs_in_dims),), + batch_size, + randomness, + )((ctx.saved_tensors, grad_outputs_)) + result = reductify( + grad_ins, grad_ins_dims, in_dims, batch_size, ctx._pt_input_shapes[key] + ) + return result + + name = f"Vmapped{autograd_function.__name__}" + Generated = type( + name, + (torch.autograd.Function,), + { + "forward": staticmethod(forward), + "backward": staticmethod(backward), + "jvp": staticmethod(jvp), + "setup_context": staticmethod(setup_context), + "generate_vmap_rule": True, + }, + ) + + return Generated + + +# tangents might be None, so we need to replace +# the corresponding in_dims with None. +def get_tangents_in_dims(input_dims: Any, tangents: tuple[Any, ...]) -> Any: + flat_in_dims, spec = pytree.tree_flatten(input_dims) + flat_tangents = pytree.arg_tree_leaves(*tangents) + result = [ + None if tangent is None else in_dim + for in_dim, tangent in zip(flat_in_dims, flat_tangents) + ] + return pytree.tree_unflatten(result, spec) + + +# NOTE: [Why do we need to run setup_context under a vmap?] +# Consider the following autograd.Function +# +# class Sum(torch.autograd.Function): +# @staticmethod +# def forward(x): +# return x.sum() +# @staticmethod +# def setup_context(ctx, inputs, outputs): +# ctx.x_shape = inputs[0] +# @staticmethod +# def backward(ctx, gy): +# return gy.expand(ctx.x_shape) +# +# x = torch.randn(B, 4) +# in_dims = 0 +# vmap(Sum.apply, in_dims)(x) +# +# Let's assume for a moment that we didn't vmap setup_context in VmappedSum: +# +# class VmappedSum(torch.autograd.Function): +# @staticmethod +# def forward(x): +# return vmap(Sum.forward, in_dims)(x) +# +# @staticmethod +# def setup_context(ctx, inputs, outputs): +# Sum.setup_context(ctx, inputs, outputs) +# +# @staticmethod +# def backward(ctx, gy): +# def backward_no_context(gy): +# return gy.expand(ctx.x_shape) +# +# dims = (0,) +# gx = vmap(backward_no_context, dims)(gy) +# return gx +# +# We end up saving [B, 4] as x_shape. In the backward, gy has shape [B], +# and we're doing: +# +# def backward_no_context(gy): +# return gy.expand([B, 4]) +# +# gx = vmap(backward_no_context, dims)(gy: "Tensor[B]") +# +# This gives us the wrong result (gx has shape [B, B, 4], but it should +# have shape [4]). Performing vmap over setup_context means the shape +# saved has shape [4] and leads to a correct result shape for gx. + + +# Wraps a ctx object. Forwards all attr accesses to the underlying object +# except for the attrs in _pt_attrs +class WrappedCtx: + _pt_reserved_attrs: tuple[str, ...] = ("_pt_reserved_attrs", "_pt_inner_ctx") + + def __init__(self, ctx: Any) -> None: + if not isinstance(ctx, WrappedCtx): + reserved_attrs = type(self)._pt_reserved_attrs + for name in reserved_attrs: + if not hasattr(ctx, name): + continue + raise RuntimeError( + f"PyTorch reserves the {reserved_attrs} field on ctx. " + "Please name your fields on ctx something else to avoid name " + "collision." + ) + self._pt_inner_ctx = ctx + + def __getattr__(self, name: str) -> Any: + return getattr(self._pt_inner_ctx, name) + + def __setattr__(self, name: str, value: Any) -> None: + if name in type(self)._pt_reserved_attrs: + self.__dict__[name] = value + return + return setattr(self._pt_inner_ctx, name, value) + + +# Wraps ctx to create a new ctx object that overrides saved_tensors. +class CtxWithSavedTensors(WrappedCtx): + _pt_reserved_attrs = ("_pt_new_saved_tensors", *WrappedCtx._pt_reserved_attrs) + + def __init__(self, ctx: Any, new_saved_tensors: Sequence[torch.Tensor]) -> None: + super().__init__(ctx) + self._pt_new_saved_tensors = new_saved_tensors + + @property + def saved_tensors(self) -> Sequence[torch.Tensor]: + return self._pt_new_saved_tensors + + +class CtxCustomSave(WrappedCtx): + _pt_reserved_attrs = ( + "_pt_saved_tensors_bdims", + "_pt_current_level", + *WrappedCtx._pt_reserved_attrs, + ) + + def __init__(self, ctx: Any, current_level: int) -> None: + super().__init__(ctx) + self._pt_saved_tensors_bdims: tuple[Any, ...] = () + self._pt_current_level = current_level + + def save_for_backward(self, *tensors: torch.Tensor) -> None: + unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level) + self._pt_inner_ctx.save_for_backward(*unwrapped_tensors) + self._pt_saved_tensors_bdims = bdims + + def save_for_forward(self, *tensors: torch.Tensor) -> None: + unwrapped_tensors, bdims = unwrap_batched(tensors, self._pt_current_level) + self._pt_inner_ctx.save_for_forward(*unwrapped_tensors) + self._pt_saved_tensors_bdims = bdims + + +def reductify( + grad_input: torch.Tensor | tuple[torch.Tensor, ...], + grad_input_bdim: int | tuple[int, ...], + input_bdim: int | tuple[int, ...], + batch_size: int, + target_shape_without_bdim_to_reduce_to: Any = None, +) -> tuple[Any, ...]: + if not isinstance(grad_input, tuple): + grad_input = (grad_input,) + if not isinstance(grad_input_bdim, tuple): + grad_input_bdim = (grad_input_bdim,) + if not isinstance(input_bdim, tuple): + input_bdim = (input_bdim,) + + if target_shape_without_bdim_to_reduce_to is None: + target_shape_without_bdim_to_reduce_to = len(grad_input) * (None,) + result = tuple( + reductify_leaf(gi, gi_bdim, i_bdim, batch_size, maybe_ishape) + for gi, gi_bdim, i_bdim, maybe_ishape in zip( + grad_input, + grad_input_bdim, + input_bdim, + target_shape_without_bdim_to_reduce_to, + ) + ) + return result + + +def reductify_leaf( + grad_input: torch.Tensor | None, + grad_input_bdim: int | None, + input_bdim: int | None, + batch_size: int, + target_shape_without_bdim_to_reduce_to: Any = None, +) -> torch.Tensor | None: + if grad_input is None: + return None + + if grad_input_bdim is None and input_bdim is None: + return grad_input + + if grad_input_bdim is not None and input_bdim is None: + return grad_input.sum(grad_input_bdim) + + # NOTE: [Why can't we rely on autograd to reduce expanded gradients?] + # For reverse-mode AD, + # given a grad_input and input, it is valid for the user to return a + # grad_input that has a broadcasted shape when compared to the input. + # In this situation, autograd automatically reduces the grad_input to + # the shape of the input. + # + # However, when input_bdim is not None, we have problems. + # + # [example 1] + # grad_input: Tensor[3, 4], input: Tensor[B, 4] + # We can expand grad_input to Tensor[B, 3, 4], but that isn't broadcastable + # from [B, 4]. + # + # [example 2] + # grad_input: Tensor[3, B, 4], input: Tensor[B, 4] + # We can swizzle grad_input to Tensor[B, 3, 4], but that isn't broadcastable + # from [B, 4]. + # + # This means that we need to also reduce the grad_input to the shape of the + # input. This behavior is controlled by the `target_shape_without_bdim_to_reduce_to` flag; + # if not-None then we do the reducing manually, otherwise, we do not do a reduction. + if input_bdim is None: + raise AssertionError("input_bdim must not be None") + + if grad_input_bdim is None: + grad_input = grad_input.unsqueeze(input_bdim) + new_shape = list(grad_input.shape) + new_shape[input_bdim] = batch_size + grad_input = grad_input.expand(new_shape) + grad_input_bdim = input_bdim + + if target_shape_without_bdim_to_reduce_to is not None: + return vmap( + torch.Tensor.sum_to_size, + in_dims=(grad_input_bdim, None), + out_dims=input_bdim, + )(grad_input, target_shape_without_bdim_to_reduce_to) + + if input_bdim != grad_input_bdim: + grad_input = grad_input.movedim(grad_input_bdim, input_bdim) + return grad_input + + +def autograd_function_forward_rewritten( + original_forward: Callable[_P, _R], + original_setup_context: Callable[..., Any], +) -> Callable[..., _R]: + def new_forward(ctx: Any, *args: _P.args, **kwargs: _P.kwargs) -> _R: + output = original_forward(*args, **kwargs) + original_setup_context(ctx, args, output) + return output + + return new_forward + + +class AutogradFunctionApply(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("autograd_function_apply") + + def __call__( + self, + fwd: torch.fx.GraphModule, + bwd: torch.fx.GraphModule, + *fwd_args: Any, + **fwd_kwargs: Any, + ) -> Any: + saved_values: Iterable[Any] | None = None + dirty_idx = fwd_kwargs.get("dirty_idx", []) + dirty_idx_set = set(dirty_idx) + non_differentiable_idx = fwd_kwargs["non_differentiable_idx"] + saved_for_backward_idx = fwd_kwargs["saved_for_backward_idx"] + + class ApplyTemplate(torch.autograd.Function): + @staticmethod + def forward(*args: Any, **kwargs: Any) -> Any: + nonlocal saved_values + + # The Interpreter here is required to propagate metadata + # from the dynamo graph body to the local_map graph body. + # This is required for fx_traceback.annotate for work. + output, saved_values = torch.fx.Interpreter(fwd).run(*args) + + # See Note [Activations with no version counter checks in eager] + # Mark tensors that came from ctx.save_for_backward with metadata. + # This allows AOT autograd to distinguish between tensors saved via + # save_for_backward vs those stashed directly on ctx (e.g., ctx.x = x). + from torch.fx.experimental.proxy_tensor import _get_proxies + + for idx, t in enumerate(saved_values): + if idx not in saved_for_backward_idx: + for proxy in _get_proxies(t): + proxy.node.meta["saved_tensor_with_no_vc_check"] = True + + return output + + @staticmethod + def setup_context(ctx: Any, inputs: tuple[Any, ...], output: Any) -> None: + def selected_outputs(idx: Iterable[int]) -> list[Any]: + idx_set = set(idx) + if isinstance(output, (tuple, list)): + return [x for i, x in enumerate(output) if i in idx_set] + return [output] if 0 in idx_set else [] + + # If users call ctx.mark_dirty() in the original fwd function. + if len(dirty_idx) > 0: + ctx.mark_dirty(*selected_outputs(dirty_idx_set)) + + # If users call ctx.mark_non_differentiable() in the original fwd function. + if len(non_differentiable_idx) > 0: + ctx.mark_non_differentiable( + *selected_outputs(non_differentiable_idx) + ) + + @staticmethod + def backward(ctx: Any, *grad: Any) -> Any: + # The Interpreter here is required to propagate metadata + # from the dynamo graph body to the local_map graph body. + # This is required for fx_traceback.annotate for work. + + if saved_values is None: + raise AssertionError("saved_values must not be None") + return torch.fx.Interpreter(bwd).run(*grad, *saved_values) + + return ApplyTemplate.apply(*fwd_args) + + +autograd_function_apply = AutogradFunctionApply() + + +class DynamoAutogradFunctionTraceHelper: + @staticmethod + def fwd_trace_helper(orig_fwd: Callable[_P, Any]) -> Callable[_P, Any]: + # autograd.Function forward does more than just running the forward method. Most + # of this logic is in C++. Here, we rewrite that functionality in python and let + # Dynamo trace it. + def inner(*args: _P.args, **kwargs: _P.kwargs) -> Any: + with torch.no_grad(): + outs = orig_fwd(*args, **kwargs) + + ctx = args[0] + dirty_tensors = getattr(ctx, "dirty_tensors", None) + + def is_dirty_tensor(tensor: torch.Tensor) -> bool: + if dirty_tensors is None: + return False + return any( + tensor is dirty_tensor + for dirty_tensor in dirty_tensors + if isinstance(dirty_tensor, torch.Tensor) + ) + + def is_tensor_arg(tensor: torch.Tensor) -> bool: + return any( + arg is tensor for arg in args if isinstance(arg, torch.Tensor) + ) + + # Handle the case where if the input is passed on directly to the output, we call view_as + # Refer to https://github.com/pytorch/pytorch/blob/main/torch/csrc/autograd/custom_function.cpp#L254 + if isinstance(outs, torch.Tensor): + if is_tensor_arg(outs) and not is_dirty_tensor(outs): + return outs.view_as(outs) + else: + return outs + + new_outs = [] + for out in outs: + if isinstance(out, torch.Tensor): + if is_tensor_arg(out) and not is_dirty_tensor(out): + new_outs.append(out.view_as(out)) + else: + new_outs.append(out) + else: + new_outs.append(out) + return tuple(new_outs) + + # TODO - there is missing functionality here, where + # autograd.Function overwrites the requires_grad_ of the output + # tensors depending on the `mark_non_differentiable`. Currently, + # this is handled hackily in Dynamo, where we just overwrite the + # variable trackers requires_grad. Refer to the function - + # overwrite_tensor_vt_requires_grad + + return inner diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/batch_norm_replacement.py b/.venv/lib/python3.12/site-packages/torch/_functorch/batch_norm_replacement.py new file mode 100644 index 0000000000000000000000000000000000000000..77aa9b9c2d7c78647d2c850b550754e43c4fe592 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/batch_norm_replacement.py @@ -0,0 +1,27 @@ +import torch.nn as nn +from torch._functorch.utils import exposed_in + + +def batch_norm_without_running_stats(module: nn.Module) -> None: + if ( + isinstance(module, nn.modules.batchnorm._BatchNorm) + and module.track_running_stats + ): + module.running_mean = None + module.running_var = None + module.num_batches_tracked = None + module.track_running_stats = False + + +@exposed_in("torch.func") +def replace_all_batch_norm_modules_(root: nn.Module) -> nn.Module: + """ + In place updates :attr:`root` by setting the ``running_mean`` and ``running_var`` to be None and + setting track_running_stats to be False for any nn.BatchNorm module in :attr:`root` + """ + # base case + batch_norm_without_running_stats(root) + + for obj in root.modules(): + batch_norm_without_running_stats(obj) + return root diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/benchmark_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/benchmark_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4a9f003aab1ece4114ee999ae3a17089bd04c436 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/benchmark_utils.py @@ -0,0 +1,245 @@ +from __future__ import annotations + +import contextlib +import json +import operator +import os +import time +from contextlib import AbstractContextManager +from typing import Any, TYPE_CHECKING +from typing_extensions import TypeVar + +import torch +from torch.profiler import profile, ProfilerActivity + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + +_R = TypeVar("_R") + + +def synchronize() -> None: + pass + + +def dump_chrome_trace( + f: Callable[[tuple[Any, ...]], _R], + input_: tuple[Any, ...], + trace_filename: str, + optimize_ctx: AbstractContextManager[Any], + activities: Sequence[ProfilerActivity], + num_runs: int = 1, + devices: list[str] | None = None, + kwargs_for_f: dict[str, Any] | None = None, + kwargs_for_profiler: dict[str, Any] | None = None, +) -> float: + """ + Output the chrome trace of running f(input_, **kwargs_for_f) with [optimize_ctx] + [num_runs] times to [trace_filename]. + + [activities] are the activities that the profiler will record, e.g. ProfilerActivity.CUDA. + Return total runtime without the profiler + + Outputs to trace_filename + """ + + if devices is None: + devices = ["cuda"] + + global synchronize + if devices != ["cpu"] and torch.accelerator.is_available(): + synchronize = torch.accelerator.synchronize + + if kwargs_for_f is None: + kwargs_for_f = {} + if kwargs_for_profiler is None: + kwargs_for_profiler = {} + + with optimize_ctx: + torch.manual_seed(1337) + for _ in range(5): # warmup runs + f(input_, **kwargs_for_f) + synchronize() + torch.manual_seed(1337) + t0 = time.perf_counter() + for _ in range(num_runs): + f(input_, **kwargs_for_f) + synchronize() + t1 = time.perf_counter() + timing = t1 - t0 + + with profile(activities=activities, **kwargs_for_profiler) as prof: + with optimize_ctx: + synchronize() + torch.manual_seed(1337) + for _ in range(num_runs): + f(input_, **kwargs_for_f) + synchronize() + prof.export_chrome_trace(trace_filename) + + return timing + + +def get_chrome_trace_events(filename: str) -> list[dict[str, Any]]: + with open(filename) as f: + data = json.load(f) + events = data["traceEvents"] + return events + + +def is_gpu_compute_event(event: dict[str, Any]) -> bool: + global gpu_pids + return ( + "pid" in event + and event["pid"] in gpu_pids + and "ph" in event + and event["ph"] == "X" + ) + + +def get_sorted_gpu_events(events: list[dict[str, Any]]) -> list[dict[str, Any]]: + sorted_gpu_events: list[dict[str, Any]] = [] + for event in events: + if not is_gpu_compute_event(event): + continue + sorted_gpu_events.append(event) + return sorted(sorted_gpu_events, key=operator.itemgetter("ts")) + + +def get_duration(sorted_gpu_events: list[dict[str, Any]]) -> int: + if len(sorted_gpu_events) == 0: + return 0 + event = sorted_gpu_events[0] + current_end_time = event["ts"] + event["dur"] + total_duration = event["dur"] + for event in sorted_gpu_events[1:]: + start_time = max(event["ts"], current_end_time) + end_time = event["ts"] + event["dur"] + total_duration = total_duration + max(end_time - start_time, 0) + current_end_time = max(current_end_time, end_time) + return total_duration + + +def get_sorted_gpu_mm_conv_events(events: list[dict[str, Any]]) -> list[dict[str, Any]]: + def is_mm_conv_event(event: dict[str, Any]) -> bool: + return "name" in event and ( + "gemm" in event["name"] + or "conv" in event["name"] + or "cutlass" in event["name"] + or "wgrad" in event["name"] + ) + + gpu_events = get_sorted_gpu_events(events) + sorted_events: list[dict[str, Any]] = [] + for event in gpu_events: + if not is_mm_conv_event(event): + continue + sorted_events.append(event) + return sorted_events + + +gpu_pids: list[Any] = [] + + +def compute_utilization(filename: str, total_length: float) -> tuple[float, float]: + """ + Process the chrome traces outputs by the pytorch profiler to compute GPU Utilization + and percent of times spent on matmul and convolution + + Args: + filename(str): Name of chrome traces file produced by pytorch profiler + + total_length(float): total length of the process without profiler in second + + Return: + tuple: (GPU Utilization, percent of time spent on matmul and convolution) + """ + events = get_chrome_trace_events(filename) + + # get pids of GPU events + global gpu_pids + gpu_pids = [] + for event in events: + if "name" not in event: + continue + if event["name"] == "process_labels" and "GPU" in event["args"]["labels"]: + gpu_pids.append(event["pid"]) + + total_length = total_length * 1e6 + sorted_gpu_events = get_sorted_gpu_events(events) + utilization = get_duration(sorted_gpu_events) / total_length + + sorted_gpu_mm_conv_events = get_sorted_gpu_mm_conv_events(events) + mm_conv_utilization = get_duration(sorted_gpu_mm_conv_events) / total_length + + return utilization, mm_conv_utilization + + +def benchmark_utilization( + f: Callable[[tuple[Any, ...]], _R], + input_: tuple[Any, ...], + trace_folder: str, + optimize_ctx: AbstractContextManager[Any] | None = None, + trace_file_name: str = "tmp_chrome_trace", + num_runs: int = 1, +) -> tuple[float, float]: + """ + Benchmark the GPU Utilization and percent of time spent on matmul and convolution operations of + running f(input_, **kwargs_for_f) with [optimize_ctx] [num_runs] times. + It will produce a chrome trace file in trace_folder/trace_file_name.json + + Example: + + ``` + def f(a): + return a.sum() + + + a = torch.rand(2**20, device="cuda") + utilization, mm_conv_utilization = benchmark_utilization( + f, a, "tmp", trace_file_name="tmp_chrome_trace" + ) + ``` + + Args: + f: function to benchmark + + input_: input to :attr:`f` + + trace_folder: name of the folder to store the chrome trace + + optimize_ctx: the context in which f will run + + trace_file_name: name of the dumped chrome trace file, default to "tmp_chrome_trace" + + num_runs: number of times to run f, excluding the warm-up runs, default to 1. + + Return: + tuple: (GPU Utilization, percent of time spent on matmul and convolution) + + """ + isExist = os.path.exists(trace_folder) + if not isExist: + os.makedirs(trace_folder) + print("create folder " + trace_folder) + + if optimize_ctx is None: + optimize_ctx = contextlib.nullcontext() + + chrome_trace_file_name = os.path.join(trace_folder, trace_file_name + ".json") + total_length = dump_chrome_trace( + f, + input_, + chrome_trace_file_name, + optimize_ctx, + [ProfilerActivity.CUDA], + num_runs=num_runs, + devices=["cuda"], + ) + utilization, mm_conv_utilization = compute_utilization( + chrome_trace_file_name, total_length + ) + + return utilization, mm_conv_utilization diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/compile_utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/compile_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..732188f9afdf7b956b84a6247e94d002014512ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/compile_utils.py @@ -0,0 +1,306 @@ +from __future__ import annotations + +import dataclasses +import operator +import struct +from typing import Any, TYPE_CHECKING + +import sympy + +import torch +import torch.fx as fx +from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils import _pytree as pytree +from torch.utils._pytree import tree_flatten + + +if TYPE_CHECKING: + from collections.abc import Callable, Hashable + + from torch._ops import OpOverloadPacket + from torch.utils._pytree import TreeSpec + +aten = torch.ops.aten + + +@dataclasses.dataclass(frozen=True) +class _ScalarKey: + tag: str + bits: bytes + + +def _normalize_cse_arg(val: Any) -> Any: + # Python float hash/eq is not value-identity: nan != nan (hash(nan) is + # id-based) while -0.0 == 0.0 and hashes equal. Key by bit pattern instead. + if type(val) is float: + return _ScalarKey("float", struct.pack(">d", val)) + if type(val) is complex: + return _ScalarKey("complex", struct.pack(">dd", val.real, val.imag)) + return val + + +def get_aten_target(node: fx.Node) -> OpOverloadPacket | Callable[..., Any] | str: + if hasattr(node.target, "overloadpacket"): + return node.target.overloadpacket + return node.target + + +rand_ops = [ + aten.dropout, + aten._fused_dropout, + aten._standard_gamma, + aten.bernoulli, + aten.multinomial, + aten.native_dropout, + aten.normal, + aten.poisson, + aten.binomial, + aten.rrelu, + aten.rand_like, + aten.rand, + aten.randint, + aten.randn, + aten.randperm, +] + + +# return a new copy of torch.fx.graph.Graph with CSE applied to the input graph +def fx_graph_cse( + fx_g: torch.fx.graph.Graph, + extra_node_key: Callable[[fx.Node], Hashable] | None = None, +) -> fx.Graph: + new_graph = fx.Graph() + env: dict[ + fx.Node, fx.Node + ] = {} # map from node in the old graph to node in the new graph + hash_env: dict[ + tuple[Any, Hashable | None, int], fx.Node + ] = {} # map from hash to a node in the new graph + token_map: dict[ + tuple[Any, Hashable | None, int], dict[str, Any] + ] = {} # map from hash to token + + from torch._inductor.pattern_matcher import ( + compute_mutation_region_ids, + same_mutation_regions, + ) + + compute_mutation_region_ids(fx_g) # type: ignore[arg-type] + + # Make a set of separate storages returned from the output, which will be preserved + # when pruning. This prevents us from deduplicating returned tensors which have + # experienced identical operations, but are separate data structures in eager mode. + output_node: fx.Node = list(fx_g.nodes)[-1] + if output_node.op != "output": + raise AssertionError( + f"expected output_node.op to be 'output', got '{output_node.op}'" + ) + + def checkable_node(node: fx.Node) -> bool: + """We can evaluate only nodes that represent tensors with defined storage.""" + if "val" not in node.meta or not isinstance(node.meta["val"], torch.Tensor): + return False + + try: + node.meta["val"].untyped_storage() + except NotImplementedError: + return False + + return True + + def custom_context_key(node: fx.Node) -> tuple[int, int | None, int | None]: + custom = node.meta.get("custom", {}) + return ( + custom.get("stream", 0), + custom.get("mempool"), + custom.get("mempool_device"), + ) + + output_storages = { + StorageWeakRef(n.meta["val"].untyped_storage()) + for n in output_node.all_input_nodes + if checkable_node(n) + } + nodes_that_alias_outputs = { + n + for n in fx_g.nodes + if checkable_node(n) + and StorageWeakRef(n.meta["val"].untyped_storage()) in output_storages + } + + # A node used as the mutable base of a functional-wrapper op is a distinct + # mutable buffer. Two identical factory ops feeding distinct bases (e.g. the + # forward and backward ``aten.full`` from a pair of ``ones_like`` calls) must + # not be CSE-merged, or the later mutation aliases a buffer that still has a + # live downstream view and reinplacing fails (mirrors the aten.empty + # exclusion below). See pytorch/pytorch#170160. + from torch._higher_order_ops.auto_functionalize import get_mutable_args + from torch._higher_order_ops.triton_kernel_wrap import ( + triton_kernel_wrapper_functional, + ) + + def _add_base(node: Any, bases: set[fx.Node]) -> None: + for b in node if isinstance(node, (list, tuple)) else (node,): + if isinstance(b, fx.Node): + bases.add(b) + + nodes_used_as_mutation_base: set[fx.Node] = set() + for n in fx_g.find_nodes( + op="call_function", target=torch.ops.higher_order.auto_functionalized_v2 + ): + # v2 lists its mutable buffers explicitly in ``_all_bases``. + for base in n.kwargs.get("_all_bases", ()): + _add_base(base, nodes_used_as_mutation_base) + for n in fx_g.find_nodes( + op="call_function", target=torch.ops.higher_order.auto_functionalized + ): + # v1 has no ``_all_bases``; the mutated tensors are the args named by the + # wrapped op's schema (``_mutable_op`` is the first positional). + mutable_op = n.args[0] + mutable_args_names, _ = get_mutable_args(mutable_op) + for name in mutable_args_names: + _add_base(n.kwargs.get(name), nodes_used_as_mutation_base) + for n in fx_g.find_nodes( + op="call_function", target=triton_kernel_wrapper_functional + ): + inner_kwargs = n.kwargs.get("kwargs", {}) + for name in n.kwargs.get("tensors_to_clone", ()): + _add_base(inner_kwargs.get(name), nodes_used_as_mutation_base) + + for n in fx_g.nodes: + # The placeholder, output, and get_attr nodes are copied to the new graph without change + # do not CSE away random operations + if ( + n.op == "placeholder" + or n.op == "output" + or n.op == "get_attr" + or n.is_impure() + or get_aten_target(n) in rand_ops + # aten.empty is non-deterministic, so don't CSE it. + # Also, aten.empty is almost always fusible into its consumer, + # so it's not worth CSEing. + or get_aten_target(n) is aten.empty + or n in nodes_that_alias_outputs + # Keep distinct functional-wrapper mutation bases independent. + or n in nodes_used_as_mutation_base + # This CSE pass currently doesn't handle re-propagation of unbacked + # meta where it'll sometimes eliminate a _local_scalar_dense but not + # replace the meta of downstream users. eg. one bug we've seen is: + # + # _local_scalar_dense_11: "Sym(u14)" = torch.ops.aten._local_scalar_dense.default(select_10); + # sym_sum_2: "Sym(u19 + u20 + u21)" = torch.sym_sum((_local_scalar_dense_11, _local_scalar_dense_12, _local_scalar_dense_13)) + # + # Notice how _local_scalar_dense_11 is u14 but sym_sum_2's meta is incorrectly the old + # pre-cse value of u19. + or ( + "val" in n.meta + and isinstance(n.meta["val"], sympy.Symbol) + and free_unbacked_symbols(n.meta["val"]) + ) + ): + new_node = new_graph.node_copy(n, lambda x: env[x]) + env[n] = new_node + else: # n.op == 'call_function', should never see n.op == 'call_module' or 'call_method' + # substitute args and kwargs members to their mapping in env if exists + # specs can be used to reconstruct nested list/dictionaries + def substitute( + arg_list: list[Any] | tuple[Any, ...], + ) -> tuple[tuple[Any, ...], TreeSpec]: + arg_list, spec = tree_flatten(arg_list) + for i in range(len(arg_list)): + v = arg_list[i] + if isinstance(v, torch.fx.node.Node) and v in env: + arg_list[i] = env[v] + if isinstance(v, (torch.SymBool, torch.SymInt, torch.SymFloat)): + arg_list[i] = v.node + arg_list[i] = _normalize_cse_arg(arg_list[i]) + return tuple(arg_list), spec + + args, args_spec = substitute(n.args) + kwargs, kwargs_spec = substitute(n.kwargs) + + # each token corresponds to a unique node + # nodes with the same token can be substituted + extra_key = extra_node_key(n) if extra_node_key is not None else None + token = { + "target": n.target, + "extra_key": extra_key, + "args": args, + "args_spec": args_spec, + "kwargs": kwargs, + "kwargs_spec": kwargs_spec, + "custom_context": custom_context_key(n), + } + + # hash substituted args to a number, do not hash specs because specs are not hashable + # We need to add type into hash to avoid situations like: + # hash((primals_2, 1.0)) == hash((primals_2, 1)) + hash_arg = hash( + (tuple((a, type(a)) for a in args), tuple((a, type(a)) for a in kwargs)) + ) + hash_val = (n.target, extra_key, hash_arg) + + # check if a node has a substitute and can be eliminated + hash_val_in_hash_env = hash_val in hash_env + overwrite_due_to_mutation = False + if hash_val_in_hash_env and token_map[hash_val] == token: + duplicate_n_prev = hash_env[hash_val] + if same_mutation_regions(n, duplicate_n_prev): + env[n] = duplicate_n_prev + continue + else: + # any futures duplicates should replace with n, not duplicate_n_prev + overwrite_due_to_mutation = True + + new_node = new_graph.node_copy(n, lambda x: env[x]) + env[n] = new_node + if overwrite_due_to_mutation or not hash_val_in_hash_env: + hash_env[hash_val] = new_node + token_map[hash_val] = token + + return new_graph + + +def raise_getitems(gm: fx.GraphModule) -> fx.GraphModule: + # Pre-create a list of nodes to iterate over, as modifying the node order + # during the loop can lead to infinite loops if not handled properly. + getitem_nodes = list( + gm.graph.find_nodes(op="call_function", target=operator.getitem) + ) + + # loop through getitem nodes in the graph and raise them to the parent node + # in reverse order to preserve their original relative order + for node in reversed(getitem_nodes): + if len(node.all_input_nodes) != 1: + raise AssertionError( + f"expected node {node.name} to have 1 input node, got {len(node.all_input_nodes)}" + ) + parent = node.all_input_nodes[0] + parent.append(node) + + gm.recompile() + return gm + + +def strip_overloads(gm: fx.GraphModule) -> None: + """ + Modifies the target of graph nodes in :attr:`gm` to strip overloads. + + Args: + gm(fx.GraphModule): The input Fx graph module to be modified + """ + for node in gm.graph.nodes: + if isinstance(node.target, torch._ops.OpOverload): + node.target = node.target.overloadpacket + gm.recompile() + + +def get_placeholders(graph: fx.Graph) -> list[Any]: + return graph.find_nodes(op="placeholder") + + +def get_outputs(graph: fx.Graph) -> list[fx.Node]: + for node in graph.find_nodes(op="output"): + return pytree.tree_leaves(node.args[0]) + raise AssertionError("No output node found") diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/compilers.py b/.venv/lib/python3.12/site-packages/torch/_functorch/compilers.py new file mode 100644 index 0000000000000000000000000000000000000000..2858fedce8b159d082c388c3a2981b2384ac69d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/compilers.py @@ -0,0 +1,505 @@ +from __future__ import annotations + +import copy +import logging +import os +import pickle +import random +from contextlib import contextmanager +from functools import partial +from typing import Any, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +import sympy + +import torch +import torch.fx as fx +import torch.nn as nn +import torch.utils._pytree as pytree +from torch import SymInt +from torch._decomp import get_decompositions +from torch.fx.experimental.symbolic_shapes import bind_symbols + +from .aot_autograd import aot_function, aot_module, make_boxed_compiler +from .compile_utils import strip_overloads +from .partitioners import ( + default_partition, + draw_graph, + min_cut_rematerialization_partition, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Sequence + + from torch.fx.node import Node + from torch.types import IntLikeType + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +log = logging.getLogger(__name__) + + +# These canonicalizations are needed here (and not decompositions), as the ops +# we're trying to canonicalize to CompositeImplicitAutograd. +def _canonicalize(fx_g: fx.GraphModule) -> fx.GraphModule: + for node in fx_g.graph.find_nodes( + op="call_function", target=torch.ops.aten._to_copy + ): + node.target = torch.ops.aten.to + fx_g.recompile() + return fx_g + + +@contextmanager +def _disable_jit_autocast() -> Generator[None, None, None]: + # pyrefly: ignore [missing-attribute] + old_jit_autocast_flag = torch._C._jit_set_autocast_mode(False) + try: + yield + finally: + # pyrefly: ignore [missing-attribute] + torch._C._jit_set_autocast_mode(old_jit_autocast_flag) + + +@make_boxed_compiler +def ts_compile(fx_g: fx.GraphModule, inps: Sequence[Any]) -> torch.jit.ScriptModule: + """ + Compiles the :attr:`fx_g` with Torchscript compiler. + + .. warning:: + This API is experimental and likely to change. + + Args: + fx_g(fx.GraphModule): The input Fx graph module to be compiled. + + Returns: + Torch scripted model. + """ + + from torch.fx._lazy_graph_module import _unwrap_lazy_graph_module + + fx_g = _unwrap_lazy_graph_module(fx_g) + + with _disable_jit_autocast(): + strip_overloads(fx_g) + + for node in fx_g.graph.find_nodes( + op="call_function", target=torch.ops.aten._to_copy + ): + if len(node.args) == 1 and len(node.kwargs) == 1 and "dtype" in node.kwargs: + node.target = torch.ops.aten.to + + for node in fx_g.graph.nodes: + new_kwargs = {} + for k, v in node.kwargs.items(): + if isinstance(v, torch.device): + v = v.type + new_kwargs[k] = v + node.kwargs = new_kwargs + + fx_g.graph.lint() + + fx_g.recompile() + + f = torch.jit.script(fx_g) + + # pyrefly: ignore [missing-attribute] + torch._C._jit_pass_remove_mutation(f.graph) + + f = torch.jit.freeze(f.eval()) + f = torch.jit.optimize_for_inference(f) + if not any(torch._subclasses.fake_tensor.is_fake_tensor(t) for t in inps): + f(*inps) + return f + + +def _draw_graph_compile( + fx_g: fx.GraphModule, _: Any, name: str, clear_meta: bool = True +) -> fx.GraphModule: + print(fx_g.code) + draw_graph(fx_g, name, clear_meta=clear_meta) + return fx_g + + +def draw_graph_compile( + name: str, +) -> Callable[[fx.GraphModule, list[Any]], fx.GraphModule]: + return make_boxed_compiler(partial(_draw_graph_compile, name=name)) + + +@make_boxed_compiler +def nop(fx_g: fx.GraphModule, _: Any) -> fx.GraphModule: + """ + Returns the :attr:`fx_g` Fx graph module as it is. This is a no-op compiler + and can be used to check accuracy. + + .. warning:: + This API is experimental and likely to change. + + """ + return fx_g + + +class DebugInterpreter(fx.Interpreter): + def run( + self, + *args: Any, + initial_env: dict[Node, Any] | None = None, + enable_io_processing: bool = True, + ) -> Any: + self.symbol_mapping = bind_symbols( + # pyrefly: ignore[bad-argument-type] + self.module, + *args, + ) + return super().run( + *args, initial_env=initial_env, enable_io_processing=enable_io_processing + ) + + def run_node(self, n: Node) -> Any: + def subst_symint(ni: IntLikeType) -> int: + if not isinstance(ni, SymInt): + return ni + r = sympy.expand(ni.node.expr.xreplace(self.symbol_mapping)) + if not r.is_number: + raise AssertionError(f"expected r to be a number, got {r}") + return int(r) + + def subst_symint_tuple(nis: tuple[IntLikeType, ...]) -> tuple[int, ...]: + return tuple(subst_symint(ni) for ni in nis) + + def check_significant_strides(a: torch.Tensor, b: torch.Tensor) -> bool: + if subst_symint(a.numel()) > 0: + for idx in range(a.ndim): + if ( + subst_symint(a.stride(idx)) != b.stride(idx) + and subst_symint(a.size(idx)) > 1 + ): + return False + return True + + def check(nv: torch.Tensor, rv: torch.Tensor, desc: Callable[[], str]) -> None: + if not callable(desc): + raise AssertionError(f"expected desc to be callable, got {type(desc)}") + if nv.dtype != rv.dtype: + raise AssertionError(f"{desc()}: {nv.dtype} != {rv.dtype}") + if subst_symint_tuple(nv.size()) != rv.size(): + raise AssertionError( + f"{desc()}: {nv.size()} aka {subst_symint_tuple(nv.size())} != {rv.size()}" + ) + same_strides = check_significant_strides(nv, rv) + if not same_strides: + raise AssertionError( + f"{desc()}: {nv.stride()} aka {subst_symint_tuple(nv.stride())} != {rv.stride()}" + ) + + r = super().run_node(n) + if "val" in n.meta: + n_vals, _n_spec = pytree.tree_flatten(n.meta["val"]) + r_vals, _r_spec = pytree.tree_flatten(r) + # TODO: There is some sort of problem where we record that an + # operator returned a tuple/list, and then later it turns out the + # real version of the operator returned a list/tuple. Need to + # figure out what's actually going on here, the error itself is + # harmless enough as we only getitem out the outputs. + # assert n_spec == r_spec, f"{n_spec} != {r_spec}" + if len(n_vals) != len(r_vals): + raise AssertionError(f"{len(n_vals)} != {len(r_vals)}") + for i, nv, rv in zip(range(len(n_vals)), n_vals, r_vals): + if not isinstance(rv, torch.Tensor): + continue + check(nv, rv, lambda: f"output {i} where {self.symbol_mapping}") + return r + + +@make_boxed_compiler +def debug_nop( + fx_g: fx.GraphModule, _: Any +) -> Callable[[DebugInterpreter, Any, dict[Node, Any] | None, bool], Any]: + """ + Returns a (slow) interpreter over the FX graph module that also checks + various debugging properties (e.g., that tracing strides matched real + strides.) + """ + return DebugInterpreter(fx_g).run + + +@make_boxed_compiler +def simple_ts_compile(fx_g: fx.GraphModule, _: Any) -> torch.jit.ScriptModule: + strip_overloads(fx_g) + f = torch.jit.script(fx_g) + f = torch.jit.freeze(f.eval()) + return f + + +def nnc_jit(f: Callable[..., Any]) -> Callable[..., Any]: + return aot_function(f, simple_ts_compile) + + +aten = torch.ops.aten +default_decompositions = { + aten.detach, + aten.gelu_backward, + aten.leaky_relu_backward, + aten.sigmoid_backward, + aten.threshold_backward, + aten.hardtanh_backward, + aten.hardsigmoid_backward, + aten.hardswish_backward, + aten.tanh_backward, + aten.silu_backward, + aten.elu_backward, + aten.cudnn_batch_norm, + aten.cudnn_batch_norm_backward, + aten.masked_fill.Scalar, + aten.masked_fill.Tensor, + aten.elu, + aten.leaky_relu, + aten.hardtanh, + aten.hardswish, + aten.hardsigmoid, + aten.conj_physical, + aten.is_same_size, +} + +# pyrefly: ignore[bad-argument-type] +default_decompositions = get_decompositions(default_decompositions) + + +@make_boxed_compiler +def print_compile(fx_g: fx.GraphModule, _: Any) -> fx.GraphModule: + print(fx_g.code) + return fx_g + + +def memory_efficient_fusion( + fn: Callable[_P, _R] | nn.Module, + **kwargs: Any, +) -> Callable[_P, _R] | nn.Module: + """ + Wrapper function over :func:`aot_function` and :func:`aot_module` to perform + memory efficient fusion. It uses the + :func:`min_cut_rematerialization_partition` partitioner to perform efficient + recomputation. It uses NVFuser to compile the generated forward and backward + graphs. + + .. warning:: + This API is experimental and likely to change. + + Args: + fn (Union[Callable, nn.Module]): A Python function or a ``nn.Module`` + that takes one or more arguments. Must return one or more Tensors. + **kwargs: Any other overrides you want to make to the settings + + Returns: + Returns a ``Callable`` or ``nn.Module`` that retains the eager behavior + of the original :attr:`fn`, but whose forward and backward graphs have + gone through recomputation optimizations, and the graphs have been + compiled with nvfuser. + + """ + config = { + "fw_compiler": ts_compile, + "bw_compiler": ts_compile, + "partition_fn": min_cut_rematerialization_partition, + "decompositions": default_decompositions, + } + config.update(kwargs) + if isinstance(fn, torch.nn.Module): + return aot_module(fn, **config) # pyrefly: ignore[bad-argument-type] + else: + return aot_function(fn, **config) # pyrefly: ignore[bad-argument-type] + + +def debug_compile( + fx_g: fx.GraphModule, inps: Sequence[torch.Tensor] +) -> torch.jit.ScriptModule: + fx_g.to_folder("foo") + print( + f""" +############################################################## +# To minimize FX graph, copy and paste the below and run it # +############################################################## + +import torch +import torch.fx as fx +from functorch.compile import minifier, check_nvfuser_subprocess, check_nvfuser_correctness_subprocess + +inps = {[(i.shape, i.dtype) for i in inps]} +inps = [torch.ones(shape, dtype=dtype, device='cuda') for (shape, dtype) in inps] +from foo import FxModule +mod = FxModule().cuda() + +with torch.jit.fuser("fuser2"): + # check_nvfuser_subprocess can be replaced with check_nvfuser_correctness_subprocess + minifier(fx.symbolic_trace(mod), inps, check_nvfuser_subprocess) +""" + ) + # pyrefly: ignore[missing-import, missing-module-attribute] + from foo import FxModule + + FxModule().cuda()(*inps) + + return ts_compile(fx_g, inps) + + +graph_index: int = 0 + + +def get_inputs(input_data_path: str) -> list[torch.Tensor]: + """ + Return a random input for the given inputs meta generated from _save_fx_default. + """ + inputs: list[torch.Tensor] = [] + with open(input_data_path, "rb") as f: + inputs_meta = pickle.load(f) + inputs = [] + for meta in inputs_meta: + if len(meta) == 1: + type = meta + input_ = type(random.random()) + else: + type, shape, _stride, dtype, device = meta + if dtype in { + torch.int, + torch.int32, + torch.int64, + torch.bool, + torch.int, + torch.uint8, + int, + float, + }: + input_ = torch.randint(0, 1, shape, dtype=dtype, device=device) + else: + input_ = torch.rand(shape, dtype=dtype, device=device) + inputs.append(input_) + return inputs + + +def _save_fx_default( + current_name: str, + folder_name: str, + dump_example_input: bool, + gm: torch.fx.GraphModule, + example_inputs: list[torch.Tensor], +) -> nn.Module: + """ + The forward, backward, and joint computation graph will be stored in + {folder_name}/{current_name}/{current_name}_forward_{graph_index}, + {folder_name}/{current_name}/{current_name}_backward_{graph_index}, and + {folder_name}/{current_name}/{current_name}_joint_{graph_index} respectively. + The input shape of the graphs will be stored in the .input files. + These files can be loaded with pickle, + and is a list of format (type, shape, stride, dtype, device). + In the case of type = int or float, it is just (type,). + For joint graph input, it is a nested list [[],[]] + where the two inner lists have the same format. + If dump_example_input is True, example_inputs will be stored in .pt file. + Since each function might produce multiple graphs, + the graph_index is used to distinguish different graphs + """ + from functorch.compile import aot_module_simplified + + def get_input_meta(args: Any) -> list[Any]: + input_meta = [] + if len(args) > 0 and isinstance(args[0], tuple): # joint input + input_meta += get_input_meta(args[0]) + input_meta += get_input_meta(args[1]) + return input_meta + for arg in args: + if type(arg) is int or type(arg) is float: + input_meta.append((type(arg),)) + else: + input_meta.append( + (type(arg), arg.shape, arg.stride(), arg.dtype, arg.device) + ) + return input_meta + + def graph_saver_helper( + gm_to_save: fx.GraphModule, args: Any, type_name: str + ) -> None: + global graph_index + if len(gm_to_save.graph.nodes) == 0: + log.log( + logging.WARNING, + "No nodes in graph {%s}_{%s}_{%s}.", + current_name, + type_name, + graph_index, + ) + return + + gm = copy.deepcopy(gm_to_save) + gm.graph.set_codegen(torch.fx.graph.CodeGen()) # remove codegen + gm.recompile() + + input_meta = get_input_meta(args) + + os.makedirs(f"{folder_name}/{current_name}", exist_ok=True) + gm.to_folder( + f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}" + ) + with open( + f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}/{current_name}_{type_name}_{graph_index}.input", + "wb", + ) as f: + pickle.dump(input_meta, f) + if dump_example_input: + torch.save( + args, + f"{folder_name}/{current_name}/{current_name}_{type_name}_{graph_index}/{current_name}_{type_name}_{graph_index}.pt", + ) + + def graph_saver_forward( + gm: fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> fx.GraphModule: + graph_saver_helper(gm, example_inputs, "forward") + return gm + + def graph_saver_backward( + gm: fx.GraphModule, example_inputs: list[torch.Tensor] + ) -> fx.GraphModule: + graph_saver_helper(gm, example_inputs, "backward") + global graph_index + graph_index += 1 + return gm + + def graph_saver_joint( + gm: fx.GraphModule, joint_args: list[torch.Tensor] + ) -> tuple[fx.GraphModule, fx.GraphModule]: + graph_saver_helper(gm, joint_args, "joint") + return default_partition(gm, joint_args) # pyrefly: ignore[missing-argument] + + # pyrefly: ignore[bad-return] + return aot_module_simplified( + gm, + example_inputs, + fw_compiler=graph_saver_forward, # pyrefly: ignore[bad-argument-type] + bw_compiler=graph_saver_backward, # pyrefly: ignore[bad-argument-type] + partition_fn=graph_saver_joint, + decompositions=default_decompositions, # pyrefly: ignore[bad-argument-type] + ) + + +# WARNING: This isn't tested anywhere!! +def graph_dumper_aot( + current_name: str, folder_name: str, dump_example_input: bool = False +) -> Callable[[bool, nn.Module], Any]: + """ + Dump the forward, backward, and joint computation graph. + Example Usage: + save_fx_func = graph_dumper_aot(current_name, folder_name, dump_example_input = False) + optimize_ctx = torchdynamo.optimize( + save_fx_func + ) + with torch.enable_grad(): + with optimize_ctx: + result = forward_and_backward_pass(model, example_inputs) + """ + global graph_index + graph_index = 0 + return partial(_save_fx_default, current_name, folder_name, dump_example_input) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/config.py b/.venv/lib/python3.12/site-packages/torch/_functorch/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a7dbde4a4181ac233187739fe215b7e91f9f19d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/config.py @@ -0,0 +1,464 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from collections.abc import Callable + + +""" +Global flags for aot autograd +""" + +import os +import sys +from typing import Literal, TYPE_CHECKING + +from torch.utils._config_module import Config, install_config_module + + +# [@compile_ignored: debug] +_save_config_ignore = [ + # callable not serializable + "joint_custom_pass", + # callable configs with uuid() for caching, or raw callables + "activation_memory_budget_runtime_estimator", + "activation_memory_budget_solver", +] + + +# Converts torch rng ops to their functional philox rng equivalents. Note that +# we functionalize only CUDA rng ops today. +functionalize_rng_ops = False + +# can be useful for debugging if we are incorrectly creating meta fake tensors +fake_tensor_allow_meta = os.environ.get("FAKE_ALLOW_META", "1") != "0" + +# Enables optional asserts in hotpath code to check for errors. If +# you are seeing weird accuracy problems, try turning this on. +# This is currently off by default as it will harm tracing time, +# but it is on by default for aot_eager. +debug_assert = False + +debug_partitioner = os.environ.get("AOT_PARTITIONER_DEBUG", "0") != "0" + +# See # NOTE [Export custom triton op] +decompose_custom_triton_ops = True + +static_weight_shapes = True + +# See https://github.com/pytorch/pytorch/issues/141881 +# Tells partitioner that parameters are free to save for backward. +treat_parameters_as_free_to_save = True + +# Applies CSE to the graph before partitioning +cse = True + +# When the partitioner's _size_of encounters a (Fake)ScriptObject in node +# metadata, it has no general way to know the object's true memory footprint: +# a ScriptObject may hold tensors internally. By default we raise rather than +# guess. Enabling this flag makes _size_of assume such objects are zero size, +# which unblocks dynamic-shapes compilation of models containing ScriptObject +# parameters (e.g. embedding-table configs from FBGEMM) at the cost of +# soundness. This is a temporary escape hatch until we have a principled way to +# probe the size of a (Fake)ScriptObject. +unsafe_treat_script_objects_as_zero_size = False + +from torch._environment import is_fbcode + + +enable_autograd_cache: bool = Config( + justknob="pytorch/remote_cache:enable_local_autograd_cache", + env_name_force="TORCHINDUCTOR_AUTOGRAD_CACHE", + default=True, +) + +autograd_cache_allow_custom_autograd_functions: bool = Config( + env_name_force="TORCHINDUCTOR_AUTOGRAD_CACHE_ALLOW_CUSTOM_AUTOGRAD", default=False +) + +# For now, this is just for enabling unit testing in test_aot_autograd_cache.py +# We will either make this the default with AOTAutogradCache, or +# we'll just use it in the precompile flow. So there's no +# need to add env vars or make it configurable +bundled_autograd_cache: bool = False + +bypass_autograd_cache_key: bool = False + +# Whether or not to normalize placeholder names in graphs +# from dynamo in AOTAutogradCache +autograd_cache_normalize_inputs = not is_fbcode() + +# Enable debug mode at first invocation to check if custom ops are valid. +# When enabled, this checks that custom operators don't violate aliasing constraints. +# +# check_custom_op_aliasing: Controls whether to run the custom op aliasing check at all. +# - When True: The check runs on first invocation of compiled functions. +# - When False: The check is skipped entirely. +# +# error_on_custom_op_aliasing: Controls behavior when a violation is detected. +# Only has effect when check_custom_op_aliasing is True. +# - When True: Raises RuntimeError on aliasing violations. +# - When False: Emits UserWarning on aliasing violations. +# +# Deprecated: Custom ops returning aliased outputs is deprecated and will +# become an error in a future version of PyTorch. Currently error_on_custom_op_aliasing +# is True in CI unless explicitly overridden. +check_custom_op_aliasing = True +error_on_custom_op_aliasing: bool = Config( + env_name_force="TORCHINDUCTOR_ERROR_ON_CUSTOM_OP_ALIASING", + default=bool(os.getenv("CI")), +) + + +def remote_autograd_cache_default() -> bool | None: + if os.environ.get("TORCHINDUCTOR_AUTOGRAD_REMOTE_CACHE") == "1": + return True + if os.environ.get("TORCHINDUCTOR_AUTOGRAD_REMOTE_CACHE") == "0": + return False + return None + + +enable_remote_autograd_cache = remote_autograd_cache_default() + + +# When AOTAutograd regenerates aliased graph outputs, +# attempt to use functionalization's view-replay logic +# before falling back to the autograd engine's view replay or as_strided. +# This can have some perf implications +# (although for many models this will not matter). +# (1) If you have many view ops chained together, replaying all of them +# at runtime can have more overhead compared to a single as_strided call +# (2) If you are doing training, AsStridedBackward is quite slow, +# and the individual view op backward formulas will likely be faster. +# (3) Some backends like XLA do not support as_strided + +# Temporary hack: disable this flag for internal +# (needed to fix an internal issue while avoiding bumping XLA pin) +# eventually: either default this config to false completely +# once XLA pin update works, +# or default config to true and fix relevant bugs + + +# View replay is currently not compatible with AOTAutogradCache, since +# FunctionalTensors are not serializable. We'll need to make them +# serializable before enabling warm cache with this config turned on. +view_replay_for_aliased_outputs = not is_fbcode() + +# Restricts the amount of computation AOTAutograd can do. +# NB: We have essentially disabled this heuristic now. However, this is kept +# here for now in case it's useful. Setting it low can artificially reduce the +# amount of recomputation AOTAutograd performs, although not in any kind of +# principled way. +max_dist_from_bw = 1000 + + +# Bans recomputation of nodes that are reading from nodes that are far before +# the current node +ban_recompute_used_far_apart = True +# Breaks up long chain of fusible ops, as otherwise we can have an arbitrarily +# long chain of recomputation in the backwards pass. +ban_recompute_long_fusible_chains = True +# Bans recomputation of nodes that must be materialized in the backwards pass +# (used by a non-fusible node) +ban_recompute_materialized_backward = True +# Chooses to ban recomputation of nodes based off an allowlist. Setting it to +# False changes it to use a denylist. Main change is on operators like +# sort/pool/stuff that isn't cheap enough to be fusible for free but also isn't +# that expensive +ban_recompute_not_in_allowlist = True +# Chooses to ban recomputation of reductions. This is generally a good idea, as +# the result of reductions is generally very small but recomputing reductions in +# a fusion can be expensive. +ban_recompute_reductions = True +# Prevents the partitioner from ever saving views (i.e. always recompute them). +# Generally a good idea since views are free to recompute. +recompute_views = False +# Set this flag to enable considering non-built-in ops, including triton and custom +# ops, for recomputation during the knapsack optimization solver. +is_non_builtin_to_include = False + +# Rematerialize AC nodes for graphs with forward+loss+backward in one graph. +# This optimization minimizes activation checkpoint node lifetimes by computing them +# just-in-time. For AC nodes only used in backward, they are deferred to backward region +# instead of being computed and saved in forward. This reduces peak memory usage. +# Note: This only applies to forward+loss+backward graphs where torch.autograd.grad is allowed +# in the graph. Joint graphs (standard AOTAutograd) use the partitioner instead. +remat_using_tags_for_fwd_loss_bwd_graph = True + +# By default, the partitioner is purely trying to optimize for runtime (although +# it should always use less memory than eager) +# This knob controls the partitioner to make that tradeoff for you, choosing the +# fastest option that saves less activations than the memory budget. +# Specifically, 0.0 corresponds to the activation memory from applying +# activation checkpointing to the full compiled region, and 1.0 corresponds to +# the activation memory from the default runtime-optimized strategy. So, 0.4 +# would result in a strategy that saves 40% of the activations compared to the +# default strategy. +# It solves a 0-1 knapsack to find the minimum recompute necessary to stay below +# the activation memory budget. +# NOTE: This *cannot* be treated as +activation_memory_budget = 1.0 + +# This controls how we estimate the runtime when deciding what the cheapest +# operators to recompute are. The 3 options are +# "flops": Bases it off of the flop count provided by torch.utils.flop_counter +# "profile": Benchmarks each operator to come up with a runtime +# "testing": Returns 1 for everything +activation_memory_budget_runtime_estimator = "flops" + +# This controls the solver used for the 0-1 knapsack. By default we use a +# quantized DP solution ("dp"). The other approaches are a "greedy", an "ilp" +# (which has a scipy dependency) and "dp_knapsack_sliding_hirschberg", which +# used memory-efficient quantized DP solution +activation_memory_budget_solver = "dp" + +# This dumps out an SVG visualization of the expected runtime vs. activation +# memory tradeoffs for all memory budget values from 0 to 1 in increments of +# 0.5. See an example here: +# https://github.com/pytorch/pytorch/pull/126320#discussion_r1625104015 +visualize_memory_budget_pareto = ( + os.environ.get("PARTITIONER_MEMORY_BUDGET_PARETO", "0") == "1" +) + +# This controls the directory in which to dump the SVG plot with the pareto +# frontier of the activation checkpointing memory-vs-runtime tradeoffs. +memory_budget_pareto_dir = os.environ.get("PARTITIONER_MEMORY_BUDGET_PARETO_DIR") + +# Sets all of the ban_recompute heuristics to False except ban_recompute_reductions +# Generally, this will probably result in some memory improvement, but at the +# cost of some performance +aggressive_recomputation = False + +# activation offloading enablement (testing purpose) +enable_activation_offloading = False + +# activation offloading with separate CUDA stream +activation_offload_separate_stream = False + +# activation offloading wait sinking when using separate stream (fwd graph) +activation_offload_sink_wait = False + +# activation reloading with prefetching when using separate streams (bwd graph) +activation_reload_prefetch = False + +# CPU ↔ GPU bandwidth in GB/s, used to estimate transfer times for prefetch +# scheduling. This is hardware-specific and should be set by the user. +activation_offload_cpu_gpu_bw: float = 50.0 + +# If FakeTensor.data_ptr() should error. +# This option is independent of AOTAutograd and torch.compile, but our policy +# is to turn it off during torch.compile. +fake_tensor_allow_unsafe_data_ptr_access = True + +# Unlifts effect tokens from the inputs/outputs in the traced graph and instead +# inserts make_token/sink_token calls in the graph to create tokens and then +# sink them at the end. Note that this means the graph is no longer functional +# which may lead to silent errors unless the backend knows how to handle the +# tokens. +unlift_effect_tokens = False + +# NOTE: [The default layout constraint for custom operators.] +# This must be the name of one of the layout constraint tags +# (that is, one of {"needs_fixed_stride_order", "flexible_layout"}), +# If the custom op does not have a layout constraint tag already +# then we assume the following applies. +# +# This config is respected by Inductor and we recommend other backends also +# respect it. +# This config is in torch._functorch and not torch._inductor because it affects +# ProxyTensor tracing. +custom_op_default_layout_constraint: Literal[ + "needs_exact_strides", "needs_fixed_stride_order", "flexible_layout" +] = "needs_exact_strides" + + +# Run aot eager decomp partition with CrossRefFakeMode +# options = False, "all", "custom_ops" +fake_tensor_crossref = False + +# This mode specifies that we should also keep track of the real +# tensor along with the fake tensor, and do real compute. While +# seemingly this eliminates the whole point of fake tensors, there are +# two obvious use cases for it: +# +# 1. When users call item()/other data dependent operations, +# if we propagate_real_tensors we are able to determine what +# the true value is and keep going. +# +# 2. It can be useful for testing, when you want to see if the fake +# and real tensors agree with each other. (Note that there are +# currently known inaccuracies in how we clone real tensors, that +# would have to be tightened up for this to be useful in this +# case.) +# +# Note that fake tensors are typically understood to be cheap to store +# indefinitely, so we tend to hold on to them longer than we would +# hold onto the real tensors. So we also support you explicitly +# deallocating the real tensor associated with a fake tensor, at which +# point we will stop propagating real tensors. +# +# One more thing: when you provide a real tensor to fakeify, we will +# clone it, so that we can safely perform mutations on it if necessary. +# This will increase live memory usage. This could potentially be +# optimized by using COW. We also currently do not faithfully +# maintain autograd metadata on the real tensor; this is fine because +# AOTAutograd will only use the fake tensor to determine leafness/etc +# of tensors in question. +fake_tensor_propagate_real_tensors = False + +# AOTDispatcher traces out a backward graph at the time of the forward pass. +# This flag controls whether or not that backward graph gets autocast behavior +# applied to it. +# +# The options are either: +# - "same_as_forward". We assume that the backward of the torch.compile'ed region +# will be run under the same autocast context manager that the region was run +# under. This is equivalent to running the following code in eager: +# +# with torch.amp.autocast(...): +# y = region(x) +# ... +# z.backward() +# +# - "off". We assume that the backward of the torch.compile'd region will +# not be run under any autocast context managers. +# This is equivalent to running the following code in eager: +# +# with torch.amp.autocast(...): +# y = region(x) +# ... +# z.backward() +# +# - or a list of kwargs dicts that represent an autocast context manager to turn +# on during the backward pass. +# +# e.g. [{"device_type": "cuda"}] is equivalent to running the following code in eager: +# +# y = region(x) +# ... +# with torch.amp.autocast(device="cuda"): +# z.backward() +backward_pass_autocast = "same_as_forward" + +# This controls whether we collect donated buffers. This flag must be set +# False if a user wants to retain_graph=True for backward. +donated_buffer = not is_fbcode() + +# Controls the default graph output format used by draw_graph. +# Most supported formats are defined here https://graphviz.org/docs/outputs/. +# The "dot" and "raw" formats write raw DOT text without invoking Graphviz. +torch_compile_graph_format = os.environ.get("TORCH_COMPILE_GRAPH_FORMAT", "svg") + +# Valid only if fake_tensor_propagate_real_tensors = True; if a fake-real +# kernel mismatch is detected, bypasses by making a fake kernel from the +# real tensor outputs. +generate_fake_kernels_from_real_mismatches = False + +# When there are device mismatches in FakeTensor device propagation, +# prefer a specific device type over others. This is particularly useful +# in full compiled mode where intermediate tensors with device mismatches +# represent only logical differences during compilation - these intermediate +# tensors will never physically materialize in the binary execution, so the +# device mismatch is not a real runtime concern. Enabling this allows the +# compiler to proceed with compilation by choosing the preferred device type +# for consistency. For example, set to "mtia" to prefer MTIA devices over +# CPU, or "cuda" to prefer CUDA devices over CPU. +fake_tensor_prefer_device_type: str | None = None + +# CUDAGraph safe run_with_rng functionalization. +graphsafe_rng_functionalization = True + +# Whether or not to eagerly compile the backward +# used by AOT compile and other settings +# TODO: once AOT compile calls aot autograd directly instead of +# through compile_fx, we can remove this +force_non_lazy_backward_lowering = False + +# only for testing, used to turn functionalization off in AOTDispatcher +_test_disable_functionalization = True + +# Error on BypassAOTAutogradCache instead of just a warning +# Used for tests +strict_autograd_cache = False + +# Note [Recomputing collectives in the partitioner] +# The purpose of this config is as follows: +# - We have many passes in the compiler (min-cut partitioning, DCE, etc) +# which can reorder or delete duplicate nodes in the graph +# - If any of these passes reorder/delete/duplicate a collective +# in a setting where the compiler is being run independently on multiple +# ranks, we run the risk that the compiler will make a different decision on +# different ranks, resulting in a NCCL hang when using torch.compile +# To handle this, we will (by default) ensure that collectives are not modified +# by the compiler. +# +# A few examples: +# - don't dead-code-eliminate collectives +# (in case they are dead on rank i but not rank j) +# - don't recompute collectives in partitioning +# (in case we recompute on rank i but not rank j) +# +# Today this flag **must** be set to false, but eventually +# we want the option to set it to true. +# In order to potentially optimize collectives, we'll need the compiler +# to broadcast information across ranks at compile time to ensure +# that any decisions on collectives are made consistently. +unsafe_allow_optimization_of_collectives = False + +# See Note [AOTAutograd Tangent Subclassness for mutated inputs] +# TODO(ivankobzarev): Remove this config, being able to deduce it compile time. +disable_guess_zero_tangent_for_mutated_input_subclass = False + +# See Note [Tangents memory format] +# By default tangents strideness is guessed to be contiguous, +# At runtime non contiguous tangents will be coerced to be contiguous. +# This config changes this guess for tangents strides to be the same as outputs. +# TODO(ivankobzarev): Remove this config once extra memory usage is investigated. +guess_tangent_strides_as_outputs = not is_fbcode() + + +# This is a temporary config to ensure all ranks take the same decision in the partitioner +# it will ultimately be removed once we share size_hints across ranks through compiler collectives +_sync_decision_cross_ranks = False + +# By default apply inlined saved_tensors_hooks only for "donated" buffers. +# "donated" buffers are invisible to the user, they are intermediates of the forward graph. +# Applying saved tensors hooks for memory optimizations only for intermediates +# guarantees that original saved tensors could be deallocated. +# This config enables saved_tensors_hooks are applied for **all** saved tensors, +# that could include inputs, parameters, outputs. +# "donated" - applied only to saved intermediates of the graph +# "no_static" - applied to all saved but not "static" +# (this includes parameters and user marked as static) +# "all" - no filtering, everything saved for backward. +saved_tensors_hooks_filtering_mode = "donated" + + +# This callback is invoked on the joint graph before partitioning +joint_custom_pass: Callable = None # type: ignore[assignment] + +force_autograd_cache = False + +# Note [Selective Decomposition] +# This config allows selective decomposition of certain operators in the graph. +# When True, it does NOT decompose any nodes, 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. +selective_decompose: bool = False + +# Complex Support +# This config disallows decomposition of complex-valued Tensors using +# `torch._subclasses.complex_tensor.ComplexTensor` by decomposing everything into +# real-valued operations, passing through the regular pipeline as necessary, +# then converting back to a regular tensor. +enable_complex_wrapper: bool = False + + +if TYPE_CHECKING: + from torch.utils._config_typing import * # noqa: F403 + + +# adds patch, save_config, invalid config checks, etc +install_config_module(sys.modules[__name__]) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/deprecated.py b/.venv/lib/python3.12/site-packages/torch/_functorch/deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..0e66a55bb6cbe18feb8ad87a5b51ce1e38e22b2a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/deprecated.py @@ -0,0 +1,188 @@ +""" +The APIs in this file are exposed as `functorch.*`. They are thin wrappers +around the torch.func.* APIs that have deprecation warnings -- we're trying +to move people to the torch.func.* equivalents. + +NB: We don't use *args, **kwargs in the signatures because that changes the +documentation. +""" + +from __future__ import annotations + +import textwrap +import warnings +from typing import Any, TYPE_CHECKING + +import torch._functorch.apis as apis +import torch._functorch.eager_transforms as _impl +import torch._functorch.make_functional as _nn_impl +import torch.nn as nn + + +if TYPE_CHECKING: + from collections.abc import Callable + + from torch._functorch.eager_transforms import argnums_t + from torch._functorch.vmap import in_dims_t, out_dims_t + + +def get_warning( + api: str, new_api: str | None = None, replace_newlines: bool = False +) -> str: + if new_api is None: + new_api = f"torch.func.{api}" + warning = ( + f"We've integrated functorch into PyTorch. As the final step of the \n" + f"integration, `functorch.{api}` is deprecated as of PyTorch \n" + f"2.0 and will be deleted in a future version of PyTorch >= 2.3. \n" + f"Please use `{new_api}` instead; see the PyTorch 2.0 release notes \n" + f"and/or the `torch.func` migration guide for more details \n" + f"https://pytorch.org/docs/main/func.migrating.html" + ) + if replace_newlines: + warning = warning.replace("\n", "") + return warning + + +def warn_deprecated(api: str, new_api: str | None = None) -> None: + warning = get_warning(api, new_api, replace_newlines=True) + warnings.warn(warning, FutureWarning, stacklevel=3) + + +def setup_docs( + functorch_api: Callable[..., Any], + torch_func_api: Callable[..., Any] | None = None, + new_api_name: str | None = None, +) -> None: + api_name = functorch_api.__name__ + if torch_func_api is None: + torch_func_api = getattr(_impl, api_name) + # See https://docs.python.org/3/using/cmdline.html#cmdoption-OO + if torch_func_api.__doc__ is None: + return + + warning = get_warning(api_name, new_api_name) + warning_note = "\n.. warning::\n\n" + textwrap.indent(warning, " ") + warning_note = textwrap.indent(warning_note, " ") + functorch_api.__doc__ = torch_func_api.__doc__ + warning_note + + +def vmap( + func: Callable[..., Any], + in_dims: in_dims_t = 0, + out_dims: out_dims_t = 0, + randomness: str = "error", + *, + chunk_size: int | None = None, +) -> Callable[..., Any]: + warn_deprecated("vmap", "torch.vmap") + return apis.vmap(func, in_dims, out_dims, randomness, chunk_size=chunk_size) + + +def grad( + func: Callable[..., Any], argnums: argnums_t = 0, has_aux: bool = False +) -> Callable[..., Any]: + warn_deprecated("grad") + return apis.grad(func, argnums, has_aux) + + +def grad_and_value( + func: Callable[..., Any], argnums: argnums_t = 0, has_aux: bool = False +) -> Callable[..., Any]: + warn_deprecated("grad_and_value") + return apis.grad_and_value(func, argnums, has_aux) + + +def vjp(func: Callable[..., Any], *primals: Any, has_aux: bool = False) -> Any: + warn_deprecated("vjp") + return _impl.vjp(func, *primals, has_aux=has_aux) + + +def jvp( + func: Callable[..., Any], + primals: Any, + tangents: Any, + *, + strict: bool = False, + has_aux: bool = False, +) -> Any: + warn_deprecated("jvp") + return _impl.jvp(func, primals, tangents, strict=strict, has_aux=has_aux) + + +def jacrev( + func: Callable[..., Any], + argnums: int | tuple[int, ...] = 0, + *, + has_aux: bool = False, + chunk_size: int | None = None, + _preallocate_and_copy: bool = False, +) -> Callable[..., Any]: + warn_deprecated("jacrev") + return _impl.jacrev( + func, + argnums, + has_aux=has_aux, + chunk_size=chunk_size, + _preallocate_and_copy=_preallocate_and_copy, + ) + + +def jacfwd( + func: Callable[..., Any], + argnums: argnums_t = 0, + has_aux: bool = False, + *, + randomness: str = "error", +) -> Callable[..., Any]: + warn_deprecated("jacfwd") + return _impl.jacfwd(func, argnums, has_aux, randomness=randomness) + + +def hessian(func: Callable[..., Any], argnums: int = 0) -> Callable[..., Any]: + warn_deprecated("hessian") + return _impl.hessian(func, argnums=argnums) + + +def functionalize( + func: Callable[..., Any], *, remove: str = "mutations" +) -> Callable[..., Any]: + warn_deprecated("functionalize") + return _impl.functionalize(func, remove=remove) + + +def make_functional(model: nn.Module, disable_autograd_tracking: bool = False) -> Any: + warn_deprecated("make_functional", "torch.func.functional_call") + return _nn_impl.make_functional(model, disable_autograd_tracking) + + +def make_functional_with_buffers( + model: nn.Module, disable_autograd_tracking: bool = False +) -> Any: + warn_deprecated("make_functional_with_buffers", "torch.func.functional_call") + return _nn_impl.make_functional_with_buffers(model, disable_autograd_tracking) + + +def combine_state_for_ensemble(models: list[nn.Module]) -> Any: + warn_deprecated("combine_state_for_ensemble", "torch.func.stack_module_state") + return _nn_impl.combine_state_for_ensemble(models) + + +setup_docs(vmap, apis.vmap, "torch.vmap") +setup_docs(grad, apis.grad) +setup_docs(grad_and_value, apis.grad_and_value) +setup_docs(vjp) +setup_docs(jvp) +setup_docs(jacrev) +setup_docs(jacfwd) +setup_docs(hessian) +setup_docs(functionalize) +setup_docs(make_functional, _nn_impl.make_functional, "torch.func.functional_call") +setup_docs( + make_functional_with_buffers, _nn_impl.make_functional, "torch.func.functional_call" +) +setup_docs( + combine_state_for_ensemble, + _nn_impl.combine_state_for_ensemble, + "torch.func.stack_module_state", +) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/eager_transforms.py b/.venv/lib/python3.12/site-packages/torch/_functorch/eager_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..69b10bca1a51b35e28db79701c9e7d2e09bc1d13 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/eager_transforms.py @@ -0,0 +1,1960 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +import contextlib +from functools import partial +from typing import Any, overload, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +import torch +import torch.autograd.forward_ad as fwAD +from torch._C._functorch import ( + _assert_wrapped_functional, # type: ignore[attr-defined] + _func_decrement_nesting, # type: ignore[attr-defined] + _func_increment_nesting, # type: ignore[attr-defined] + _grad_decrement_nesting, + _grad_increment_nesting, + _propagate_functional_input_mutation, # type: ignore[attr-defined] + _unwrap_functional_tensor, + _wrap_for_grad, + _wrap_functional_tensor, + get_inplace_requires_grad_allowed, + get_unwrapped, + is_functorch_wrapped_tensor, + set_inplace_requires_grad_allowed, +) +from torch._functorch.predispatch import ( + _jvp_decrement_nesting, + _jvp_increment_nesting, + _unwrap_for_grad, +) +from torch._functorch.utils import argnums_t, exposed_in +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.fx.experimental import const_fold +from torch.fx.experimental.proxy_tensor import make_fx +from torch.utils import _pytree as pytree +from torch.utils._pytree import ( + tree_flatten, + tree_map, + tree_map_, + tree_map_only, + tree_unflatten, + treespec_pprint, +) + +from .apis import _wraps_without_dynamo_attrs, vmap +from .vmap import doesnt_support_saved_tensors_hooks, get_chunk_sizes + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, Sequence + + +_P = ParamSpec("_P") +_R = TypeVar("_R") +_T = TypeVar("_T") + + +def lazy_dynamo_disallow(func: Callable[_P, _R]) -> Callable[_P, _R]: + import torch._dynamo + + return torch._dynamo.disallow_in_graph(func) + + +@contextlib.contextmanager +def enable_inplace_requires_grad(enabled: bool) -> Generator[None, None, None]: + prev_state = get_inplace_requires_grad_allowed() + set_inplace_requires_grad_allowed(enabled) + try: + yield + finally: + set_inplace_requires_grad_allowed(prev_state) + + +def _set_tensor_requires_grad(x: torch.Tensor) -> torch.Tensor: + # avoid graph-break on x.requires_grad_() + # https://github.com/pytorch/pytorch/pull/110053 + return x.requires_grad_() + + +def _create_differentiable(inps: Any, level: int | None = None) -> Any: + def create_differentiable(x: torch.Tensor | Any) -> torch.Tensor: + if isinstance(x, torch.Tensor): + with enable_inplace_requires_grad(True): + return _set_tensor_requires_grad(x) + raise ValueError(f"Thing passed to transform API must be Tensor, got {type(x)}") + + return tree_map(create_differentiable, inps) + + +_Tensors = torch.Tensor | tuple[torch.Tensor, ...] +_TensorsT = TypeVar("_TensorsT", bound=_Tensors) +_TensorsU = TypeVar("_TensorsU", bound=_Tensors) + + +def _undo_create_differentiable(inps: _TensorsT, level: int | None = None) -> _TensorsT: + def unwrap_tensors(x: _TensorsU) -> _TensorsU: + if isinstance(x, torch.Tensor): + if level is None: + raise AssertionError("level must not be None when unwrapping tensors") + # pyrefly: ignore[bad-return] + return _unwrap_for_grad(x, level) + # TODO: Remove the following hack for namedtuples + if isinstance(x, tuple): + return tree_map(unwrap_tensors, tuple(x)) + + raise RuntimeError(f"Expected tensors, got unsupported type {type(x)}") + + return tree_map(unwrap_tensors, inps) + + +def _is_differentiable(maybe_tensor: object) -> bool: + if not isinstance(maybe_tensor, torch.Tensor): + return False + return maybe_tensor.requires_grad + + +def _any_differentiable( + tensor_or_tuple_of_tensors: _Tensors, +) -> bool: + flat_args, _ = tree_flatten(tensor_or_tuple_of_tensors) + return any(tuple(map(_is_differentiable, flat_args))) + + +def _wrap_tensor_for_grad(maybe_tensor: _T, level: int) -> _T: + if not isinstance(maybe_tensor, torch.Tensor): + return maybe_tensor + # pyrefly: ignore[bad-return] + return _wrap_for_grad(maybe_tensor, level) + + +def _wrap_all_tensors(tensor_pytree: _T, level: int) -> _T: + return tree_map(partial(_wrap_tensor_for_grad, level=level), tensor_pytree) + + +# TODO: this is more accurate - enable in 3.11 +# _Ts = TypeVarTuple("_Ts") +# @overload +# def _as_tuple(val: tuple[*_Ts]) -> tuple[*_Ts]: ... +@overload +def _as_tuple(val: tuple[_R, ...]) -> tuple[_R]: ... +@overload +def _as_tuple(val: _R) -> tuple[_R]: ... +def _as_tuple(val: object) -> object: + if isinstance(val, tuple): + return val + return (val,) + + +# Version of autograd.grad that handles outputs that don't depend on inputs + + +def _autograd_grad( + outputs: Sequence[torch.Tensor], + inputs: Sequence[torch.Tensor], + grad_outputs: Sequence[torch.Tensor] | None = None, + retain_graph: bool = False, + create_graph: bool = True, +) -> tuple[torch.Tensor, ...]: + if grad_outputs is None: + diff_outputs = tuple(out for out in outputs if out.requires_grad) + else: + result = tuple( + (out, go) for out, go in zip(outputs, grad_outputs) if out.requires_grad + ) + if len(result) == 0: + diff_outputs, grad_outputs = (), () + else: + diff_outputs, grad_outputs = zip(*result) + if len(diff_outputs) == 0: + return tuple(torch.zeros_like(inp) for inp in inputs) + with torch._dynamo.compiled_autograd._disable(): + grad_inputs = torch.autograd.grad( + diff_outputs, + inputs, + grad_outputs, + retain_graph=retain_graph, + create_graph=create_graph, + allow_unused=True, + ) + grad_inputs = tuple( + torch.zeros_like(inp) if gi is None else gi + for gi, inp in zip(grad_inputs, inputs) + ) + return grad_inputs + + +# NOTE [grad and vjp interaction with no_grad] +# +# def f(x): +# with torch.no_grad(): +# c = x ** 2 +# return x - c +# +# The thing to consider is if enable_grad is on/off before grad gets called. +# +# Case 1: enable_grad is on. +# grad(f)(x) +# In this case, `grad` should respect the inner torch.no_grad. +# +# Case 2: enable_grad is off +# with torch.no_grad(): +# grad(f)(x) +# In this case, `grad` should respect the inner torch.no_grad, but not the +# outer one. This is because `grad` is a "function transform": its result +# should not depend on the result of a context manager outside of `f`. +# +# This gives us the following desired behavior: +# - (nested) grad transforms must obey torch.no_grad inside them +# - (nested) grad transforms should not obey torch.no_grad outside them +# +# To achieve this behavior, upon entering grad/vjp: +# - we save the current ("previous") is_grad_enabled (*) +# - we unconditionally enable grad. +# +# Inside DynamicLayerBackFallback, when we're temporarily popping `grad` layer +# off the stack: +# - if grad_mode is disabled, then we do nothing. (there is a torch.no_grad +# active, all subsequent grad transforms must obey it). +# - if grad_mode is enabled, and the previous is_grad_enabled (*) is False, +# then we temporarily restore the previous `is_grad_enabled`. This is +# because we're crossing the boundary from a `grad` outside the +# no_grad to a `grad` inside the no_grad. +# +# NB: vjp has some interesting behavior because the vjp's Callable[..., Any] can be called +# under a different grad_mode than the forward computation... +# +# NB: forward-mode AD: forward-mode AD doesn't respect torch.no_grad, but +# it respects c10::AutoFwGradMode. We've implemented the same logic for +# our jvp transform (it will have special handling if FwGradMode is disabled). + + +# How do we increment and decrement the nesting? I don't think we can. +@exposed_in("torch.func") +def vjp( + func: Callable[..., Any], *primals: Any, has_aux: bool = False +) -> tuple[Any, Callable[..., Any]] | tuple[Any, Callable[..., Any], Any]: + """ + Standing for the vector-Jacobian product, returns a tuple containing the + results of ``func`` applied to ``primals`` and a function that, when + given ``cotangents``, computes the reverse-mode Jacobian of ``func`` with + respect to ``primals`` times ``cotangents``. + + Args: + func (Callable[..., Any]): A Python function that takes one or more arguments. Must + return one or more Tensors. + primals (Tensors): Positional arguments to ``func`` that must all be + Tensors. The returned function will also be computing the + derivative with respect to these arguments + has_aux (bool): Flag indicating that ``func`` returns a + ``(output, aux)`` tuple where the first element is the output of + the function to be differentiated and the second element is + other auxiliary objects that will not be differentiated. + Default: False. + + Returns: + Returns a ``(output, vjp_fn)`` tuple containing the output of ``func`` + applied to ``primals`` and a function that computes the vjp of + ``func`` with respect to all ``primals`` using the cotangents passed + to the returned function. If ``has_aux is True``, then instead returns a + ``(output, vjp_fn, aux)`` tuple. + The returned ``vjp_fn`` function will return a tuple of each VJP. + + When used in simple cases, :func:`vjp` behaves the same as :func:`grad` + + >>> x = torch.randn([5]) + >>> f = lambda x: x.sin().sum() + >>> (_, vjpfunc) = torch.func.vjp(f, x) + >>> grad = vjpfunc(torch.tensor(1.0))[0] + >>> assert torch.allclose(grad, torch.func.grad(f)(x)) + + However, :func:`vjp` can support functions with multiple outputs by + passing in the cotangents for each of the outputs + + >>> x = torch.randn([5]) + >>> f = lambda x: (x.sin(), x.cos()) + >>> (_, vjpfunc) = torch.func.vjp(f, x) + >>> vjps = vjpfunc((torch.ones([5]), torch.ones([5]))) + >>> assert torch.allclose(vjps[0], x.cos() + -x.sin()) + + :func:`vjp` can even support outputs being Python structs + + >>> x = torch.randn([5]) + >>> f = lambda x: {"first": x.sin(), "second": x.cos()} + >>> (_, vjpfunc) = torch.func.vjp(f, x) + >>> cotangents = {"first": torch.ones([5]), "second": torch.ones([5])} + >>> vjps = vjpfunc(cotangents) + >>> assert torch.allclose(vjps[0], x.cos() + -x.sin()) + + The function returned by :func:`vjp` will compute the partials with + respect to each of the ``primals`` + + >>> x, y = torch.randn([5, 4]), torch.randn([4, 5]) + >>> (_, vjpfunc) = torch.func.vjp(torch.matmul, x, y) + >>> cotangents = torch.randn([5, 5]) + >>> vjps = vjpfunc(cotangents) + >>> assert len(vjps) == 2 + >>> assert torch.allclose(vjps[0], torch.matmul(cotangents, y.transpose(0, 1))) + >>> assert torch.allclose(vjps[1], torch.matmul(x.transpose(0, 1), cotangents)) + + ``primals`` are the positional arguments for ``f``. All kwargs use their + default value + + >>> x = torch.randn([5]) + >>> def f(x, scale=4.): + >>> return x * scale + >>> + >>> (_, vjpfunc) = torch.func.vjp(f, x) + >>> vjps = vjpfunc(torch.ones_like(x)) + >>> assert torch.allclose(vjps[0], torch.full(x.shape, 4.0)) + + .. note:: + Using PyTorch ``torch.no_grad`` together with ``vjp``. + Case 1: Using ``torch.no_grad`` inside a function: + + >>> def f(x): + >>> with torch.no_grad(): + >>> c = x ** 2 + >>> return x - c + + In this case, ``vjp(f)(x)`` will respect the inner ``torch.no_grad``. + + Case 2: Using ``vjp`` inside ``torch.no_grad`` context manager: + + >>> # xdoctest: +SKIP(failing) + >>> with torch.no_grad(): + >>> vjp(f)(x) + + In this case, ``vjp`` will respect the inner ``torch.no_grad``, but not the + outer one. This is because ``vjp`` is a "function transform": its result + should not depend on the result of a context manager outside of ``f``. + """ + return _vjp_with_argnums(func, *primals, has_aux=has_aux) + + +@contextlib.contextmanager +def _disable_inference_mode() -> Generator[None, None, None]: + # Disable inference_mode without clobbering grad_mode / fw_grad_mode. + # torch.inference_mode(False) unconditionally sets grad_mode=True and + # fw_grad_mode=True; we save and restore those to avoid that. + # No-op when inference_mode is already off. + if not torch.is_inference_mode_enabled(): + yield + return + prev_grad = torch.is_grad_enabled() + prev_fw_grad = torch._C._is_fwd_grad_enabled() + with torch.inference_mode(False): + torch._C._set_grad_enabled(prev_grad) + torch._C._set_fwd_grad_enabled(prev_fw_grad) + yield + + +@contextlib.contextmanager +def grad_increment_nesting() -> Generator[int, None, None]: + try: + grad_level = _grad_increment_nesting() + yield grad_level + finally: + _grad_decrement_nesting() + + +def enter_jvp_nesting() -> int: + global JVP_NESTING + jvp_level = _jvp_increment_nesting() + JVP_NESTING += 1 + return jvp_level + + +def exit_jvp_nesting() -> None: + global JVP_NESTING + _jvp_decrement_nesting() + JVP_NESTING -= 1 + + +@contextlib.contextmanager +def jvp_increment_nesting() -> Generator[int, None, None]: + try: + yield enter_jvp_nesting() + finally: + exit_jvp_nesting() + + +@doesnt_support_saved_tensors_hooks +def _vjp_with_argnums( + func: Callable[..., Any], + *primals: Any, + argnums: argnums_t | None = None, + has_aux: bool = False, +) -> tuple[Any, Callable[..., Any]] | tuple[Any, Callable[..., Any], Any]: + # This is the same function as vjp but also accepts an argnums argument + # All args are the same as vjp except for the added argument + # argnums (int or tuple[int,...] | None): Optional, specifies the argument(s) to compute gradients with respect to. + # If None, computes the gradients with respect to all inputs (used for vjp). Default: None + # + # WARN: Users should NOT call this function directly and should just be calling vjp. + # It is only separated so that inputs passed to jacrev but not differentiated get the correct wrappers. + # + # NOTE: All error messages are produced as if vjp was being called, even if this was called by jacrev + # + # Returns the same two elements as :func:`vjp` but the function returned, vjp_fn, returns a tuple of VJPs + # for only the primal elements given by argnums. + with grad_increment_nesting() as level: + # See NOTE [grad and vjp interaction with no_grad] + with torch.enable_grad(): + primals = _wrap_all_tensors(primals, level) + if argnums is None: + diff_primals = _create_differentiable(primals, level) + else: + diff_primals = _slice_argnums(primals, argnums, as_tuple=False) + tree_map_(partial(_create_differentiable, level=level), diff_primals) + primals_out = func(*primals) + + aux: Any = None + if has_aux: + if not (isinstance(primals_out, tuple) and len(primals_out) == 2): + raise RuntimeError( + "vjp(f, *primals): output of function f should be a tuple: (output, aux) " + "if has_aux is True" + ) + primals_out, aux = primals_out + aux = _undo_create_differentiable(aux, level) + + flat_primals_out, primals_out_spec = tree_flatten(primals_out) + assert_non_empty_tensor_output(flat_primals_out, "vjp(f, *primals)") + flat_diff_primals, primals_spec = tree_flatten(diff_primals) + results = _undo_create_differentiable(primals_out, level) + + for primal_out in flat_primals_out: + if not isinstance(primal_out, torch.Tensor): + raise AssertionError( + f"expected primal_out to be a Tensor, got {type(primal_out)}" + ) + if primal_out.is_floating_point() or primal_out.is_complex(): + continue + raise RuntimeError( + "vjp(f, ...): All outputs of f must be " + "floating-point or complex Tensors, got Tensor " + f"with dtype {primal_out.dtype}" + ) + + def wrapper( + cotangents: Any, + retain_graph: bool = True, + create_graph: bool | None = None, + ) -> Any: + if create_graph is None: + create_graph = torch.is_grad_enabled() + flat_cotangents, cotangents_spec = tree_flatten(cotangents) + if primals_out_spec != cotangents_spec: + raise RuntimeError( + f"Expected pytree structure of cotangents to be the same " + f"as pytree structure of outputs to the function. " + f"cotangents: {treespec_pprint(cotangents_spec)}, " + f"primal output: {treespec_pprint(primals_out_spec)}" + ) + # This closure runs after grad_increment_nesting exits, so + # inference_mode may have been restored. Disable it for autograd. + # Skip under Dynamo — tracing through the generator CM emits + # spurious _enter_inference_mode nodes. + ctx = ( + contextlib.nullcontext() + if torch.compiler.is_compiling() + else _disable_inference_mode() + ) + with ctx: + result = _autograd_grad( + flat_primals_out, + flat_diff_primals, + flat_cotangents, + retain_graph=retain_graph, + create_graph=create_graph, + ) + return tree_unflatten(result, primals_spec) + + if has_aux: + return results, wrapper, aux # type: ignore[possibly-unbound] + else: + return results, wrapper + + +def _safe_zero_index(x: tuple[_R, ...]) -> _R: + if len(x) != 1: + raise AssertionError(f"expected tuple of length 1, got length {len(x)}") + return x[0] + + +# jacrev and jacfwd don't support complex functions +# Helper function to throw appropriate error. +def error_if_complex(func_name: str, args: Any, is_input: bool) -> None: + flat_args = pytree.tree_leaves(args) + for idx, arg in enumerate(flat_args): + if isinstance(arg, torch.Tensor) and arg.dtype.is_complex: + input_or_output = "inputs" if is_input else "outputs" + err_msg = ( + f"{func_name}: Expected all {input_or_output} " + f"to be real but received complex tensor at flattened input idx: {idx}" + ) + raise RuntimeError(err_msg) + + +@exposed_in("torch.func") +def jacrev( + func: Callable[..., Any], + argnums: int | tuple[int, ...] = 0, + *, + has_aux: bool = False, + chunk_size: int | None = None, + _preallocate_and_copy: bool = False, +) -> Callable[..., Any]: + """ + Computes the Jacobian of ``func`` with respect to the arg(s) at index + ``argnum`` using reverse mode autodiff + + .. note:: + Using :attr:`chunk_size=1` is equivalent to computing the jacobian + row-by-row with a for-loop i.e. the constraints of :func:`vmap` are + not applicable. + + Args: + func (function): A Python function that takes one or more arguments, + one of which must be a Tensor, and returns one or more Tensors + argnums (int or tuple[int, ...]): Optional, integer or tuple of integers, + saying which arguments to get the Jacobian with respect to. + Default: 0. + has_aux (bool): Flag indicating that ``func`` returns a + ``(output, aux)`` tuple where the first element is the output of + the function to be differentiated and the second element is + auxiliary objects that will not be differentiated. + Default: False. + chunk_size (None or int): If None (default), use the maximum chunk size + (equivalent to doing a single vmap over vjp to compute the jacobian). + If 1, then compute the jacobian row-by-row with a for-loop. + If not None, then compute the jacobian :attr:`chunk_size` rows at a time + (equivalent to doing multiple vmap over vjp). If you run into memory issues computing + the jacobian, please try to specify a non-None chunk_size. + + Returns: + Returns a function that takes in the same inputs as ``func`` and + returns the Jacobian of ``func`` with respect to the arg(s) at + ``argnums``. If ``has_aux is True``, then the returned function + instead returns a ``(jacobian, aux)`` tuple where ``jacobian`` + is the Jacobian and ``aux`` is auxiliary objects returned by ``func``. + + A basic usage with a pointwise, unary operation will give a diagonal array + as the Jacobian + + >>> from torch.func import jacrev + >>> x = torch.randn(5) + >>> jacobian = jacrev(torch.sin)(x) + >>> expected = torch.diag(torch.cos(x)) + >>> assert torch.allclose(jacobian, expected) + + If you would like to compute the output of the function as well as the + jacobian of the function, use the ``has_aux`` flag to return the output + as an auxiliary object: + + >>> from torch.func import jacrev + >>> x = torch.randn(5) + >>> + >>> def f(x): + >>> return x.sin() + >>> + >>> def g(x): + >>> result = f(x) + >>> return result, result + >>> + >>> jacobian_f, f_x = jacrev(g, has_aux=True)(x) + >>> assert torch.allclose(f_x, f(x)) + + :func:`jacrev` can be composed with vmap to produce batched + Jacobians: + + >>> from torch.func import jacrev, vmap + >>> x = torch.randn(64, 5) + >>> jacobian = vmap(jacrev(torch.sin))(x) + >>> assert jacobian.shape == (64, 5, 5) + + Additionally, :func:`jacrev` can be composed with itself to produce + Hessians + + >>> from torch.func import jacrev + >>> def f(x): + >>> return x.sin().sum() + >>> + >>> x = torch.randn(5) + >>> hessian = jacrev(jacrev(f))(x) + >>> assert torch.allclose(hessian, torch.diag(-x.sin())) + + By default, :func:`jacrev` computes the Jacobian with respect to the first + input. However, it can compute the Jacobian with respect to a different + argument by using ``argnums``: + + >>> from torch.func import jacrev + >>> def f(x, y): + >>> return x + y ** 2 + >>> + >>> x, y = torch.randn(5), torch.randn(5) + >>> jacobian = jacrev(f, argnums=1)(x, y) + >>> expected = torch.diag(2 * y) + >>> assert torch.allclose(jacobian, expected) + + Additionally, passing a tuple to ``argnums`` will compute the Jacobian + with respect to multiple arguments + + >>> from torch.func import jacrev + >>> def f(x, y): + >>> return x + y ** 2 + >>> + >>> x, y = torch.randn(5), torch.randn(5) + >>> jacobian = jacrev(f, argnums=(0, 1))(x, y) + >>> expectedX = torch.diag(torch.ones_like(x)) + >>> expectedY = torch.diag(2 * y) + >>> assert torch.allclose(jacobian[0], expectedX) + >>> assert torch.allclose(jacobian[1], expectedY) + + .. note:: + Using PyTorch ``torch.no_grad`` together with ``jacrev``. + Case 1: Using ``torch.no_grad`` inside a function: + + >>> def f(x): + >>> with torch.no_grad(): + >>> c = x ** 2 + >>> return x - c + + In this case, ``jacrev(f)(x)`` will respect the inner ``torch.no_grad``. + + Case 2: Using ``jacrev`` inside ``torch.no_grad`` context manager: + + >>> with torch.no_grad(): + >>> jacrev(f)(x) + + In this case, ``jacrev`` will respect the inner ``torch.no_grad``, but not the + outer one. This is because ``jacrev`` is a "function transform": its result + should not depend on the result of a context manager outside of ``f``. + """ + if not (chunk_size is None or chunk_size > 0): + raise ValueError("jacrev: `chunk_size` should be greater than 0.") + + @_wraps_without_dynamo_attrs(func) + def wrapper_fn(*args: Any) -> Any: + error_if_complex("jacrev", args, is_input=True) + vjp_out = _vjp_with_argnums(func, *args, argnums=argnums, has_aux=has_aux) + aux: Any = None + if has_aux: + # pyrefly: ignore[bad-unpacking] + output, vjp_fn, aux = vjp_out + else: + # pyrefly: ignore[bad-unpacking] + output, vjp_fn = vjp_out + + # See NOTE: [Computing jacobian with vmap and vjp for multiple outputs] + flat_output, output_spec = tree_flatten(output) + + error_if_complex("jacrev", flat_output, is_input=False) + + # NB: vjp already checks that all outputs are tensors + # Step 1: Construct grad_outputs by splitting the standard basis + flat_output_numels = tuple(out.numel() for out in flat_output) + + primals = _slice_argnums(args, argnums) + flat_primals, primals_spec = tree_flatten(primals) + + def compute_jacobian_stacked() -> list[Any]: + # Helper function to compute chunked Jacobian + # The intermediate chunked calculation are only + # scoped at this function level. + chunked_results: list[list[Any]] = [] + for flat_basis_chunk in _chunked_standard_basis_for_( + flat_output, flat_output_numels, chunk_size=chunk_size + ): + if chunk_size == 1: + # sanity check. + for t in flat_basis_chunk: + if t.size(0) != 1: + raise AssertionError( + f"expected t.size(0) to be 1, got {t.size(0)}" + ) + + flat_basis_chunk = tree_map( + lambda t: torch.squeeze(t, 0), flat_basis_chunk + ) + + basis = tree_unflatten(flat_basis_chunk, output_spec) + + if chunk_size == 1: + # Behaviour with `chunk_size=1` is same as `for-loop` + # i.e. user shouldn't deal with the limitations of vmap. + chunked_result = vjp_fn(basis) + else: # chunk_size is None or chunk_size != 1 + chunked_result = vmap(vjp_fn)(basis) + + flat_results = pytree.tree_leaves(chunked_result) + + if chunk_size == 1: + flat_results = tree_map( + lambda t: torch.unsqueeze(t, 0), flat_results + ) + + chunked_results.append(flat_results) + + if len(chunked_results) == 1: + # Short-circuit if we used a single chunk + return chunked_results[0] + + # Concatenate chunks. + flat_results = [] + # Iterate and concat the jacobians of different + # inputs. + for idx in range(len(flat_primals)): + r = tuple(r_[idx] for r_ in chunked_results) + flat_results.append(torch.cat(r, 0)) + + return flat_results + + def compute_jacobian_preallocate_and_copy() -> list[Any]: + # Helper function to compute chunked Jacobian + # The intermediate chunked calculation are only + # scoped at this function level. + out_vec_size = sum(flat_output_numels) + + # Don't pre-allocate if we have a single chunk. + stacked_results: list[torch.Tensor] = [] + if not (chunk_size is None or chunk_size >= out_vec_size): + stacked_results = [ + primal.new_zeros(out_vec_size, *primal.shape) + for primal in flat_primals + ] + + for idx, flat_basis_chunk in enumerate( + _chunked_standard_basis_for_( + flat_output, flat_output_numels, chunk_size=chunk_size + ) + ): + if chunk_size == 1: + # sanity check. + for t in flat_basis_chunk: + if t.size(0) != 1: + raise AssertionError( + f"expected t.size(0) to be 1, got {t.size(0)}" + ) + + flat_basis_chunk = [torch.squeeze(t, 0) for t in flat_basis_chunk] + + basis = tree_unflatten(flat_basis_chunk, output_spec) + + if chunk_size == 1: + # Behaviour with `chunk_size=1` is same as `for-loop` + # i.e. user shouldn't deal with the limitations of vmap. + chunked_result = vjp_fn(basis) + else: # chunk_size is None or chunk_size != 1 + chunked_result = vmap(vjp_fn)(basis) + + flat_results = pytree.tree_leaves(chunked_result) + + # Short-circuit if we have a single chunk. + if chunk_size is None or chunk_size >= out_vec_size: + if chunk_size == 1: # and out_vec_size == 1 + # Since we squeezed the output dim + flat_results = tree_map( + lambda t: torch.unsqueeze(t, 0), flat_results + ) + return flat_results + + for r, sr in zip(flat_results, stacked_results): # type: ignore[possibly-unbound] + sr[idx * chunk_size : (idx + 1) * chunk_size].copy_(r) + + return stacked_results # type: ignore[possibly-unbound] + + if _preallocate_and_copy: + flat_jacobians_per_input = compute_jacobian_preallocate_and_copy() + else: + flat_jacobians_per_input = compute_jacobian_stacked() + + # Step 2: The returned jacobian is one big tensor per input. In this step, + # we split each Tensor by output. + flat_jacobians_per_input = [ + torch.split(result, list(flat_output_numels), dim=0) + for result in flat_jacobians_per_input + ] + flat_input_flat_output = [ + tuple( + split.view(out.shape + primal.shape) + for split, out in zip(splits, flat_output) + ) + for splits, primal in zip(flat_jacobians_per_input, flat_primals) + ] + + # Step 3: Right now, `jacobian` is a List[List[Tensor]]. + # The outer List corresponds to the number of primals, + # the inner List corresponds to the number of outputs. + # We need to: + # a. Exchange the order of the outer List and inner List + # b. tree_unflatten the inner Lists (which correspond to the primals) + # c. handle the argnums=int case + # d. tree_unflatten the outer List (which corresponds to the outputs) + flat_output_flat_input = tuple(zip(*flat_input_flat_output)) + + flat_output_input = tuple( + tree_unflatten(flat_input, primals_spec) + for flat_input in flat_output_flat_input + ) + + if isinstance(argnums, int): + flat_output_input = tuple( + _safe_zero_index(flat_input) for flat_input in flat_output_input + ) + output_input = tree_unflatten(flat_output_input, output_spec) + if has_aux: + return output_input, aux # type: ignore[possibly-unbound] + return output_input + + return wrapper_fn + + +# NOTE: [Computing jacobian with vmap and vjp for multiple outputs] +# +# Let's consider f(x) = (x**2, x.sum()) and let x = torch.randn(3). +# It turns out we can compute the jacobian of this function with a single +# call to autograd.grad by using vmap over the correct grad_outputs. +# +# Firstly, one way to compute the jacobian is to stack x**2 and x.sum() +# into a 4D vector. E.g., use g(x) = torch.stack([x**2, x.sum()]) +# +# To get the first row of the jacobian, we call +# >>> autograd.grad(g(x), x, grad_outputs=torch.tensor([1, 0, 0, 0])) +# To get the 2nd row of the jacobian, we call +# >>> autograd.grad(g(x), x, grad_outputs=torch.tensor([0, 1, 0, 0])) +# and so on. +# +# Using vmap, we can vectorize all 4 of these computations into one by +# passing the standard basis for R^4 as the grad_output. +# vmap(partial(autograd.grad, g(x), x))(torch.eye(4)). +# +# Now, how do we compute the jacobian *without stacking the output*? +# We can just split the standard basis across the outputs. So to +# compute the jacobian of f(x), we'd use +# >>> autograd.grad(f(x), x, grad_outputs=_construct_standard_basis_for(...)) +# The grad_outputs looks like the following: +# ( torch.tensor([[1, 0, 0], +# [0, 1, 0], +# [0, 0, 1], +# [0, 0, 0]]), +# torch.tensor([[0], +# [0], +# [0], +# [1]]) ) +# +# But we're not done yet! +# >>> vmap(partial(autograd.grad(f(x), x, grad_outputs=...))) +# returns a Tensor of shape [4, 3]. We have to remember to split the +# jacobian of shape [4, 3] into two: +# - one of shape [3, 3] for the first output +# - one of shape [ 3] for the second output + + +def _chunked_standard_basis_for_( + tensors: Sequence[torch.Tensor], + tensor_numels: Sequence[int], + chunk_size: int | None = None, +) -> Generator[tuple[torch.Tensor, ...], None, None]: + # This function: + # - constructs a N=sum(tensor_numels) standard basis. i.e. an NxN identity matrix. + # - Splits the identity matrix into chunks with each chunk size determined by `tensor_numels`. + # - Each chunk corresponds to one tensor. The chunk has the same dtype and + # device as the tensor + # + # For example, with tensor_numels = [1, 2, 1], this function returns: + # ( tensor([[1], tensor([[0, 0], tensor([[0], + # [0], [1, 0], [0], + # [0], [0, 1], [0], + # [0]]) , [0, 0]]) , [1]]) ) + # + # Precondition: tensor_numels == tuple(tensor.numel() for tensor in tensors) + # Precondition: tensors always has at least one element. + # + # See NOTE: [Computing jacobian with vmap and grad for multiple tensors] + # for context behind this function. + # NOTE: Argument `chunk_size` is used to generate chunked basis instead of + # one huge basis matrix. `chunk_size` dictates the maximum size of the + # basis matrix along dim=0. + if len(tensors) != len(tensor_numels): + raise AssertionError( + f"len(tensors)={len(tensors)} != len(tensor_numels)={len(tensor_numels)}" + ) + if len(tensors) == 0: + raise AssertionError("tensors must have at least one element") + if chunk_size is not None and chunk_size <= 0: + raise AssertionError(f"chunk_size must be > 0 or None, got {chunk_size}") + total_numel = sum(tensor_numels) + if chunk_size and chunk_size < total_numel: + chunk_numels = get_chunk_sizes(total_numel, chunk_size) + else: # chunk_size is None or chunk_size >= total_numel + chunk_size = total_numel + chunk_numels = [total_numel] + + diag_start_indices = [] + diag_start_idx = 0 + for tensor_numel in tensor_numels: + diag_start_indices.append(diag_start_idx) + diag_start_idx -= tensor_numel + + for chunk_idx, total_numel in enumerate(chunk_numels): + chunks = tuple( + tensor.new_zeros(total_numel, tensor_numel) + for tensor, tensor_numel in zip(tensors, tensor_numels) + ) + + for chunk, diag_start_idx in zip(chunks, diag_start_indices): + offset = int(diag_start_idx) + chunk_idx * chunk_size + chunk.diagonal(offset).fill_(1) + chunks = tuple( + chunk.view(total_numel, *tensor.shape) + for chunk, tensor in zip(chunks, tensors) + ) + yield chunks + + +def _construct_standard_basis_for( + tensors: Sequence[torch.Tensor], tensor_numels: Sequence[int] +) -> tuple[torch.Tensor, ...] | None: + for basis in _chunked_standard_basis_for_(tensors, tensor_numels, chunk_size=None): + return basis + return None + + +def _validate_and_wrap_argnum(argnum: int, num_args: int) -> int: + if not isinstance(argnum, int): + raise RuntimeError(f"argnum must be int, got: {type(argnum)}") + if argnum >= 0 and argnum < num_args: + return argnum + if argnum < 0 and argnum >= -num_args: + return argnum + num_args + raise RuntimeError(f"Got argnum={argnum}, but only {num_args} positional inputs") + + +def _check_unique_non_empty(argnums: argnums_t) -> None: + if isinstance(argnums, tuple): + if len(argnums) == 0: + raise RuntimeError("argnums must be non-empty") + if len(set(argnums)) != len(argnums): + raise RuntimeError(f"argnums elements must be unique, got {argnums}") + + +def _replace_args( + old_args: tuple[Any, ...], new_args: tuple[Any, ...], argnums: argnums_t +) -> tuple[Any, ...]: + if isinstance(argnums, int): + if len(new_args) != 1: + raise RuntimeError( + f"new_args should be of size 1, was of size {len(new_args)}" + ) + return tuple( + new_args[0] if i == argnums else old_args[i] for i in range(len(old_args)) + ) + if isinstance(argnums, tuple): + if len(new_args) != len(argnums): + raise RuntimeError( + "new_args should have the same size as argnums. " + f"Argnums size {len(argnums)}, new_args size {len(new_args)}" + ) + + argnums_tuple = argnums + + def get_right_elem(i: int) -> Any: + return ( + new_args[argnums_tuple.index(i)] if i in argnums_tuple else old_args[i] + ) + + return tuple(get_right_elem(i) for i in range(len(old_args))) + raise RuntimeError(f"argnums must be int or Tuple[int, ...], got: {type(argnums)}") + + +def _validate_and_wrap_argnums(argnums: argnums_t, num_args: int) -> argnums_t: + if isinstance(argnums, int): + return _validate_and_wrap_argnum(argnums, num_args) + if isinstance(argnums, tuple): + return tuple(_validate_and_wrap_argnum(argnum, num_args) for argnum in argnums) + raise AssertionError("Should never get here") + + +def _slice_argnums( + args: tuple[Any, ...], argnums: argnums_t, as_tuple: bool = True +) -> Any: + if not isinstance(argnums, int) and not isinstance(argnums, tuple): + raise RuntimeError( + f"argnums must be int or Tuple[int, ...], got: {type(argnums)}" + ) + argnums = _validate_and_wrap_argnums(argnums, len(args)) + _check_unique_non_empty(argnums) + if isinstance(argnums, int): + if as_tuple: + return (args[argnums],) + else: + return args[argnums] + return tuple(args[i] for i in argnums) + + +JVP_NESTING = 0 + + +def assert_flat_tuple_of_tensors(elts: Any, api: str, argname: str) -> None: + if not isinstance(elts, tuple): + raise RuntimeError( + f"{api}: Expected {argname} to be a tuple of Tensors, got {type(elts)}" + ) + for elt in elts: + if isinstance(elt, torch.Tensor): + continue + raise RuntimeError( + f"{api}: Expected {argname} to be a tuple of Tensors, got " + f"a tuple with an element of type {type(elt)}" + ) + if len(elts) == 0: + raise RuntimeError( + f"{api}: Expected {argname} to be a non-empty tuple of Tensors." + ) + + +def assert_non_empty_tensor_output(output: list[Any], api: str) -> None: + if (len(output) == 1 and output[0] is None) or len(output) < 1: + raise RuntimeError( + f"{api}: Expected f to be a function that has non-empty output (got output = {output})" + ) + for o in output: + if not isinstance(o, torch.Tensor): + raise RuntimeError( + f"{api}: expected f(*primals) to return only tensors" + f", got unsupported type {type(o)}" + ) + + +def assert_output_is_tensor_or_tensors(output: Any, api: str) -> None: + if isinstance(output, torch.Tensor): + return + if not isinstance(output, tuple): + raise RuntimeError( + f"{api}: Expected output of f to be a Tensor or Tensors, got {type(output)}" + ) + if len(output) == 0: + raise RuntimeError( + f"{api}: Expected output of f to be a non-empty tuple of Tensors." + ) + for out in output: + if isinstance(out, torch.Tensor): + continue + raise RuntimeError( + f"{api}: Expected output of f to be a Tensor or Tensors, got " + f"{type(out)} as an output" + ) + + +def assert_non_empty_list_of_tensors( + output: list[torch.Tensor], api: str, argname: str +) -> None: + if len(output) == 0: + raise RuntimeError(f"{api}: Expected {argname} to contain at least one Tensor.") + for out in output: + if isinstance(out, torch.Tensor): + continue + raise RuntimeError( + f"{api}: Expected {argname} to only contain Tensors, got {type(out)}" + ) + + +jvp_str = "jvp(f, primals, tangents)" + + +def safe_unpack_dual( + dual: torch.Tensor, strict: bool +) -> tuple[torch.Tensor, torch.Tensor]: + if not isinstance(dual, torch.Tensor): + raise RuntimeError( + f"{jvp_str}: expected f(*args) to return only tensors" + f", got unsupported type {type(dual)}" + ) + + primal, tangent = fwAD.unpack_dual(dual) + if tangent is None: + if strict: + raise RuntimeError( + "jvp(f, primals, tangents, strict=True): " + "The output of f is independent of " + "the inputs. This is not allowed with strict=True." + ) + tangent = torch.zeros_like(primal) + return primal, tangent + + +@exposed_in("torch.func") +def jvp( + func: Callable[..., Any], + primals: Any, + tangents: Any, + *, + strict: bool = False, + has_aux: bool = False, +) -> tuple[Any, Any] | tuple[Any, Any, Any]: + """ + Standing for the Jacobian-vector product, returns a tuple containing + the output of `func(*primals)` and the "Jacobian of ``func`` evaluated at + ``primals``" times ``tangents``. This is also known as forward-mode autodiff. + + Args: + func (function): A Python function that takes one or more arguments, + one of which must be a Tensor, and returns one or more Tensors + primals (Tensors): Positional arguments to ``func`` that must all be + Tensors. The returned function will also be computing the + derivative with respect to these arguments + tangents (Tensors): The "vector" for which Jacobian-vector-product is + computed. Must be the same structure and sizes as the inputs to + ``func``. + has_aux (bool): Flag indicating that ``func`` returns a + ``(output, aux)`` tuple where the first element is the output of + the function to be differentiated and the second element is + other auxiliary objects that will not be differentiated. + Default: False. + + Returns: + Returns a ``(output, jvp_out)`` tuple containing the output of ``func`` + evaluated at ``primals`` and the Jacobian-vector product. + If ``has_aux is True``, then instead returns a ``(output, jvp_out, aux)`` tuple. + + .. note:: + You may see this API error out with "forward-mode AD not implemented + for operator X". If so, please file a bug report and we will prioritize it. + + jvp is useful when you wish to compute gradients of a function R^1 -> R^N + + >>> from torch.func import jvp + >>> x = torch.randn([]) + >>> f = lambda x: x * torch.tensor([1.0, 2.0, 3]) + >>> warnings.filterwarnings( + ... "ignore", message=".*torch.jit.script" + ... ) # docs: hide + >>> value, grad = jvp(f, (x,), (torch.tensor(1.0),)) + >>> assert torch.allclose(value, f(x)) + >>> assert torch.allclose(grad, torch.tensor([1.0, 2, 3])) + + :func:`jvp` can support functions with multiple inputs by passing in the + tangents for each of the inputs + + >>> from torch.func import jvp + >>> x = torch.randn(5) + >>> y = torch.randn(5) + >>> f = lambda x, y: (x * y) + >>> _, output = jvp(f, (x, y), (torch.ones(5), torch.ones(5))) + >>> assert torch.allclose(output, x + y) + + """ + + return _jvp_with_argnums( + func, primals, tangents, argnums=None, strict=strict, has_aux=has_aux + ) + + +def _jvp_with_argnums( + func: Callable[..., Any], + primals: Any, + tangents: Any, + argnums: argnums_t | None, + *, + strict: bool = False, + has_aux: bool, +) -> tuple[Any, Any] | tuple[Any, Any, Any]: + # This is the same function as jvp but also accepts an argnums argument + # Most args are the same as jvp except for the added argument + # argnums (int or tuple[int, ...]): Optional, specifies the argument(s) to compute gradients with respect to. + # If None, computes the gradients with respect to all inputs (used for jvp). Default: None + # Because of this, tangents must be of length argnums and matches up to the corresponding primal whose index is + # given by argnums + # + # WARN: Users should NOT call this function directly and should just be calling jvp. + # It is only separated so that inputs passed to jacfwd but not differentiated get the correct wrappers. + # + # NOTE: All error messages are produced as if jvp was being called, even if this was called by jacfwd + # + # Returns the same two elements as :func:`jvp` but the returned tuple, ``jvp_out``, only has JVPs with respect to + # the primals given by argnums + if not isinstance(primals, tuple): + raise RuntimeError( + f"{jvp_str}: Expected primals to be a tuple. " + f"E.g. it should be valid to call f(*primals)." + ) + diff_args = primals if argnums is None else _slice_argnums(primals, argnums) + flat_primals, primals_spec = tree_flatten(diff_args) + flat_tangents, tangents_spec = tree_flatten(tangents) + if primals_spec != tangents_spec: + raise RuntimeError( + f"{jvp_str}: Expected primals and tangents to have the same python " + f"structure. For example, if primals is a tuple of 3 tensors, " + f"tangents also must be. Got primals with structure {primals_spec} " + f"and tangents with structure {tangents_spec}" + ) + assert_non_empty_list_of_tensors(flat_primals, jvp_str, "primals") + assert_non_empty_list_of_tensors(flat_tangents, jvp_str, "tangents") + + global JVP_NESTING + + with jvp_increment_nesting() as level: + with fwAD._set_fwd_grad_enabled(True): + ctx = fwAD.dual_level if JVP_NESTING == 1 else contextlib.nullcontext + with ctx(): + flat_duals = tuple( + fwAD.make_dual(p, t) for p, t in zip(flat_primals, flat_tangents) + ) + duals = tree_unflatten(flat_duals, primals_spec) + if argnums is not None: + primals = _wrap_all_tensors(primals, level) + duals = _replace_args(primals, duals, argnums) + result_duals = func(*duals) + aux: Any = None + if has_aux: + if not (isinstance(result_duals, tuple) and len(result_duals) == 2): + raise RuntimeError( + f"{jvp_str}: output of function f should be a tuple: (output, aux) " + "if has_aux is True" + ) + result_duals, aux = result_duals + aux = _undo_create_differentiable(aux, level) + + result_duals, spec = tree_flatten(result_duals) + assert_non_empty_tensor_output(result_duals, jvp_str) + + primals_out, tangents_out = zip( + *[safe_unpack_dual(dual, strict) for dual in result_duals] + ) + primals_out = tree_map( + partial(_undo_create_differentiable, level=level), primals_out + ) + tangents_out = tree_map( + partial(_undo_create_differentiable, level=level), tangents_out + ) + + primals_out_unflatten = tree_unflatten(primals_out, spec) + tangents_out_unflatten = tree_unflatten(tangents_out, spec) + if has_aux: + return primals_out_unflatten, tangents_out_unflatten, aux # type: ignore[possibly-unbound] + + return primals_out_unflatten, tangents_out_unflatten + + +def safe_unflatten(tensor: torch.Tensor, dim: int, shape: torch.Size) -> torch.Tensor: + if len(shape) == 0: + if tensor.shape[dim] != 1: + raise AssertionError( + f"expected tensor.shape[{dim}] to be 1, got {tensor.shape[dim]}" + ) + return tensor.squeeze(dim) + return tensor.unflatten(dim, shape) + + +@exposed_in("torch.func") +def jacfwd( + func: Callable[..., Any], + argnums: argnums_t = 0, + has_aux: bool = False, + *, + randomness: str = "error", +) -> Callable[..., Any]: + """ + Computes the Jacobian of ``func`` with respect to the arg(s) at index + ``argnum`` using forward-mode autodiff + + Args: + func (function): A Python function that takes one or more arguments, + one of which must be a Tensor, and returns one or more Tensors + argnums (int or tuple[int, ...]): Optional, integer or tuple of integers, + saying which arguments to get the Jacobian with respect to. + Default: 0. + has_aux (bool): Flag indicating that ``func`` returns a + ``(output, aux)`` tuple where the first element is the output of + the function to be differentiated and the second element is + auxiliary objects that will not be differentiated. + Default: False. + randomness(str): Flag indicating what type of randomness to use. + See :func:`vmap` for more detail. Allowed: "different", "same", "error". + Default: "error" + + Returns: + Returns a function that takes in the same inputs as ``func`` and + returns the Jacobian of ``func`` with respect to the arg(s) at + ``argnums``. If ``has_aux is True``, then the returned function + instead returns a ``(jacobian, aux)`` tuple where ``jacobian`` + is the Jacobian and ``aux`` is auxiliary objects returned by ``func``. + + .. note:: + You may see this API error out with "forward-mode AD not implemented + for operator X". If so, please file a bug report and we will prioritize it. + An alternative is to use :func:`jacrev`, which has better operator coverage. + + A basic usage with a pointwise, unary operation will give a diagonal array + as the Jacobian + + >>> from torch.func import jacfwd + >>> x = torch.randn(5) + >>> jacobian = jacfwd(torch.sin)(x) + >>> expected = torch.diag(torch.cos(x)) + >>> assert torch.allclose(jacobian, expected) + + :func:`jacfwd` can be composed with vmap to produce batched + Jacobians: + + >>> from torch.func import jacfwd, vmap + >>> x = torch.randn(64, 5) + >>> jacobian = vmap(jacfwd(torch.sin))(x) + >>> assert jacobian.shape == (64, 5, 5) + + If you would like to compute the output of the function as well as the + jacobian of the function, use the ``has_aux`` flag to return the output + as an auxiliary object: + + >>> from torch.func import jacfwd + >>> x = torch.randn(5) + >>> + >>> def f(x): + >>> return x.sin() + >>> + >>> def g(x): + >>> result = f(x) + >>> return result, result + >>> + >>> jacobian_f, f_x = jacfwd(g, has_aux=True)(x) + >>> assert torch.allclose(f_x, f(x)) + + Additionally, :func:`jacrev` can be composed with itself or :func:`jacrev` + to produce Hessians + + >>> from torch.func import jacfwd, jacrev + >>> def f(x): + >>> return x.sin().sum() + >>> + >>> x = torch.randn(5) + >>> hessian = jacfwd(jacrev(f))(x) + >>> assert torch.allclose(hessian, torch.diag(-x.sin())) + + By default, :func:`jacfwd` computes the Jacobian with respect to the first + input. However, it can compute the Jacobian with respect to a different + argument by using ``argnums``: + + >>> from torch.func import jacfwd + >>> def f(x, y): + >>> return x + y ** 2 + >>> + >>> x, y = torch.randn(5), torch.randn(5) + >>> jacobian = jacfwd(f, argnums=1)(x, y) + >>> expected = torch.diag(2 * y) + >>> assert torch.allclose(jacobian, expected) + + Additionally, passing a tuple to ``argnums`` will compute the Jacobian + with respect to multiple arguments + + >>> from torch.func import jacfwd + >>> def f(x, y): + >>> return x + y ** 2 + >>> + >>> x, y = torch.randn(5), torch.randn(5) + >>> jacobian = jacfwd(f, argnums=(0, 1))(x, y) + >>> expectedX = torch.diag(torch.ones_like(x)) + >>> expectedY = torch.diag(2 * y) + >>> assert torch.allclose(jacobian[0], expectedX) + >>> assert torch.allclose(jacobian[1], expectedY) + + """ + + @_wraps_without_dynamo_attrs(func) + def wrapper_fn(*args: Any) -> Any: + error_if_complex("jacfwd", args, is_input=True) + primals = args if argnums is None else _slice_argnums(args, argnums) + flat_primals, primals_spec = tree_flatten(primals) + flat_primals_numels = tuple(p.numel() for p in flat_primals) + flat_basis = _construct_standard_basis_for(flat_primals, flat_primals_numels) + if flat_basis is None: + raise AssertionError("flat_basis must not be None") + basis = tree_unflatten(flat_basis, primals_spec) + + def push_jvp(basis: Any) -> Any: + output = _jvp_with_argnums( + func, args, basis, argnums=argnums, has_aux=has_aux + ) + # output[0] is the output of `func(*args)` + error_if_complex("jacfwd", output[0], is_input=False) + if has_aux: + _, jvp_out, aux = output # pyrefly: ignore[bad-unpacking] + return jvp_out, aux + _, jvp_out = output # pyrefly: ignore[bad-unpacking] + return jvp_out + + results = vmap(push_jvp, randomness=randomness)(basis) + aux: Any = None + if has_aux: + results, aux = results + # aux is in the standard basis format, e.g. NxN matrix + # We need to fetch the first element as original `func` output + flat_aux, aux_spec = tree_flatten(aux) + flat_aux = [value[0] for value in flat_aux] + aux = tree_unflatten(flat_aux, aux_spec) + + jac_outs, spec = tree_flatten(results) + # Most probably below output check can never raise an error + # as jvp should test the output before + # assert_non_empty_output(jac_outs, 'jacfwd(f, ...)(*args)') + + jac_outs_ins = tuple( + tuple( + safe_unflatten(jac_out_in, -1, primal.shape) + for primal, jac_out_in in zip( + flat_primals, + torch.split( + jac_out.movedim(0, -1), list(flat_primals_numels), dim=-1 + ), + ) + ) + for jac_out in jac_outs + ) + jac_outs_ins = tuple( + tree_unflatten(jac_ins, primals_spec) for jac_ins in jac_outs_ins + ) + + if isinstance(argnums, int): + jac_outs_ins = tuple(jac_ins[0] for jac_ins in jac_outs_ins) + if has_aux: + return tree_unflatten(jac_outs_ins, spec), aux # type: ignore[possibly-unbound] + return tree_unflatten(jac_outs_ins, spec) + + return wrapper_fn + + +@exposed_in("torch.func") +def hessian(func: Callable[..., Any], argnums: argnums_t = 0) -> Callable[..., Any]: + """ + Computes the Hessian of ``func`` with respect to the arg(s) at index + ``argnum`` via a forward-over-reverse strategy. + + The forward-over-reverse strategy (composing ``jacfwd(jacrev(func))``) is + a good default for good performance. It is possible to compute Hessians + through other compositions of :func:`jacfwd` and :func:`jacrev` like + ``jacfwd(jacfwd(func))`` or ``jacrev(jacrev(func))``. + + Args: + func (function): A Python function that takes one or more arguments, + one of which must be a Tensor, and returns one or more Tensors + argnums (int or tuple[int, ...]): Optional, integer or tuple of integers, + saying which arguments to get the Hessian with respect to. + Default: 0. + + Returns: + Returns a function that takes in the same inputs as ``func`` and + returns the Hessian of ``func`` with respect to the arg(s) at + ``argnums``. + + .. note:: + You may see this API error out with "forward-mode AD not implemented + for operator X". If so, please file a bug report and we will prioritize it. + An alternative is to use ``jacrev(jacrev(func))``, which has better + operator coverage. + + A basic usage with a R^N -> R^1 function gives a N x N Hessian: + + >>> from torch.func import hessian + >>> def f(x): + >>> return x.sin().sum() + >>> + >>> x = torch.randn(5) + >>> hess = hessian(f)(x) # equivalent to jacfwd(jacrev(f))(x) + >>> assert torch.allclose(hess, torch.diag(-x.sin())) + + """ + return jacfwd(jacrev(func, argnums), argnums) + + +@doesnt_support_saved_tensors_hooks +def grad_and_value_impl( + func: Callable[..., Any], + argnums: argnums_t, + has_aux: bool, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> tuple[Any, Any]: + with grad_increment_nesting() as level: + output, aux, grad_input = None, None, None + # See NOTE [grad and vjp interaction with no_grad] + with torch.enable_grad(): + args = _wrap_all_tensors(args, level) + kwargs = _wrap_all_tensors(kwargs, level) + diff_args = _slice_argnums(args, argnums, as_tuple=False) + tree_map_(partial(_create_differentiable, level=level), diff_args) + + output = func(*args, **kwargs) + if has_aux: + if not (isinstance(output, tuple) and len(output) == 2): + raise RuntimeError( + "grad_and_value(f)(*args): output of function f should be a tuple: (output, aux) " + "if has_aux is True" + ) + output, aux = output + + if not isinstance(output, torch.Tensor): + raise RuntimeError( + "grad_and_value(f)(*args): Expected f(*args) " + f"to return a Tensor, got {type(output)}" + ) + if output.dim() != 0: + raise RuntimeError( + "grad_and_value(f)(*args): Expected f(*args) " + "to return a scalar Tensor, got tensor with " + f"{output.dim()} dims. Maybe you wanted to " + "use the vjp or jacrev APIs instead?" + ) + + flat_diff_args, spec = tree_flatten(diff_args) + + # NB: need create_graph so that backward pass isn't run in no_grad mode + flat_outputs = _as_tuple(output) + flat_grad_input = _autograd_grad( + flat_outputs, flat_diff_args, create_graph=True + ) + grad_input = tree_unflatten(flat_grad_input, spec) + + grad_input = _undo_create_differentiable(grad_input, level) + output = _undo_create_differentiable(output, level) + if has_aux: + # pyrefly: ignore[bad-specialization] + aux = _undo_create_differentiable(aux, level) + + if has_aux: + return grad_input, (output, aux) + return grad_input, output + + +def grad_impl( + func: Callable[..., Any], + argnums: argnums_t, + has_aux: bool, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> Any: + results = grad_and_value_impl(func, argnums, has_aux, args, kwargs) + if has_aux: + grad, (_, aux) = results + return grad, aux + grad, _ = results + return grad + + +def _maybe_wrap_functional_tensor( + maybe_tensor: Any, level: int, *, _python_functionalize: bool = False +) -> Any: + if not isinstance(maybe_tensor, torch.Tensor): + return maybe_tensor + wrapped = _wrap_functional_tensor(maybe_tensor, level) + _assert_wrapped_functional(maybe_tensor, wrapped) + if _python_functionalize: + # pyrefly: ignore[missing-argument] + out = FunctionalTensor(wrapped) + # pyrefly: ignore[missing-attribute] + torch._mirror_autograd_meta_to(maybe_tensor, out) + return out + return wrapped + + +def _wrap_all_tensors_to_functional( + tensor_pytree: Any, level: int, *, _python_functionalize: bool = False +) -> Any: + return tree_map( + partial( + lambda x: _maybe_wrap_functional_tensor( + x, level, _python_functionalize=_python_functionalize + ) + ), + tensor_pytree, + ) + + +def _maybe_unwrap_functional_tensor(maybe_tensor: Any, *, reapply_views: bool) -> Any: + if not isinstance(maybe_tensor, torch.Tensor): + return maybe_tensor + if isinstance(maybe_tensor, FunctionalTensor): + maybe_tensor = maybe_tensor.elem + + if not torch._is_functional_tensor(maybe_tensor): + # If it's not a functional tensor, just return it. + # This can happen if we functionalize a fn that returns a global, + # which was never wrapped properly. + return maybe_tensor + # Sync any pending updates on the output tensor + torch._sync(maybe_tensor) + return _unwrap_functional_tensor(maybe_tensor, reapply_views) + + +def _unwrap_all_tensors_from_functional( + tensor_pytree: Any, *, reapply_views: bool +) -> Any: + return tree_map( + lambda t: _maybe_unwrap_functional_tensor(t, reapply_views=reapply_views), + tensor_pytree, + ) + + +@exposed_in("torch.func") +def functionalize( + func: Callable[..., Any], *, remove: str = "mutations" +) -> Callable[..., Any]: + """ + functionalize is a transform that can be used to remove (intermediate) + mutations and aliasing from a function, while preserving the function's + semantics. + + ``functionalize(func)`` returns a new function with the same semantics + as ``func``, but with all intermediate mutations removed. + Every inplace operation performed on an intermediate tensor: + ``intermediate.foo_()`` + gets replaced by its out-of-place equivalent: + ``intermediate_updated = intermediate.foo()``. + + functionalize is useful for shipping a pytorch program off to + backends or compilers that aren't able to easily represent + mutations or aliasing operators. + + Args: + func (Callable[..., Any]): A Python function that takes one or more arguments. + remove (str): An optional string argument, that takes on either + the value 'mutations' or 'mutations_and_views'. + If 'mutations' is passed in then all mutating operators + will be replaced with their non-mutating equivalents. + If 'mutations_and_views' is passed in, then additionally, all aliasing + operators will be replaced with their non-aliasing equivalents. + Default: 'mutations'. + + Returns: + Returns a new "functionalized" function. It takes the same inputs as + ``func``, and has the same behavior, but any mutations + (and optionally aliasing) performed on intermediate tensors + in the function will be removed. + + functionalize will also remove mutations (and views) that were performed on function inputs. + However to preserve semantics, functionalize will "fix up" the mutations after + the transform has finished running, by detecting if any tensor inputs "should have" + been mutated, and copying the new data back to the inputs if necessary. + + + Example:: + + >>> # xdoctest: +SKIP + >>> import torch + >>> from torch.fx.experimental.proxy_tensor import make_fx + >>> from torch.func import functionalize + >>> + >>> # A function that uses mutations and views, but only on intermediate tensors. + >>> def f(a): + ... b = a + 1 + ... c = b.view(-1) + ... c.add_(1) + ... return b + ... + >>> inpt = torch.randn(2) + >>> + >>> out1 = f(inpt) + >>> out2 = functionalize(f)(inpt) + >>> + >>> # semantics are the same (outputs are equivalent) + >>> print(torch.allclose(out1, out2)) + True + >>> + >>> f_traced = make_fx(f)(inpt) + >>> f_no_mutations_traced = make_fx(functionalize(f))(inpt) + >>> f_no_mutations_and_views_traced = make_fx(functionalize(f, remove='mutations_and_views'))(inpt) + >>> + >>> print(f_traced.code) + + + + def forward(self, a_1): + add = torch.ops.aten.add(a_1, 1); a_1 = None + view = torch.ops.aten.view(add, [-1]) + add_ = torch.ops.aten.add_(view, 1); view = None + return add + + >>> print(f_no_mutations_traced.code) + + + + def forward(self, a_1): + add = torch.ops.aten.add(a_1, 1); a_1 = None + view = torch.ops.aten.view(add, [-1]); add = None + add_1 = torch.ops.aten.add(view, 1); view = None + view_1 = torch.ops.aten.view(add_1, [2]); add_1 = None + return view_1 + + >>> print(f_no_mutations_and_views_traced.code) + + + + def forward(self, a_1): + add = torch.ops.aten.add(a_1, 1); a_1 = None + view_copy = torch.ops.aten.view_copy(add, [-1]); add = None + add_1 = torch.ops.aten.add(view_copy, 1); view_copy = None + view_copy_1 = torch.ops.aten.view_copy(add_1, [2]); add_1 = None + return view_copy_1 + + + >>> # A function that mutates its input tensor + >>> def f(a): + ... b = a.view(-1) + ... b.add_(1) + ... return a + ... + >>> f_no_mutations_and_views_traced = make_fx(functionalize(f, remove='mutations_and_views'))(inpt) + >>> # + >>> # All mutations and views have been removed, + >>> # but there is an extra copy_ in the graph to correctly apply the mutation to the input + >>> # after the function has completed. + >>> print(f_no_mutations_and_views_traced.code) + + + + def forward(self, a_1): + view_copy = torch.ops.aten.view_copy(a_1, [-1]) + add = torch.ops.aten.add(view_copy, 1); view_copy = None + view_copy_1 = torch.ops.aten.view_copy(add, [2]); add = None + copy_ = torch.ops.aten.copy_(a_1, view_copy_1); a_1 = None + return view_copy_1 + + + There are a few "failure modes" for functionalize that are worth calling out: + (1) Like other torch.func transforms, `functionalize()` doesn't work with functions + that directly use `.backward()`. The same is true for torch.autograd.grad. + If you want to use autograd, you can compute gradients directly + with `functionalize(grad(f))`. + (2) Like other torch.func transforms, `functionalize()` doesn't work with global state. + If you call `functionalize(f)` on a function that takes views / mutations of + non-local state, functionalization will simply no-op and pass the view/mutation + calls directly to the backend. + One way to work around this is to ensure that any non-local state creation + is wrapped into a larger function, which you then call functionalize on. + (3) `resize_()` has some limitations: functionalize will only work on programs + that use resize_()` as long as the tensor being resized is not a view. + (4) `as_strided()` has some limitations: functionalize will not work on + `as_strided()` calls that result in tensors with overlapping memory. + + + Finally, a helpful mental model for understanding functionalization is that + most user pytorch programs are writing with the public torch API. + When executed, torch operators are generally decomposed into + our internal C++ "ATen" API. + The logic for functionalization happens entirely at the level of ATen. + Functionalization knows how to take every aliasing operator in ATen, + and map it to its non-aliasing equivalent + (e.g. ``tensor.view({-1})`` -> ``at::view_copy(tensor, {-1})``), + and how to take every mutating operator in ATen, + and map it to its non-mutating equivalent + (e.g. ``tensor.add_(1)`` -> ``at::add(tensor, -1)``), + while tracking aliases and mutations out-of-line to know when to fix things up. + Information about which ATen operators are aliasing or mutating all comes from + https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/native_functions.yaml. + """ + if remove == "mutations": + reapply_views = True + elif remove == "mutations_and_views": + reapply_views = False + else: + raise RuntimeError( + f"functionalize(f, remove='mutations'): received invalid argument for remove={remove}." + " Valid options are:\n" + " remove='mutations': all inplace and out= operators will be removed from the program, and replaced" + " with their out-of-place equivalents.\n" + " remove='mutations_and_views': In addition to the above, all aliasing operators {view} will be" + " replaced with their non-aliasing counterparts, {view}_copy.\n" + ) + + @_wraps_without_dynamo_attrs(func) + def wrapped(*args: Any, **kwargs: Any) -> Any: + try: + func_level = _func_increment_nesting(reapply_views) + func_args = _wrap_all_tensors_to_functional(args, func_level) + func_kwargs = _wrap_all_tensors_to_functional(kwargs, func_level) + + flattened_unwrapped_args = pytree.arg_tree_leaves(*args) + flattened_wrapped_args = pytree.arg_tree_leaves(*func_args) + flattened_unwrapped_kwargs = pytree.arg_tree_leaves(**kwargs) + flattened_wrapped_kwargs = pytree.arg_tree_leaves(**func_kwargs) + + func_outputs = func(*func_args, **func_kwargs) + outputs = _unwrap_all_tensors_from_functional( + func_outputs, reapply_views=reapply_views + ) + + for a in flattened_wrapped_args + flattened_wrapped_kwargs: + if isinstance(a, torch.Tensor): + # Call sync_() on the inputs, to ensure that any pending mutations have been applied. + torch._sync(a) + + # And if any mutations were applied to the inputs, we need to propagate them back to the user. + for unwrapped, wrapped in zip( + flattened_unwrapped_args, flattened_wrapped_args + ): + if isinstance(unwrapped, torch.Tensor) and isinstance( + wrapped, torch.Tensor + ): + _propagate_functional_input_mutation(unwrapped, wrapped) + for unwrapped, wrapped in zip( + flattened_unwrapped_kwargs, flattened_wrapped_kwargs + ): + if isinstance(unwrapped, torch.Tensor) and isinstance( + wrapped, torch.Tensor + ): + _propagate_functional_input_mutation(unwrapped, wrapped) + + return outputs + finally: + _func_decrement_nesting() + + return wrapped + + +@exposed_in("torch.func") +def linearize( + func: Callable[..., Any], *primals: Any +) -> tuple[Any, Callable[..., Any]]: + """ + Returns the value of ``func`` at ``primals`` and linear approximation + at ``primals``. + + Args: + func (Callable[..., Any]): A Python function that takes one or more arguments. + primals (Tensors): Positional arguments to ``func`` that must all be + Tensors. These are the values at which the function is linearly approximated. + + Returns: + Returns a ``(output, jvp_fn)`` tuple containing the output of ``func`` + applied to ``primals`` and a function that computes the jvp of + ``func`` evaluated at ``primals``. + + linearize is useful if jvp is to be computed multiple times at ``primals``. However, + to achieve this, linearize saves intermediate computation and has higher memory requirements + than directly applying `jvp`. So, if all the ``tangents`` are known, it maybe more efficient + to compute vmap(jvp) instead of using linearize. + + .. note:: + linearize evaluates ``func`` twice. Please file an issue for an implementation + with a single evaluation. + + Example:: + + >>> import torch + >>> from torch.func import linearize + >>> def fn(x): + ... return x.sin() + ... + >>> warnings.filterwarnings("ignore", message=".*Attempted to insert a get_attr Node with no underlying reference") # docs: hide + >>> output, jvp_fn = linearize(fn, torch.zeros(3, 3)) + >>> jvp_fn(torch.ones(3, 3)) + tensor([[1., 1., 1.], + [1., 1., 1.], + [1., 1., 1.]]) + >>> + + """ + # Note: We evaluate `fn` twice. + # Once for returning the output and other while + # tracing the graph. + # If this becomes a bottle-neck, we should update + # make_fx such that it also returns the output. + + output = func(*primals) + _, output_spec = tree_flatten(output) + + flat_primals, primals_argspec = tree_flatten(primals) + + # tangents for tracing + flat_tangents = tuple(p.new_empty(()).expand_as(p) for p in flat_primals) + + # function to trace + def trace_fn(flat_tangents: tuple[torch.Tensor, ...]) -> Any: + with fwAD.dual_level(): + flat_duals = tuple( + fwAD.make_dual(p, t) for p, t in zip(flat_primals, flat_tangents) + ) + duals = tree_unflatten(flat_duals, primals_argspec) + output = func(*duals) + tangents = tree_map_only( + torch.Tensor, lambda dual: safe_unpack_dual(dual, False)[1], output + ) + + return tangents + + jvp_graph = lazy_dynamo_disallow(make_fx)(trace_fn)(flat_tangents) + const_folded_jvp_graph = lazy_dynamo_disallow(const_fold.split_const_subgraphs)( + jvp_graph + ) + + # Hold only the meta-data regarding the primals. + flat_primals_shape = tuple(p.shape for p in flat_primals) + flat_primals_device = tuple(p.device for p in flat_primals) + flat_primals_dtype = tuple(p.dtype for p in flat_primals) + + def forward_ad_checks(flat_tangents: Sequence[torch.Tensor]) -> None: + for idx, t in enumerate(flat_tangents): + if t.shape != flat_primals_shape[idx]: + msg = ( + f"tangent:{idx} with shape {t.shape} in flattened " + f"pytree doesn't match the shape {flat_primals_shape[idx]} " + "of the corresponding primal." + ) + raise RuntimeError(msg) + + if t.device != flat_primals_device[idx]: + msg = ( + f"tangent:{idx} with device {t.device} in flattened " + f"pytree doesn't match the device {flat_primals_device[idx]} " + "of the corresponding primal." + ) + raise RuntimeError(msg) + + if t.dtype != flat_primals_dtype[idx]: + msg = ( + f"tangent:{idx} with dtype {t.dtype} in flattened " + f"pytree doesn't match the dtype {flat_primals_dtype[idx]} " + "of the corresponding primal." + ) + raise RuntimeError(msg) + + # jvp_fn : Callable[..., Any] to return + # It takes care of checking the argspec of tangents, + # calling the folded fx graph and unflattening fx graph output + def jvp_fn(*tangents: Any) -> Any: + flat_tangents, tangent_argspec = tree_flatten(tangents) + if tangent_argspec != primals_argspec: + raise RuntimeError( + f"Expected the tangents {tangent_argspec} to have " + f"the same argspec as the primals {primals_argspec}" + ) + + forward_ad_checks(flat_tangents) # type: ignore[arg-type] + + flat_output = const_folded_jvp_graph(*flat_tangents) + # const folded graph can return flat output, + # so transform output. + return tree_unflatten(flat_output, output_spec) + + return output, jvp_fn + + +@exposed_in("torch.func") +def debug_unwrap(tensor: torch.Tensor, *, recurse: bool = True) -> torch.Tensor: + """Unwraps a functorch tensor (e.g. BatchedTensor, GradTrackingTensor) to its underlying tensor. + + This function should only be used in a debug setting (e.g. trying to print the + value of a Tensor in a debugger). Otherwise, using the result of function + inside of a function being transformed will lead to undefined behavior. + """ + if not is_functorch_wrapped_tensor(tensor): + return tensor + result = get_unwrapped(tensor) + if recurse: + return debug_unwrap(result) + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/einops.py b/.venv/lib/python3.12/site-packages/torch/_functorch/einops.py new file mode 100644 index 0000000000000000000000000000000000000000..0c8a1b2c77ece0773b3fad127a0982e3a1265e28 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/einops.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import torch +from torch._functorch.utils import exposed_in + + +__all__ = ["rearrange"] + + +@exposed_in("torch.func") +def rearrange( + tensor: torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor, ...], + pattern: str, + **axes_lengths: int, +) -> torch.Tensor: + r"""A native implementation of `einops.rearrange`, a reader-friendly smart element reordering for multidimensional + tensors. This operation includes functionality of transpose (axes permutation), reshape (view), squeeze, unsqueeze, + stack, concatenate and other operations. + + See: https://einops.rocks/api/rearrange/ + + Args: + tensor (Tensor or sequence of Tensor): the tensor(s) to rearrange + pattern (str): the rearrangement pattern + axes_lengths (int): any additional length specifications for dimensions + + Returns: + Tensor: the rearranged tensor + + Examples: + >>> from torch.func import rearrange + >>> # suppose we have a set of 32 images in "h w c" format (height-width-channel) + >>> images = torch.randn((32, 30, 40, 3)) + + >>> # stack along first (batch) axis, output is a single array + >>> rearrange(images, "b h w c -> b h w c").shape + torch.Size([32, 30, 40, 3]) + + >>> # concatenate images along height (vertical axis), 960 = 32 * 30 + >>> rearrange(images, "b h w c -> (b h) w c").shape + torch.Size([960, 40, 3]) + + >>> # concatenated images along horizontal axis, 1280 = 32 * 40 + >>> rearrange(images, "b h w c -> h (b w) c").shape + torch.Size([30, 1280, 3]) + + >>> # reordered axes to "b c h w" format for deep learning + >>> rearrange(images, "b h w c -> b c h w").shape + torch.Size([32, 3, 30, 40]) + + >>> # flattened each image into a vector, 3600 = 30 * 40 * 3 + >>> rearrange(images, "b h w c -> b (c h w)").shape + torch.Size([32, 3600]) + + >>> # split each image into 4 smaller (top-left, top-right, bottom-left, bottom-right), 128 = 32 * 2 * 2 + >>> rearrange(images, "b (h1 h) (w1 w) c -> (b h1 w1) h w c", h1=2, w1=2).shape + torch.Size([128, 15, 20, 3]) + + >>> # space-to-depth operation + >>> rearrange(images, "b (h h1) (w w1) c -> b h w (c h1 w1)", h1=2, w1=2).shape + torch.Size([32, 15, 20, 12]) + """ + if not isinstance(tensor, torch.Tensor): + tensor = torch.stack(tensor) + + # Lazy import to avoid circular import: + # torch._functorch.einops -> functorch.einops (package __init__) -> torch._functorch.einops + from functorch.einops.rearrange import _create_rearrange_callable + + rearrange_callable = _create_rearrange_callable( + tensor.ndim, pattern, **axes_lengths + ) + + return rearrange_callable(tensor) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/functional_call.py b/.venv/lib/python3.12/site-packages/torch/_functorch/functional_call.py new file mode 100644 index 0000000000000000000000000000000000000000..051681a044f0b3f35b2a9fd142f37977be8f26c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/functional_call.py @@ -0,0 +1,264 @@ +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +import torch +import torch.nn as nn +from torch import Tensor +from torch._functorch.utils import exposed_in + + +@exposed_in("torch.func") +def functional_call( + module: torch.nn.Module, + parameter_and_buffer_dicts: dict[str, Tensor] | Sequence[dict[str, Tensor]], + args: Any = None, + kwargs: dict[str, Any] | None = None, + *, + tie_weights: bool = True, + strict: bool = False, +) -> Any: + r"""Performs a functional call on the module by replacing the module parameters + and buffers with the provided ones. + + .. note:: If the module has active parametrizations, passing a value in the + :attr:`parameter_and_buffer_dicts` argument with the name set to the regular parameter + name will completely disable the parametrization. + If you want to apply the parametrization function to the value passed + please set the key as ``{submodule_name}.parametrizations.{parameter_name}.original``. + + .. note:: If the module performs in-place operations on parameters/buffers, these will be reflected + in the ``parameter_and_buffer_dicts`` input. + + + Example:: + + >>> a = {'foo': torch.zeros(())} + >>> # xdoctest: +SKIP + >>> mod = Foo() # does self.foo = self.foo + 1 + >>> print(mod.foo) # tensor(0.) + >>> functional_call(mod, a, torch.ones(())) + >>> print(mod.foo) # tensor(0.) + >>> print(a['foo']) # tensor(1.) + + .. note:: If the module has tied weights, whether or not functional_call respects the tying is determined by the + tie_weights flag. + + Example:: + + >>> a = {'foo': torch.zeros(())} + >>> # xdoctest: +SKIP + >>> mod = Foo() # has both self.foo and self.foo_tied which are tied. Returns x + self.foo + self.foo_tied + >>> print(mod.foo) # tensor(1.) + >>> mod(torch.zeros(())) # tensor(2.) + >>> functional_call(mod, a, torch.zeros(())) # tensor(0.) since it will change self.foo_tied too + >>> functional_call(mod, a, torch.zeros(()), tie_weights=False) # tensor(1.)--self.foo_tied is not updated + >>> new_a = {'foo': torch.zeros(()), 'foo_tied': torch.zeros(())} + >>> functional_call(mod, new_a, torch.zeros()) # tensor(0.) + + An example of passing multiple dictionaries + + .. code-block:: python + + a = ( + {"weight": torch.ones(1, 1)}, + {"buffer": torch.zeros(1)}, + ) # two separate dictionaries + mod = nn.Bar(1, 1) # return self.weight @ x + self.buffer + print(mod.weight) # tensor(...) + print(mod.buffer) # tensor(...) + x = torch.randn((1, 1)) + print(x) + functional_call(mod, a, x) # same as x + print(mod.weight) # same as before functional_call + + + And here is an example of applying the grad transform over the parameters + of a model. + + .. code-block:: python + + import torch + import torch.nn as nn + from torch.func import functional_call, grad + + x = torch.randn(4, 3) + t = torch.randn(4, 3) + model = nn.Linear(3, 3) + + + def compute_loss(params, x, t): + y = functional_call(model, params, x) + return nn.functional.mse_loss(y, t) + + + grad_weights = grad(compute_loss)(dict(model.named_parameters()), x, t) + + .. note:: If the user does not need grad tracking outside of grad transforms, they can detach all of the + parameters for better performance and memory usage + + Example:: + + >>> detached_params = {k: v.detach() for k, v in model.named_parameters()} + >>> grad_weights = grad(compute_loss)(detached_params, x, t) + >>> grad_weights.grad_fn # None--it's not tracking gradients outside of grad + + This means that the user cannot call ``grad_weight.backward()``. However, if they don't need autograd tracking + outside of the transforms, this will result in less memory usage and faster speeds. + + Args: + module (torch.nn.Module): the module to call + parameters_and_buffer_dicts (Dict[str, Tensor] or tuple of Dict[str, Tensor]): the parameters that will be used in + the module call. If given a tuple of dictionaries, they must have distinct keys so that all dictionaries can + be used together + args (Any or tuple): arguments to be passed to the module call. If not a tuple, considered a single argument. + kwargs (dict): keyword arguments to be passed to the module call + tie_weights (bool, optional): If True, then parameters and buffers tied in the original model will be treated as + tied in the reparameterized version. Therefore, if True and different values are passed for the tied + parameters and buffers, it will error. If False, it will not respect the originally tied parameters and + buffers unless the values passed for both weights are the same. Default: True. + strict (bool, optional): If True, then the parameters and buffers passed in must match the parameters and + buffers in the original module. Therefore, if True and there are any missing or unexpected keys, it will + error. Default: False. + + Returns: + Any: the result of calling ``module``. + """ + if isinstance(parameter_and_buffer_dicts, dict): + parameters_and_buffers = parameter_and_buffer_dicts + elif isinstance(parameter_and_buffer_dicts, Sequence): + if not all(isinstance(d, dict) for d in parameter_and_buffer_dicts): + raise ValueError( + "Expected all elements of parameter_and_buffer_dicts to be dictionaries" + ) + all_keys = [k for d in parameter_and_buffer_dicts for k in d] + all_keys_counter: dict[str, int] = {} + for k in all_keys: + v = all_keys_counter.get(k, 0) + all_keys_counter[k] = v + 1 + repeated_keys = [key for key, n in all_keys_counter.items() if n > 1] + if len(repeated_keys) > 0: + raise ValueError( + f"{repeated_keys} appeared in multiple dictionaries; behavior of functional call is ambiguous" + ) + parameters_and_buffers = { + k: v for d in parameter_and_buffer_dicts for k, v in d.items() + } + else: + raise ValueError( + f"Expected parameter_and_buffer_dicts to be a dict, or a list/tuple of dicts, " + f"but got {type(parameter_and_buffer_dicts)}" + ) + + return nn.utils.stateless._functional_call( + module, + parameters_and_buffers, + args, + kwargs, + tie_weights=tie_weights, + strict=strict, + ) + + +@exposed_in("torch.func") +def stack_module_state( + models: Sequence[nn.Module] | nn.ModuleList, +) -> tuple[dict[str, Any], dict[str, Any]]: + """stack_module_state(models) -> params, buffers + + Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`. + + Given a list of ``M`` ``nn.Modules`` of the same class, returns two dictionaries + that stack all of their parameters and buffers together, indexed by name. + The stacked parameters are optimizable (i.e. they are new leaf nodes in the + autograd history that are unrelated to the original parameters and can be + passed directly to an optimizer). + + Here's an example of how to ensemble over a very simple model: + + .. code-block:: python + + num_models = 5 + batch_size = 64 + in_features, out_features = 3, 3 + models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)] + data = torch.randn(batch_size, 3) + + + def wrapper(params, buffers, data): + return torch.func.functional_call(models[0], (params, buffers), data) + + + params, buffers = stack_module_state(models) + output = vmap(wrapper, (0, 0, None))(params, buffers, data) + + assert output.shape == (num_models, batch_size, out_features) + + When there's submodules, this follows state dict naming conventions + + .. code-block:: python + + import torch.nn as nn + + + class Foo(nn.Module): + def __init__(self, in_features, out_features): + super().__init__() + hidden = 4 + self.l1 = nn.Linear(in_features, hidden) + self.l2 = nn.Linear(hidden, out_features) + + def forward(self, x): + return self.l2(self.l1(x)) + + + num_models = 5 + in_features, out_features = 3, 3 + models = [Foo(in_features, out_features) for i in range(num_models)] + params, buffers = stack_module_state(models) + print(list(params.keys())) # "l1.weight", "l1.bias", "l2.weight", "l2.bias" + + .. warning:: + All of the modules being stacked together must be the same (except for + the values of their parameters/buffers). For example, they should be in the + same mode (training vs eval). + """ + if len(models) == 0: + raise RuntimeError("stack_module_state: Expected at least one model, got 0.") + if not (all(m.training for m in models) or all(not m.training for m in models)): + raise RuntimeError( + "stack_module_state: Expected all models to have the same training/eval mode." + ) + model0_typ = type(models[0]) + if not all(type(m) is model0_typ for m in models): + raise RuntimeError( + "stack_module_state: Expected all models to be of the same class." + ) + all_params = [dict(model.named_parameters()) for model in models] + params = { + k: construct_stacked_leaf(tuple(params[k] for params in all_params), k) + for k in all_params[0] + } + all_buffers = [dict(model.named_buffers()) for model in models] + buffers = { + k: construct_stacked_leaf(tuple(buffers[k] for buffers in all_buffers), k) + for k in all_buffers[0] + } + + return params, buffers + + +def construct_stacked_leaf( + tensors: tuple[Tensor, ...] | list[Tensor], name: str +) -> Tensor: + all_requires_grad = all(t.requires_grad for t in tensors) + none_requires_grad = all(not t.requires_grad for t in tensors) + if not all_requires_grad and not none_requires_grad: + raise RuntimeError( + f"Expected {name} from each model to have the same .requires_grad" + ) + result = torch.stack(tensors) + if all_requires_grad: + result = result.detach().requires_grad_() + return result diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/fx_minifier.py b/.venv/lib/python3.12/site-packages/torch/_functorch/fx_minifier.py new file mode 100644 index 0000000000000000000000000000000000000000..95ddd9ef46afc3cde232fe7d0c3502f4b1cbd8dc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/fx_minifier.py @@ -0,0 +1,562 @@ +from __future__ import annotations + +import copy +import math +import os +import sys +from dataclasses import dataclass +from functools import partial, wraps +from typing import Any, TYPE_CHECKING + +import torch +import torch.fx as fx +from torch.hub import tqdm +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._content_store import ContentStoreWriter + +from .compile_utils import get_outputs, get_placeholders + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + +is_tuple = object() + + +@dataclass +class LoadTensorMeta: + size: tuple[int, ...] + stride: tuple[int, ...] + dtype: torch.dtype + device: torch.device + + +class ConcreteProp(torch.fx.Interpreter): + def __init__( + self, + mod: fx.GraphModule, + *, + writer: ContentStoreWriter | None = None, + skip_offload: bool = False, + ) -> None: + super().__init__(mod) + self.writer = writer + self.skip_offload = skip_offload + self.seen_storages: set[StorageWeakRef] = set() + self.pbar: Any = None + + def run_node(self, n: fx.Node) -> Any: + self.pbar.update(1) + r = super().run_node(n) + name = n.name + + if isinstance(r, torch.Tensor): + if self.writer is None: + n.meta["concrete_value"] = r + else: + if StorageWeakRef(r.untyped_storage()) in self.seen_storages: + # Refuse to offload tensors which alias other live + # tensors, because this will violate operator contracts + n.meta["concrete_value"] = None + else: + if not self.skip_offload: + self.writer.write_tensor(os.path.join("eager", name), r) + n.meta["concrete_value"] = LoadTensorMeta( + r.size(), r.stride(), r.dtype, r.device + ) + self.seen_storages.add(StorageWeakRef(r.untyped_storage())) + else: + n.meta["concrete_value"] = is_tuple + + return r + + def propagate(self, *args: Any) -> Any: + mod = self.module + if not isinstance(mod, fx.GraphModule): + raise AssertionError(f"expected fx.GraphModule, got {type(mod)}") + with tqdm( + desc="Saving intermediates for delta debugging", + total=len(mod.graph.nodes), + disable=self.writer is None, + ) as pbar: + self.pbar = pbar + r = super().run(*args) + if not self.skip_offload: + pbar.set_description( + "Saved! To skip next time, run with --skip-saving-eager-intermediates" + ) + return r + + +def is_load_tensor_node(node: fx.Node) -> bool: + return ( + node.op == "call_function" + and node.target is torch.ops.debugprims.load_tensor.default + ) + + +# inplace modifies node/inps +def _convert_node_to_placeholder( + graph: fx.Graph, node: fx.Node, inps: list[torch.Tensor] +) -> bool: + if node.op == "output" or node.op == "placeholder": + return False + + if is_load_tensor_node(node): + return False + + concrete_val = node.meta.get("concrete_value", None) + + if isinstance(concrete_val, torch.Tensor): + node.op = "placeholder" + node.target = node.name + node.args = () + node.kwargs = {} + + inps.append(concrete_val) + return True + + elif concrete_val is None: + return False + + elif concrete_val is is_tuple: + r = False + for tuple_user in list(node.users): + r = _convert_node_to_placeholder(graph, tuple_user, inps) or r + # NB: We must not erase the node at this point, because + # we are iterating over the nodes and this would change + # the iteration order + # graph.erase_node(node) + return r + + elif isinstance(concrete_val, LoadTensorMeta): + node.op = "call_function" + node.target = torch.ops.debugprims.load_tensor.default + node.args = ( + os.path.join("eager", node.name), + concrete_val.size, + concrete_val.stride, + ) + node.kwargs = { + "device": concrete_val.device, + "dtype": concrete_val.dtype, + } + return True + + return False + + +def create_minified_hlo_graph( + minified_fx_graph: fx.GraphModule, inputs: Sequence[torch.Tensor] +) -> None: + """ + Takes minified FX graph as primary input, and ports it to HLO via StableHLO + Provides minified HLO graph as output, and archive them to local directory + """ + hlo_dir = f"{os.getcwd()}/hlo_files" + os.makedirs(hlo_dir, exist_ok=True) + + from torch_xla.stablehlo import save_torch_model_as_stablehlo + + save_torch_model_as_stablehlo(minified_fx_graph, inputs, hlo_dir) + + +def dump_state(fx_g: fx.GraphModule, inps: Sequence[torch.Tensor]) -> None: + print( + f""" +# Working Repro with {len(fx_g.graph.nodes)} nodes +inps = {[(i.shape, i.dtype, str(i.device)) for i in inps]} +inps = [torch.zeros(())] + [torch.ones(shape, dtype=dtype, device=device) for (shape, dtype, device) in inps] +{fx_g.code} +""" + ) + + +def is_power_of_two(n: int) -> bool: + if n == 0: + return False + return (n & (n - 1)) == 0 + + +@dataclass +class ReproState: + graph: fx.Graph + inps: Sequence[torch.Tensor] + + def __post_init__(self) -> None: + ph_nodes = get_placeholders(self.graph) + if len(ph_nodes) != len(self.inps): + raise AssertionError( + f"len(ph_nodes)={len(ph_nodes)} != len(self.inps)={len(self.inps)}" + ) + + +def minifier( + fail_f: fx.GraphModule, + inps: Sequence[torch.Tensor], + module_fails: Callable[[fx.GraphModule, Sequence[torch.Tensor]], bool], + dump_state: Callable[[fx.GraphModule, Sequence[torch.Tensor]], None] = dump_state, + *, + save_dir: str | None = None, + offload_to_disk: bool = False, + skip_offload: bool = False, + skip_sanity: bool = False, + max_granularity: int | None = None, +) -> tuple[fx.GraphModule, Sequence[torch.Tensor]]: + """ + Minimizes a FX graph with given inputs, such that the resulting FX graph still returns True for module_fails. + + Does 2 main strategies: + 1. Truncates suffix: Removes some suffix from the graph and sets a new output. + 2. Delta Debugging: Tries replacing half of the graph with inputs. If fails, + tries replacing quarter of the graph, etc. + + >>> # xdoctest: +SKIP(failing) + >>> failing_function = fx.symbolic_trace(f) + >>> minimize(failing_function, [torch.randn(5)], lambda fx_g, inps: fx_g(*inps)) + + note: module_fails returns True if it fails. + """ + + failing_graph = fail_f.graph + cur_size = len(failing_graph.nodes) + + if max_granularity is not None and not is_power_of_two(max_granularity): + raise RuntimeError(f"max_granularity {max_granularity} not power of two") + + num_queries = 0 + + def deepcopy_fx_graph(fx_graph: fx.Graph) -> fx.Graph: + return fx.GraphModule(fail_f, copy.deepcopy(fx_graph)).graph + + def graph_fails(graph: fx.Graph, inps: Sequence[torch.Tensor]) -> bool: + nonlocal num_queries + graph = copy.deepcopy(graph) + num_queries += 1 + mod = fx.GraphModule(fail_f, graph) + mod.graph.lint() + return module_fails(mod, inps) + + writer = None + if offload_to_disk: + if save_dir is None: + raise AssertionError("save_dir must not be None when offload_to_disk=True") + writer = ContentStoreWriter(save_dir) + + ConcreteProp(fail_f, writer=writer, skip_offload=skip_offload).propagate(*inps) + if not skip_sanity and not graph_fails(failing_graph, inps): + raise RuntimeError("Input graph did not fail the tester") + print(f"Started off with {cur_size} nodes", file=sys.stderr) + + def _register_strategy( + strategy: Callable[[fx.Graph, Sequence[torch.Tensor], int], ReproState | None], + name: str, + ) -> Callable[[ReproState, int], ReproState | None]: + @wraps(strategy) + def new_func(old_state: ReproState, granularity: int = 1) -> ReproState | None: + print(file=sys.stderr) + print( + f"Strategy: {name} (G: {granularity}) " + f"({len(old_state.graph.nodes)} nodes, {len(old_state.inps)} inputs)", + file=sys.stderr, + ) + new_state = strategy( + deepcopy_fx_graph(old_state.graph), list(old_state.inps), granularity + ) + if new_state is not None: + new_nodes = len(new_state.graph.nodes) + old_nodes = len(old_state.graph.nodes) + new_inps = len(new_state.inps) + old_inps = len(old_state.inps) + new_outs = len(get_outputs(new_state.graph)) + old_outs = len(get_outputs(old_state.graph)) + progress_made = False + if new_nodes < old_nodes: + progress_made = True + print( + f"SUCCESS: Went from {old_nodes} to {new_nodes} nodes", + file=sys.stderr, + ) + if new_inps > old_inps: + progress_made = True + print( + f"SUCCESS: Went from {old_inps} to {new_inps} inputs", + file=sys.stderr, + ) + if new_outs < old_outs: + progress_made = True + print( + f"SUCCESS: Went from {old_outs} to {new_outs} outputs", + file=sys.stderr, + ) + + if not progress_made: + raise RuntimeError("Success raised but no progress made?") + + if not graph_fails(new_state.graph, new_state.inps): + print( + "WARNING: Something went wrong, not applying this minification", + file=sys.stderr, + ) + return None + return new_state + else: + print(f"FAIL: {name}", file=sys.stderr) + return None + + return new_func + + def register_strategy( + name: str, + ) -> Callable[ + [Callable[[fx.Graph, Sequence[torch.Tensor], int], ReproState | None]], + Callable[[ReproState, int], ReproState | None], + ]: + return partial(_register_strategy, name=name) + + @register_strategy("Truncate suffix") + def remove_suffix( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + tested: set[int] = set() + new_graph = fx.Graph() + env: dict[fx.Node, fx.Node] = {} + for idx, node in enumerate(cur_graph.nodes): + new_node = new_graph.node_copy(node, lambda x: env[x]) + if node.op not in ["placeholder", "output"]: + # If idx is divisible by (granularity * 2), it would have been checked already. + if ( + idx % granularity == 0 + and (idx % (granularity * 2) != 0) + and idx not in tested + ): + output_node = new_graph.output((new_node,)) + if len(new_graph.nodes) < len(cur_graph.nodes) and graph_fails( + new_graph, cur_inps + ): + return ReproState(new_graph, cur_inps) + else: + tested.add(idx) + new_graph.erase_node(output_node) + env[node] = new_node + return None + + @register_strategy("Remove outputs") + def remove_outputs( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + granularity = max(1, granularity // 2) + output: fx.Node | None = None + for idx, node in enumerate(cur_graph.nodes): + node.idx = idx # type: ignore[attr-defined] + if node.op == "output": + output = node + break + + if output is None: + return None + + if isinstance(output.args[0], fx.Node): + return None + + # output.args[0] is a tuple/list of nodes when returning multiple outputs + output_args_raw = output.args[0] + if not isinstance(output_args_raw, (list, tuple)): + raise AssertionError( + f"expected output_args_raw to be list or tuple, got {type(output_args_raw)}" + ) + output_args = sorted( + output_args_raw, + key=lambda x: x.idx if isinstance(x, fx.Node) else int(1e9), # type: ignore[attr-defined] + ) + if len(output_args) == 1: + return None + + for idx in range(0, len(output_args), granularity): + output.args = (output_args[:idx] + output_args[idx + granularity :],) + if graph_fails(cur_graph, cur_inps): + return ReproState(cur_graph, cur_inps) + return None + + def remove_unused_inputs_unchecked(cur_state: ReproState) -> ReproState | None: + cur_graph = cur_state.graph + cur_inps = cur_state.inps + ph_nodes = list(get_placeholders(cur_graph)) + if len(ph_nodes) != len(cur_inps): + raise AssertionError( + f"len(ph_nodes)={len(ph_nodes)} != len(cur_inps)={len(cur_inps)}" + ) + + new_inps: list[torch.Tensor] = [] + for idx in range(len(ph_nodes)): + if len(ph_nodes[idx].users) == 0: + cur_graph.erase_node(ph_nodes[idx]) + else: + new_inps.append(cur_inps[idx]) + if len(new_inps) < len(cur_inps): + return ReproState(cur_graph, new_inps) + return None + + def remove_unused_inputs_checked(cur_state: ReproState) -> ReproState | None: + new_state = remove_unused_inputs_unchecked(cur_state) + if new_state is not None and graph_fails(new_state.graph, new_state.inps): + return new_state + return None + + def _remove_unused_wrapper( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + return remove_unused_inputs_checked(ReproState(cur_graph, cur_inps)) + + remove_unused_inputs = register_strategy("Remove unused inputs")( + _remove_unused_wrapper + ) + + @register_strategy("Eliminate dead code") + def eliminate_dead_code( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + if cur_graph.eliminate_dead_code() and graph_fails(cur_graph, cur_inps): + return ReproState(cur_graph, cur_inps) + return None + + def _consolidate_placeholders( + cur_graph: fx.Graph, inps: list[torch.Tensor] + ) -> fx.Graph: + new_graph = fx.Graph() + env = {} + seen_non_placeholder = False + + # Move all placeholders to the front; also, if any load_tensor + # is at the front, convert it into an input (because it can be live + # all the time) + for node in cur_graph.nodes: + if node.op == "placeholder": + new_node = new_graph.node_copy(node, lambda x: env[x]) + env[node] = new_node + elif not seen_non_placeholder and is_load_tensor_node(node): + new_node = new_graph.placeholder(node.name) + env[node] = new_node + inps.append( + torch.ops.debugprims.load_tensor.default(*node.args, **node.kwargs) + ) + else: + seen_non_placeholder = True + + # Move everyone else + for node in cur_graph.nodes: + if node not in env: + new_node = new_graph.node_copy(node, lambda x: env[x]) + env[node] = new_node + return new_graph + + @register_strategy("Delta Debugging") + def delta_debugging( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + num_nodes = len(cur_graph.nodes) + for start_range in range(0, num_nodes, granularity): + is_removing = False + new_graph = deepcopy_fx_graph(cur_graph) + new_inps = list(cur_inps[:]) + end_range = min(num_nodes, start_range + granularity) + for idx in range(start_range, end_range): + new_node = list(new_graph.nodes)[idx] + if _convert_node_to_placeholder(new_graph, new_node, new_inps): + is_removing = True + if not is_removing: + continue + new_graph.eliminate_dead_code() + new_graph = _consolidate_placeholders(new_graph, new_inps) + new_state = remove_unused_inputs_unchecked(ReproState(new_graph, new_inps)) + if new_state is None: + new_state = ReproState(new_graph, new_inps) + if graph_fails(new_state.graph, new_state.inps): + return ReproState(new_state.graph, new_state.inps) + + return None + + @register_strategy("Consolidate Inputs") + def consolidate_inputs( + cur_graph: fx.Graph, cur_inps: Sequence[torch.Tensor], granularity: int + ) -> ReproState | None: + old_len = len(cur_inps) + new_inps = list(cur_inps[:]) + cur_graph = _consolidate_placeholders(cur_graph, new_inps) + if len(cur_inps) > old_len and graph_fails(cur_graph, new_inps): + return ReproState(cur_graph, new_inps) + return None + + failing_state = ReproState(failing_graph, inps) + + def try_granularity( + failing_state: ReproState, granularity: int, use_non_granular: bool + ) -> ReproState | None: + print(f"Trying granularity {granularity}", file=sys.stderr) + + strategies = [] + num_nodes = len(failing_state.graph.nodes) + num_outputs = len(get_outputs(failing_state.graph)) + if num_outputs > num_nodes // 2: + strategies += [remove_outputs] + + if use_non_granular: + strategies += [ + eliminate_dead_code, + remove_unused_inputs, + consolidate_inputs, + ] + + strategies += [remove_suffix, delta_debugging] + + for strategy in strategies: + new_state = strategy(failing_state, granularity) + if new_state is not None: + return new_state + return None + + while True: + dump_state(fx.GraphModule(fail_f, failing_state.graph), failing_state.inps) + granularity = int(2 ** (math.floor(math.log2(len(failing_state.graph.nodes))))) + if max_granularity is not None: + granularity = min(max_granularity, granularity) + new_state = try_granularity(failing_state, granularity, use_non_granular=True) + if new_state is not None: + failing_state = new_state + continue + + granularity //= 2 + has_progress = False + while granularity >= 1: + new_state = try_granularity( + failing_state, granularity, use_non_granular=False + ) + if new_state is not None: + failing_state = new_state + has_progress = True + break + granularity //= 2 + if has_progress: + continue + + new_state = remove_outputs(failing_state, 1) + if new_state is not None: + failing_state = new_state + continue + + break + + if not graph_fails(failing_state.graph, failing_state.inps): + raise RuntimeError("Uh oh, something went wrong :( Final graph is not failing") + + print(f"Made {num_queries} queries", file=sys.stderr) + failing_fx = fx.GraphModule(fail_f, failing_state.graph) + + # If XLA debugging environment is enabled, create minified HLO graph as well + if "XLA_HLO_DEBUG" in os.environ: + create_minified_hlo_graph(failing_fx, failing_state.inps) + + dump_state(failing_fx, failing_state.inps) + print("Wrote minimal repro out to repro.py", file=sys.stderr) + return failing_fx, failing_state.inps diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/make_functional.py b/.venv/lib/python3.12/site-packages/torch/_functorch/make_functional.py new file mode 100644 index 0000000000000000000000000000000000000000..65b77627b1dc8f922d1c511a345859ae9eb60346 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/make_functional.py @@ -0,0 +1,669 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +import copy +from typing import Any, NoReturn, TYPE_CHECKING + +import torch +import torch.nn as nn +from torch import Tensor +from torch.nn.utils._named_member_accessor import NamedMemberAccessor + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + +# Utilities to make nn.Module "functional" +# In particular the goal is to be able to provide a function that takes as input +# the parameters and evaluate the nn.Module using fixed inputs. + + +def raise_parameter_tying_error() -> NoReturn: + raise RuntimeError( + "make_functional(module): we don't yet support models that " + "do parameter tying (also sometimes known as weight sharing). " + "Please try to rewrite your model by replacing all instances of the " + "tied parameter with another and/or comment your support in " + "https://github.com/pytorch/functorch/issues/446" + ) + + +def create_names_map( + named_params: dict[str, Tensor] | Iterable[tuple[str, Tensor]], + tied_named_params: dict[str, Tensor] | Iterable[tuple[str, Tensor]], +) -> dict[str, list[str]]: + """ + named_params is a dictionary of tensors: {'A': A, 'B': B} + tied_named_params is another dictionary of tensors {'A': A, 'B': B, 'B_tied': B} + with potentially tied (or 'duplicated') tensors + + This function creates a mapping from the names in named_params to the + names in tied_named_params: {'A': ['A'], 'B': ['B', 'B_tied']}. + """ + named_params_dict = dict(named_params) + tied_named_params_dict = dict(tied_named_params) + + tensors_dict_keys = set(named_params_dict.keys()) + tied_tensors_dict_keys = set(tied_named_params_dict.keys()) + if not tensors_dict_keys.issubset(tied_tensors_dict_keys): + raise AssertionError( + f"tensors_dict_keys {tensors_dict_keys} is not a subset of " + f"tied_tensors_dict_keys {tied_tensors_dict_keys}" + ) + + tensor_to_mapping: dict[Tensor, tuple[str, list[str]]] = {} + for key, tensor in named_params_dict.items(): + tensor_to_mapping[tensor] = (key, []) + for key, tensor in tied_named_params_dict.items(): + if tensor not in tensor_to_mapping: + raise AssertionError( + f"tensor for key '{key}' not found in tensor_to_mapping" + ) + tensor_to_mapping[tensor][1].append(key) + return dict(tensor_to_mapping.values()) + + +def _extract_members( + mod: nn.Module, + named_members: Callable[..., Iterable[tuple[str, Tensor]]], + subclass: Callable[[Tensor], Tensor], +) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]: + all_named_members = tuple(named_members(remove_duplicate=False)) + unique_named_members = tuple(named_members(remove_duplicate=True)) + names_map = create_names_map(unique_named_members, all_named_members) + + # Remove all the members in the model + # pyrefly: ignore [implicit-any] + memo = {} + accessor = NamedMemberAccessor(mod) + for name, p in all_named_members: + if p not in memo: + memo[p] = subclass(torch.empty_like(p, device="meta")) + replacement = memo[p] + accessor.set_tensor(name, replacement) + + if len(unique_named_members) == 0: + names, params = (), () + else: + names, params = zip(*unique_named_members) # type: ignore[assignment] + return params, names, names_map + + +def extract_weights( + mod: nn.Module, +) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]: + """ + This function removes all the Parameters from the model and + return them as a tuple as well as their original attribute names. + The weights must be re-loaded with `load_weights` before the model + can be used again. + Note that this function modifies the model in place and after this + call, mod.parameters() will be empty. + """ + return _extract_members(mod, mod.named_parameters, nn.Parameter) + + +def extract_buffers( + mod: nn.Module, +) -> tuple[tuple[Tensor, ...], tuple[str, ...], dict[str, list[str]]]: + return _extract_members(mod, mod.named_buffers, lambda x: x) + + +def load_weights( + mod: nn.Module, + names: Sequence[str], + params: Sequence[Tensor], + as_params: bool = False, +) -> None: + """ + Reload a set of weights so that `mod` can be used again to perform a forward pass. + Note that the `params` are regular Tensors (that can have history) and so are left + as Tensors. This means that mod.parameters() will still be empty after this call. + """ + accessor = NamedMemberAccessor(mod) + if as_params: + params = [nn.Parameter(p) for p in params] + accessor.set_tensors(names, params) + + +def _swap_state( + mod: nn.Module, names_map: dict[str, list[str]], elems: Iterable[Tensor] +) -> list[Tensor]: + result: list[Tensor] = [] + accessor = NamedMemberAccessor(mod) + for (_, attr_names), elem in zip(names_map.items(), elems): + for i, attr_name in enumerate(attr_names): + if i == 0: + result.append(accessor.swap_tensor(attr_name, elem)) + else: + accessor.set_tensor(attr_name, elem) + return result + + +def load_buffers( + mod: nn.Module, + names: Sequence[str], + buffers: Sequence[Tensor], + as_params: bool = False, +) -> None: + accessor = NamedMemberAccessor(mod) + accessor.set_tensors(names, buffers) + + +def load_state( + model: nn.Module, + weights: Sequence[Tensor], + weight_names: Sequence[str], + buffers: Sequence[Tensor] = (), + buffer_names: Sequence[str] = (), +) -> nn.Module: + """load_state(model, weights, weight_names, buffers=(), buffer_names=()) -> model + + load_state takes `weights` and `buffers` and assigns them to the model. + This is the inverse operation of `make_functional_deprecated_v1`. + """ + if len(weight_names) != len(weights): + raise AssertionError( + f"len(weight_names)={len(weight_names)} != len(weights)={len(weights)}" + ) + load_weights(model, weight_names, weights) + if len(buffers) > 0: + if len(buffer_names) != len(buffers): + raise AssertionError( + f"len(buffer_names)={len(buffer_names)} != len(buffers)={len(buffers)}" + ) + load_buffers(model, buffer_names, buffers) + return model + + +def make_functional_deprecated_v1( + model: nn.Module, +) -> tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]: + """make_functional_deprecated_v1(model) -> weights, func, weight_names + + Given an nn.Module, make_functional_deprecated_v1 extracts the state (weights) + and returns a functional version of the model, `func`. This makes + it so that it is possible use transforms over the parameters of + `model`. + + `func` can be invoked as follows: + ``` + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + weights, func, _ = make_functional_deprecated_v1(model) + func(weights, (x,)) + ``` + + And here is an example of applying the grad transform: + ``` + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + weights, _, func = make_functional_deprecated_v1(model) + grad_weights = grad(func)(weights, (x,)) + ``` + + To put the state back into a model, use `load_state`. + """ + buffers = list(model.buffers()) + if len(buffers) > 0: + raise RuntimeError( + "make_functional_deprecated_v1(model): `model` has buffers. Please use " + "make_functional_with_buffers_deprecated_v1(model) instead." + ) + weights, descriptors, _ = extract_weights(model) + + def fun(weights: tuple[Tensor, ...], data: tuple[Any, ...]) -> Any: + mutable_model = copy.deepcopy(model) + load_weights(mutable_model, descriptors, weights) + return mutable_model(*data) + + return weights, fun, descriptors + + +def make_functional_with_buffers_deprecated_v1( + model: nn.Module, +) -> tuple[ + tuple[Tensor, ...], + tuple[Tensor, ...], + Callable[..., Any], + tuple[str, ...], + tuple[str, ...], +]: + """make_functional_with_buffers_deprecated_v1(model) -> weights, buffers, func, weight_names, buffer_names + + Given an nn.Module, make_functional_with_buffers_deprecated_v1 extracts the state (weights and buffers) + and returns a functional version of the model, `func`. + + `func` can be invoked as follows: + ``` + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + weights, buffers, func, _, _ = make_functional_with_buffers_deprecated_v1(model) + func(weights, buffers, (x,)) + ``` + + And here is an example of applying the grad transform: + ``` + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + weights, buffers, func, _, _ = make_functional_with_buffers_deprecated_v1(model) + func(weights, buffers, (x,)) + grad_weights = grad(func)(weights, buffers, (x,)) + ``` + + To put the state back into a model, use `load_state`. + """ + weights, weight_descriptors, _ = extract_weights(model) + buffers, buf_descriptors, _ = extract_buffers(model) + + def fun( + weights: tuple[Tensor, ...], + buffers: tuple[Tensor, ...], + data: tuple[Any, ...], + ) -> Any: + mutable_model = copy.deepcopy(model) + load_weights(mutable_model, weight_descriptors, weights) + load_buffers(mutable_model, buf_descriptors, buffers) + return mutable_model(*data) + + return weights, buffers, fun, weight_descriptors, buf_descriptors + + +class FunctionalModuleWithBuffers(nn.Module): + """ + This is the callable object returned by :func:`make_functional_with_buffers`. + """ + + def __init__( + self, + stateless_model: nn.Module, + param_names: tuple[str, ...], + buffer_names: tuple[str, ...], + param_names_map: dict[str, list[str]], + buffer_names_map: dict[str, list[str]], + ) -> None: + super().__init__() + self.stateless_model = stateless_model + self.param_names = param_names + self.buffer_names = buffer_names + + self.all_names_map = dict(param_names_map) + self.all_names_map.update(buffer_names_map) + + @staticmethod + def _create_from( + model: nn.Module, disable_autograd_tracking: bool = False + ) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]: + # TODO: We don't need to copy the model to create a stateless copy + model_copy = copy.deepcopy(model) + params, param_names, param_names_map = extract_weights(model_copy) + buffers, buffer_names, buffer_names_map = extract_buffers(model_copy) + if disable_autograd_tracking: + for param in params: + param.requires_grad_(False) + return ( + FunctionalModuleWithBuffers( + model_copy, param_names, buffer_names, param_names_map, buffer_names_map + ), + params, + buffers, + ) + + def forward( + self, + params: Iterable[Tensor], + buffers: Iterable[Tensor], + *args: Any, + **kwargs: Any, + ) -> Any: + # Temporarily load the state back onto self.stateless_model + old_state = _swap_state( + self.stateless_model, + self.all_names_map, + tuple(params) + tuple(buffers), + ) + try: + return self.stateless_model(*args, **kwargs) + finally: + # Remove the loaded state on self.stateless_model + _swap_state(self.stateless_model, self.all_names_map, old_state) + + +class FunctionalModule(nn.Module): + """ + This is the callable object returned by :func:`make_functional`. + """ + + def __init__( + self, + stateless_model: nn.Module, + param_names: tuple[str, ...], + names_map: dict[str, list[str]], + ) -> None: + super().__init__() + self.stateless_model = stateless_model + self.param_names = param_names + self.names_map = names_map + + @staticmethod + def _create_from( + model: nn.Module, disable_autograd_tracking: bool = False + ) -> tuple[FunctionalModule, tuple[Tensor, ...]]: + # TODO: We don't need to copy the model to create a stateless copy + model_copy = copy.deepcopy(model) + params, param_names, names_map = extract_weights(model_copy) + if disable_autograd_tracking: + for param in params: + param.requires_grad_(False) + return FunctionalModule(model_copy, param_names, names_map), params + + def forward(self, params: Iterable[Tensor], *args: Any, **kwargs: Any) -> Any: + # Temporarily load the state back onto self.stateless_model + old_state = _swap_state(self.stateless_model, self.names_map, params) + try: + return self.stateless_model(*args, **kwargs) + finally: + # Remove the loaded state on self.stateless_model + _swap_state(self.stateless_model, self.names_map, old_state) + + +def make_functional( + model: nn.Module, disable_autograd_tracking: bool = False +) -> tuple[FunctionalModule, tuple[Tensor, ...]]: + """make_functional(model, disable_autograd_tracking=False) -> func, params + + Given a ``torch.nn.Module``, :func:`make_functional` extracts the state + (params) and returns a functional version of the model, ``func``. This + makes it so that it is possible use transforms over the parameters of + ``model``. + + ``func`` can be invoked as follows: + + .. code-block:: python + + import torch + import torch.nn as nn + from functorch import make_functional + + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + func, params = make_functional(model) + func(params, x) + + And here is an example of applying the grad transform over the parameters + of a model. + + .. code-block:: python + + import torch + import torch.nn as nn + from functorch import make_functional, grad + + x = torch.randn(4, 3) + t = torch.randn(4, 3) + model = nn.Linear(3, 3) + func, params = make_functional(model) + + + def compute_loss(params, x, t): + y = func(params, x) + return nn.functional.mse_loss(y, t) + + + grad_weights = grad(compute_loss)(params, x, t) + + If the model has any buffers, please use :func:`make_functional_with_buffers` instead. + + Args: + model (torch.nn.Module): Input model. + disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters. + The returned params are unrelated to the set of params from the original model. If False (default), + the params will have ``requires_grad=True`` on them (aka they will be trackable with regular + PyTorch autograd), matching the requires_grad-ness of the params from the original model. + Otherwise, the returned params will have ``requires_grad=False``. Default, False. + If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or + ``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``. + Otherwise, if you're only planning on using functorch's gradient transforms, + then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking + history with PyTorch autograd. + + """ + buffers = list(model.buffers()) + if len(buffers) > 0: + raise RuntimeError( + "make_functional(model): `model` has buffers. Please use " + "make_functional_with_buffers(model) instead." + ) + return FunctionalModule._create_from( + model, disable_autograd_tracking=disable_autograd_tracking + ) + + +def make_functional_with_buffers( + model: nn.Module, disable_autograd_tracking: bool = False +) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]: + """make_functional_with_buffers(model, disable_autograd_tracking=False) -> func, params, buffers + + Given a ``torch.nn.Module``, make_functional_with_buffers extracts the + state (params and buffers) and returns a functional version of the model + ``func`` that can be invoked like a function. + + ``func`` can be invoked as follows: + + .. code-block:: python + + import torch + import torch.nn as nn + from functorch import make_functional_with_buffers + + x = torch.randn(4, 3) + model = nn.Linear(3, 3) + func, params, buffers = make_functional_with_buffers(model) + func(params, buffers, x) + + And here is an example of applying the grad transform over the parameters + of a model: + + .. code-block:: python + + import torch + import torch.nn as nn + from functorch import make_functional_with_buffers, grad + + x = torch.randn(4, 3) + t = torch.randn(4, 3) + model = nn.Linear(3, 3) + func, params, buffers = make_functional_with_buffers(model) + + + def compute_loss(params, buffers, x, t): + y = func(params, buffers, x) + return nn.functional.mse_loss(y, t) + + + grad_weights = grad(compute_loss)(params, buffers, x, t) + + Args: + model (torch.nn.Module): Input model. + disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters. + The returned params are unrelated to the set of params from the original model. If False (default), + the params will have ``requires_grad=True`` on them (aka they will be trackable with regular + PyTorch autograd), matching the requires_grad-ness of the params from the original model. + Otherwise, the returned params will have ``requires_grad=False``. Default, False. + If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or + ``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``. + Otherwise, if you're only planning on using functorch's gradient transforms, + then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking + history with PyTorch autograd. + + """ + return FunctionalModuleWithBuffers._create_from( + model, disable_autograd_tracking=disable_autograd_tracking + ) + + +def transpose_stack( + tuple_of_tuple_of_tensors: tuple[tuple[Tensor, ...], ...], +) -> tuple[Tensor, ...]: + tuple_of_tuple_of_tensors = tuple(zip(*tuple_of_tuple_of_tensors)) + results = tuple( + torch.stack(shards).detach() for shards in tuple_of_tuple_of_tensors + ) + return results + + +def combine_state_for_ensemble( + models: Sequence[nn.Module], +) -> tuple[FunctionalModuleWithBuffers, tuple[Tensor, ...], tuple[Tensor, ...]]: + """combine_state_for_ensemble(models) -> func, params, buffers + + Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`. + + Given a list of ``M`` ``nn.Modules`` of the same class, stacks all of their + parameters and buffers together to make ``params`` and ``buffers``. + Each parameter and buffer in the result will have an additional dimension + of size ``M``. + + :func:`combine_state_for_ensemble` also returns ``func``, a functional + version of one of the models in :attr:`models`. One cannot directly run + ``func(params, buffers, *args, **kwargs)`` directly, you probably want to + use ``vmap(func, ...)(params, buffers, *args, **kwargs)`` + + Here's an example of how to ensemble over a very simple model: + + .. code-block:: python + + num_models = 5 + batch_size = 64 + in_features, out_features = 3, 3 + models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)] + data = torch.randn(batch_size, 3) + + fmodel, params, buffers = combine_state_for_ensemble(models) + output = vmap(fmodel, (0, 0, None))(params, buffers, data) + + assert output.shape == (num_models, batch_size, out_features) + + .. warning:: + All of the modules being stacked together must be the same (except for + the values of their parameters/buffers). For example, they should be in the + same mode (training vs eval). + + This API is subject to change -- we're investigating better ways to + create ensembles and would love your feedback how to improve this. + """ + if len(models) == 0: + raise RuntimeError( + "combine_state_for_ensemble: Expected at least one model, got 0." + ) + if not (all(m.training for m in models) or all(not m.training for m in models)): + raise RuntimeError( + "combine_state_for_ensemble: Expected all models to " + "have the same training/eval mode." + ) + model0_typ = type(models[0]) + if not all(type(m) is model0_typ for m in models): + raise RuntimeError( + "combine_state_for_ensemble: Expected all models to be of the same class." + ) + funcs, params, buffers = zip( + *[make_functional_with_buffers(model) for model in models] + ) + params = transpose_stack(params) + buffers = transpose_stack(buffers) + return funcs[0], params, buffers + + +def functional_init( + model_class: type[nn.Module], + ensemble_shape: tuple[()] | tuple[int, ...] = (), + device: torch.types.Device = "cpu", +) -> Callable[..., tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]]: + def wrapped( + *args: Any, **kwargs: Any + ) -> tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]]: + if len(ensemble_shape) >= 2: + raise ValueError("NYI: ensemble_shape with more than 1 element") + if len(ensemble_shape) == 0: + model = model_class(*args, **kwargs).to(device) + return make_functional_deprecated_v1(model) + num_models = ensemble_shape[0] # type: ignore[misc] + if num_models <= 0: + raise ValueError(f"num_models {num_models} should be > 0") + # NB: Not very efficient, more of a POC + models = tuple( + model_class(*args, **kwargs).to(device) for _ in range(num_models) + ) + _, fn, names = make_functional_deprecated_v1(model_class(*args, **kwargs)) + weights = tuple(make_functional_deprecated_v1(model)[0] for model in models) + weights = tuple(zip(*weights)) + weights = tuple(torch.stack(shards).detach() for shards in weights) + return weights, fn, names + + return wrapped + + +def functional_init_with_buffers( + model_class: type[nn.Module], + ensemble_shape: tuple[()] | tuple[int, ...] = (), + device: torch.types.Device = "cpu", +) -> Callable[ + ..., + tuple[ + tuple[Tensor, ...], + tuple[Tensor, ...], + Callable[..., Any], + tuple[str, ...], + tuple[str, ...], + ] + | tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]], +]: + def wrapped( + *args: Any, **kwargs: Any + ) -> ( + tuple[ + tuple[Tensor, ...], + tuple[Tensor, ...], + Callable[..., Any], + tuple[str, ...], + tuple[str, ...], + ] + | tuple[tuple[Tensor, ...], Callable[..., Any], tuple[str, ...]] + ): + if len(ensemble_shape) >= 2: + raise ValueError("NYI: ensemble_shape with more than 1 element") + if len(ensemble_shape) == 0: + model = model_class(*args, **kwargs).to(device) + return make_functional_deprecated_v1(model) + num_models = ensemble_shape[0] # type: ignore[misc] + if num_models <= 0: + raise ValueError(f"num_models {num_models} should be > 0") + # NB: Not very efficient, more of a POC + models = tuple( + model_class(*args, **kwargs).to(device) for _ in range(num_models) + ) + ( + _, + _, + fn, + weight_names, + buffer_names, + ) = make_functional_with_buffers_deprecated_v1(model_class(*args, **kwargs)) + weights, buffers = zip( + *tuple( + make_functional_with_buffers_deprecated_v1(model)[:2] + for model in models + ) + ) + weights = tuple(zip(*weights)) + weights = tuple(torch.stack(shards).detach() for shards in weights) + buffers = tuple(zip(*buffers)) + buffers = tuple(torch.stack(shards).detach() for shards in buffers) + return weights, buffers, fn, weight_names, buffer_names + + return wrapped diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/partitioners.py b/.venv/lib/python3.12/site-packages/torch/_functorch/partitioners.py new file mode 100644 index 0000000000000000000000000000000000000000..528f27550aa8acc31afd437d469f09f5e8d495aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/partitioners.py @@ -0,0 +1,4407 @@ +from __future__ import annotations + +import copy +import functools +import hashlib +import heapq +import itertools +import logging +import math +import operator +import os +import os.path +import re +import warnings +from collections import defaultdict, deque +from collections.abc import Callable, Iterator +from dataclasses import dataclass, replace +from typing import Any, cast, TYPE_CHECKING + +import sympy + +import torch +import torch._inductor.inductor_prims +import torch.distributed +import torch.fx as fx +import torch.utils._pytree as pytree +from torch._dynamo.utils import counters, is_node_meta_valid +from torch._functorch._activation_checkpointing.ac_logging_utils import ( + create_structured_trace_for_min_cut_info, +) +from torch._functorch._aot_autograd.streams import _SYNC_OPS +from torch._functorch._aot_autograd.utils import is_with_effects +from torch._inductor import config as inductor_config +from torch._inductor.custom_graph_pass import ( + CustomKnapsackSolver, + CustomRuntimeEstimator, +) +from torch._inductor.fx_passes.control_dependencies import ( + control_deps as control_deps_hop, + get_subgraph_name, +) +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_opaque_value +from torch._library.utils import is_builtin +from torch._logging import LazyString, trace_structured +from torch._logging._internal import trace_log +from torch._subclasses.fake_tensor import extract_tensor_metadata +from torch._subclasses.meta_utils import is_sparse_any +from torch.fx.experimental._backward_state import BackwardState +from torch.fx.experimental.proxy_tensor import is_sym_node, py_sym_types +from torch.fx.experimental.sym_node import magic_methods, method_to_operator, SymNode +from torch.fx.experimental.symbolic_shapes import ( + _get_placeholder_expr, + find_symbol_binding_fx_nodes, + free_symbols, + is_symbol_binding_fx_node, + is_symbolic, + optimization_hint, + statically_known_false, + statically_known_true, +) +from torch.fx.passes import graph_drawer +from torch.fx.traceback import _get_memory_budget_annotation +from torch.utils._ordered_set import OrderedSet +from torch.utils.checkpoint import CheckpointPolicy + +from . import config +from ._activation_checkpointing.graph_info_provider import GraphInfoProvider +from ._activation_checkpointing.knapsack import ( + dp_knapsack, + dp_knapsack_sliding_hirschberg, + greedy_knapsack, + ilp_knapsack, +) +from ._activation_checkpointing.knapsack_evaluator import KnapsackEvaluator +from ._aot_autograd.descriptors import ( + AOTOutput, + SavedForBackwardsAOTOutput, + SavedForBackwardsNoVcCheckAOTOutput, +) +from ._aot_autograd.functional_utils import _is_functional_graph +from ._aot_autograd.graph_compile import is_opaque_node +from ._aot_autograd.logging_utils import get_aot_graph_name +from ._aot_autograd.utils import ( + _is_bwd_seed_offset, + _is_fwd_seed_offset, + _is_primal, + _is_tangent, + get_default_generator, + get_device_rng_state, + supports_graphsafe_rng, +) +from .compile_utils import fx_graph_cse, get_aten_target, raise_getitems + + +if TYPE_CHECKING: + import networkx as nx + + +AOT_PARTITIONER_DEBUG: bool = config.debug_partitioner +log: logging.Logger = logging.getLogger(__name__) + +aten = torch.ops.aten +prims = torch.ops.prims + + +@dataclass +class OpTypes: + """Class for keeping track of different operator categories""" + + fusible_ops: OrderedSet[Callable[..., Any]] + compute_intensive_ops: OrderedSet[Callable[..., Any]] + random_ops: OrderedSet[Callable[..., Any]] + view_ops: OrderedSet[Callable[..., Any]] + recomputable_ops: OrderedSet[Callable[..., Any]] + + def is_fusible(self, node: fx.Node) -> bool: + return get_aten_target(node) in self.fusible_ops + + def is_compute_intensive(self, node: fx.Node) -> bool: + return get_aten_target(node) in self.compute_intensive_ops + + def is_random(self, node: fx.Node) -> bool: + return get_aten_target(node) in self.random_ops + + def is_view(self, node: fx.Node) -> bool: + return get_aten_target(node) in self.view_ops + + def is_recomputable(self, node: fx.Node) -> bool: + return get_aten_target(node) in self.recomputable_ops + + +@dataclass +class NodeInfo: + # Be careful about iterating over these explicitly, as their order may not + # be deterministic + inputs: list[fx.Node] + _required_fw_nodes: OrderedSet[fx.Node] + required_bw_nodes: OrderedSet[fx.Node] + tangents_closure: OrderedSet[fx.Node] + unclaimed_nodes: OrderedSet[fx.Node] + fw_order: dict[fx.Node, int] + # Effectively maps to which of our primals are parameters + static_lifetime_input_nodes: OrderedSet[fx.Node] + + @functools.cached_property + def required_fw_nodes(self) -> list[fx.Node]: + return sorted( + (n for n in self._required_fw_nodes), key=lambda n: self.fw_order[n] + ) + + def is_required_fw(self, n: fx.Node) -> bool: + return n in self._required_fw_nodes + + def is_required_bw(self, n: fx.Node) -> bool: + return n in self.required_bw_nodes + + def is_unclaimed(self, n: fx.Node) -> bool: + return n in self.unclaimed_nodes + + def get_fw_order(self, n: fx.Node) -> int: + if n not in self._required_fw_nodes: + raise AssertionError(f"Node {n} not in fw nodes!") + return self.fw_order[n] + + +@dataclass +class MinCutOptions: + ban_if_used_far_apart: bool + ban_if_long_fusible_chains: bool + ban_if_materialized_backward: bool + ban_if_not_in_allowlist: bool + ban_if_reduction: bool + + +def must_recompute(node: fx.Node) -> bool: + return node.meta.get("recompute", None) in [ + CheckpointPolicy.MUST_RECOMPUTE, + CheckpointPolicy.PREFER_RECOMPUTE, + ] + + +def get_schema_arg_idx(target: object, arg_name: str) -> int | None: + """Return the positional schema index for an operator argument name.""" + if not isinstance(target, torch._ops.OpOverload): + return None + for idx, arg in enumerate(target._schema.arguments): + if arg.name == arg_name: + return idx + return None + + +def is_nonzero_dropout_sdpa(node: fx.Node) -> bool: + """Return True unless SDPA-family dropout is statically known to be disabled.""" + target = node.target + if not isinstance(target, torch._ops.OpOverload): + return True + + dropout_arg_idx = get_schema_arg_idx(target, "dropout_p") + if dropout_arg_idx is None: + return True + + dropout_arg = target._schema.arguments[dropout_arg_idx] + if len(node.args) > dropout_arg_idx: + dropout_p = node.args[dropout_arg_idx] + elif "dropout_p" in node.kwargs: + dropout_p = node.kwargs["dropout_p"] + elif dropout_arg.default_value is not None: + dropout_p = dropout_arg.default_value + else: + return True + + return not statically_known_true(cast(bool | torch.SymBool, dropout_p == 0.0)) + + +def is_rng_op(node: fx.Node) -> bool: + """Return True when a node's seeded nondeterminism cannot be statically ruled out.""" + if not ( + hasattr(node.target, "tags") + and torch.Tag.nondeterministic_seeded in node.target.tags + ): + return False + + if get_schema_arg_idx(node.target, "dropout_p") is not None: + return is_nonzero_dropout_sdpa(node) + + return True + + +def _is_assert_only_symbool(node: fx.Node) -> bool: + return ( + isinstance(node.meta.get("val"), torch.SymBool) + and len(node.users) > 0 + and all( + user.target is torch.ops.aten._assert_scalar.default for user in node.users + ) + ) + + +def has_recomputable_ops(fx_g: fx.GraphModule) -> bool: + for node in fx_g.graph.nodes: + if must_recompute(node): + return True + return False + + +def has_recomputable_rng_ops(fx_g: fx.GraphModule) -> bool: + for node in fx_g.graph.nodes: + if must_recompute(node) and is_rng_op(node): + return True + return False + + +def sym_node_size(node: fx.Node) -> int: + if isinstance(node.meta["val"], (torch.SymInt, torch.SymBool)): + return 1 + if not isinstance(node.meta["val"], torch.SymFloat): + raise AssertionError( + f"expected node.meta['val'] to be SymFloat, got {type(node.meta['val'])}" + ) + return 4 + + +class InvalidNodeBase: + def __repr__(self) -> str: + return "Invalid Node" + + +# Run DCE while overriding the definition of is_impure_node +def is_not_collective(node: fx.Node) -> bool: + return getattr(node.target, "namespace", None) != "_c10d_functional" + + +InvalidNode = InvalidNodeBase() + + +def _get_ho_op_original_input(getitem_node: fx.Node) -> fx.Node | None: + """Given a getitem node, check if it extracts from a higher-order op + that has kwargs mapping the key back to an original input. + + Returns the original input node if found, None otherwise. + """ + if getitem_node.target != operator.getitem: + return None + ho_result = getitem_node.args[0] + key = getitem_node.args[1] + if not isinstance(ho_result, fx.Node) or ho_result.op != "call_function": + return None + if "kwargs" not in ho_result.kwargs: + return None + kwargs = ho_result.kwargs["kwargs"] + # pyrefly: ignore [not-iterable, unsupported-operation] + if key not in kwargs: + return None + # pyrefly: ignore [bad-index, unsupported-operation] + original_input = kwargs[key] + if isinstance(original_input, fx.Node): + return original_input + return None + + +def _is_copy_node_bw_only(node: fx.Node) -> fx.Node | None: + """Check if node is a view/reshape of a higher-order op output that aliases an input. + + Returns the original input node from the higher-order op's kwargs if the pattern + matches, None otherwise. + """ + if node.target not in (torch.ops.aten.view.default, torch.ops.aten.reshape.default): + return None + source = node.args[0] + if not isinstance(source, fx.Node): + return None + return _get_ho_op_original_input(source) + + +def _find_input_for_invalid_output( + node: fx.Node, + env: dict[fx.Node, Any], +) -> fx.Node | None: + """Try to find a valid input replacement for an invalid forward output. + + This handles cases where a forward output depends on backward nodes but + semantically aliases an input. For example, a view of a getitem from a + triton kernel that mutates a buffer in backward, or a direct getitem from + such a higher-order op. The original input may be a primal or a valid + intermediate node already present in the forward graph. + """ + # Pattern 1: view/reshape(getitem(ho_op, key)) -> ho_op.kwargs["kwargs"][key] + original_input = _is_copy_node_bw_only(node) + if ( + original_input is not None + and original_input in env + and not isinstance(env[original_input], InvalidNodeBase) + ): + return env[original_input] + # Pattern 2: getitem(ho_op, key) -> ho_op.kwargs["kwargs"][key] + original_input = _get_ho_op_original_input(node) + if ( + original_input is not None + and original_input in env + and not isinstance(env[original_input], InvalidNodeBase) + ): + return env[original_input] + return None + + +def _control_deps_has_sync_op(node: fx.Node) -> bool: + """Check if a control_deps node's subgraph has a sync operation.""" + sg_node = node.args[1] + if not ( + isinstance(sg_node, fx.Node) + and sg_node.op == "get_attr" + and isinstance(sg_node.target, str) + ): + raise AssertionError(f"expected get_attr subgraph node, got {sg_node}") + owning_mod = node.graph.owning_module + if owning_mod is None: + raise AssertionError("expected graph to have an owning_module") + sg_mod = getattr(owning_mod, sg_node.target) + if not isinstance(sg_mod, fx.GraphModule): + raise AssertionError(f"expected GraphModule, got {type(sg_mod)}") + return any( + n.op == "call_function" and n.target in _SYNC_OPS for n in sg_mod.graph.nodes + ) + + +def _build_see_through_map(cd_node: fx.Node) -> dict[int, fx.Node]: + """Build a mapping from getitem indices to underlying dep nodes. + + For a control_deps(additional_deps, subgraph, *deps), getitem index k + (k >= 1) corresponds to deps[k-1] which is args[k+1]. + """ + deps = cd_node.args[2:] + return {i + 1: dep for i, dep in enumerate(deps) if isinstance(dep, fx.Node)} + + +def _try_clone_subgraph_filtering_deps( + original_sg_mod: fx.GraphModule, + valid_dep_indices: list[int], +) -> tuple[fx.Graph, dict[int, int]] | None: + """Clone a control_deps subgraph, keeping only valid-dep placeholders. + + Preserves any call_function nodes (the side-effecting operation) as long + as all placeholders they reference are in the valid set. Returns + (new_graph, idx_remap) where idx_remap maps old getitem indices to new + ones, or None if the operation uses an invalid dep. + """ + orig_phs = original_sg_mod.graph.find_nodes(op="placeholder") + valid_dep_set = OrderedSet(valid_dep_indices) + dropped_phs = OrderedSet( + [ph for i, ph in enumerate(orig_phs) if i not in valid_dep_set] + ) + + for n in original_sg_mod.graph.nodes: + if n.op == "call_function": + if any(inp in dropped_phs for inp in n.all_input_nodes): + return None + + sg = fx.Graph() + sg_env: dict[fx.Node, fx.Node] = {} + for n in original_sg_mod.graph.nodes: + if n.op == "output" or n in dropped_phs: + continue + sg_env[n] = sg.node_copy(n, lambda x, _env=sg_env: _env[x]) + + orig_out_arg = original_sg_mod.graph.output_node().args[0] + if isinstance(orig_out_arg, tuple): + sg.output( + tuple( + sg_env[item] if isinstance(item, fx.Node) else item + for item in orig_out_arg + if not isinstance(item, fx.Node) or item in sg_env + ) + ) + elif isinstance(orig_out_arg, fx.Node) and orig_out_arg in sg_env: + sg.output(sg_env[orig_out_arg]) + else: + sg.output(orig_out_arg) + + preserved_op = any(n.op == "call_function" for n in sg.nodes) + idx_remap: dict[int, int] = { + old_i + 1: new_j + 1 for new_j, old_i in enumerate(valid_dep_indices) + } + if preserved_op: + idx_remap[0] = 0 + return sg, idx_remap + + +def _rebuild_control_deps_for_extract( + node: fx.Node, + env: dict[fx.Node, Any], + new_graph: fx.Graph, +) -> tuple[fx.Node, dict[int, int]] | None: + """Rebuild a control_deps node with only valid deps for graph extraction. + + When a control_deps node mixes valid (forward) and invalid (backward) args, + this creates a new control_deps in new_graph with only the valid deps and a + matching subgraph. Returns (new_node, idx_remap) where idx_remap maps old + getitem indices to new getitem indices, or None if no valid deps remain. + + additional_deps (args[0]) and deps (args[2:]) are filtered independently -- + additional_deps are ordering-only constraints and may reference nodes that + are not in the deps set. + """ + deps = node.args[2:] + valid_dep_indices = [ + i + for i, dep in enumerate(deps) + if isinstance(dep, fx.Node) and not isinstance(env.get(dep), InvalidNodeBase) + ] + if not valid_dep_indices: + return None + + # pyrefly: ignore [bad-index] + new_deps = tuple(env[deps[i]] for i in valid_dep_indices) + + additional_deps = node.args[0] + if not isinstance(additional_deps, (tuple, list)): + raise AssertionError( + f"expected tuple/list additional_deps, got {type(additional_deps)}" + ) + valid_additional_deps = tuple( + env[d] + for d in additional_deps + if isinstance(d, fx.Node) and not isinstance(env.get(d), InvalidNodeBase) + ) + + owning_mod = node.graph.owning_module + if owning_mod is None: + raise AssertionError("expected graph to have an owning_module") + + sg_node = node.args[1] + if not ( + isinstance(sg_node, fx.Node) + and sg_node.op == "get_attr" + and isinstance(sg_node.target, str) + ): + raise AssertionError(f"expected get_attr subgraph node, got {sg_node}") + original_sg_mod = getattr(owning_mod, sg_node.target) + if not isinstance(original_sg_mod, fx.GraphModule): + raise AssertionError(f"expected GraphModule, got {type(original_sg_mod)}") + + result = _try_clone_subgraph_filtering_deps(original_sg_mod, valid_dep_indices) + if result is not None: + sg, idx_remap = result + else: + sg = fx.Graph() + sg_placeholders = [sg.placeholder(f"dep_{i}") for i in range(len(new_deps))] + sg.output((None, *sg_placeholders)) + idx_remap = { + old_i + 1: new_j + 1 for new_j, old_i in enumerate(valid_dep_indices) + } + + sg_name = get_subgraph_name(owning_mod, "cd_extract") + setattr(owning_mod, sg_name, fx.GraphModule(torch.nn.Module(), sg)) + new_sg_node = new_graph.get_attr(sg_name) + + new_cd = new_graph.create_node( + "call_function", + control_deps_hop, + args=(valid_additional_deps, new_sg_node, *new_deps), + name=node.name, + ) + new_cd.meta = node.meta.copy() + if "val" in node.meta and isinstance(node.meta["val"], tuple): + orig_val = node.meta["val"] + new_cd.meta["val"] = (orig_val[0],) + tuple( + orig_val[i + 1] for i in valid_dep_indices if i + 1 < len(orig_val) + ) + + return new_cd, idx_remap + + +def _extract_graph_with_inputs_outputs( + joint_graph: fx.Graph, + inputs: list[fx.Node], + outputs: list[fx.Node], + outputs_descs: list[AOTOutput], + subgraph: str | None = None, + ignore_must_be_in_fw_bw: bool = False, +) -> fx.Graph: + """ + Given a graph, extracts out a subgraph that takes the specified nodes as + inputs and returns the specified outputs. + + This includes specifying non-placeholder nodes as inputs. + + The general strategy is to initialize all inputs with proxies as we + encounter them, and trace through the graph, only keeping values which take + in valid proxies. Then, all dead code is eliminated. + """ + new_graph = fx.Graph() + env: dict[fx.Node, fx.Node] = {} + # For control_deps nodes with mixed valid/invalid args, we create a new + # control_deps with only the valid deps. This dict maps the original + # control_deps node to a {old_getitem_idx: new_getitem_idx} remapping so + # downstream getitem nodes can be rewritten to the correct indices. + _control_deps_idx_remap: dict[fx.Node, dict[int, int]] = {} + # For forward sync control_deps eliminated during backward extraction, + # maps the control_deps node to {getitem_idx: joint_graph_dep_node}. + # Getitems resolve directly to env[dep_node], bypassing the control_deps. + _control_deps_see_through: dict[fx.Node, dict[int, fx.Node]] = {} + + # Add new placeholder nodes in the order specified by the inputs + for node in inputs: + new_node = new_graph.placeholder(node.name) + # Can't use node_copy here as we may be turning previous call_function into placeholders + new_node.meta = node.meta + # pyrefly: ignore [unsupported-operation] + env[node] = new_node + + for node in joint_graph.nodes: + if not ignore_must_be_in_fw_bw: + if ( + _must_be_in_backward(node) + and subgraph != "backward" + and node not in inputs + ): + env[node] = InvalidNode # type: ignore[assignment] + continue + + if ( + _must_be_in_forward(node) + and subgraph != "forward" + and node not in inputs + ): + env[node] = InvalidNode # type: ignore[assignment] + continue + + if node in env: + # Node must be one of our inputs. (Any member of env which wasn't an + # input to start must have been created by this loop and won't be in + # joint_graph.nodes). + continue + elif node.op == "placeholder": + env[node] = InvalidNode # type: ignore[assignment] + elif node.op == "call_function": + if ( + node.target is operator.getitem + and node.args[0] in _control_deps_see_through + ): + dep_map = _control_deps_see_through[node.args[0]] + idx = node.args[1] + if idx in dep_map: + env[node] = env[dep_map[idx]] + else: + env[node] = InvalidNode # type: ignore[assignment] + continue + if ( + node.target is operator.getitem + and node.args[0] in _control_deps_idx_remap + ): + idx_map = _control_deps_idx_remap[node.args[0]] + idx = node.args[1] + if idx in idx_map: + new_idx = idx_map[idx] + new_getitem = new_graph.create_node( + "call_function", + operator.getitem, + args=(env[node.args[0]], new_idx), + name=node.name, + ) + new_getitem.meta = node.meta + env[node] = new_getitem + else: + env[node] = InvalidNode # type: ignore[assignment] + continue + + all_args = pytree.arg_tree_leaves(*node.args, **node.kwargs) + all_args = [ + isinstance(env[x], InvalidNodeBase) + for x in all_args + if isinstance(x, fx.Node) + ] + if any(all_args): + if node.target is control_deps_hop: + # During backward extraction, eliminate forward sync + # control_deps entirely -- their subgraphs reference + # forward-only runtime state (streams/events) that is + # dead at backward time. Getitems are resolved directly + # to the underlying deps via _control_deps_see_through. + if ( + subgraph == "backward" + and not ( + _has_tag_is_backward(node) + or _has_tag_must_be_in_backward(node) + ) + and _control_deps_has_sync_op(node) + ): + _control_deps_see_through[node] = _build_see_through_map(node) + env[node] = InvalidNode # type: ignore[assignment] + continue + new_cd_node = _rebuild_control_deps_for_extract( + node, env, new_graph + ) + if new_cd_node is not None: + env[node] = new_cd_node[0] + _control_deps_idx_remap[node] = new_cd_node[1] + continue + env[node] = InvalidNode # type: ignore[assignment] + continue + # During backward extraction, eliminate forward sync control_deps + # entirely. See above for rationale. + if ( + node.target is control_deps_hop + and subgraph == "backward" + and not ( + _has_tag_is_backward(node) or _has_tag_must_be_in_backward(node) + ) + and _control_deps_has_sync_op(node) + ): + _control_deps_see_through[node] = _build_see_through_map(node) + env[node] = InvalidNode # type: ignore[assignment] + continue + # pyrefly: ignore [unsupported-operation, bad-argument-type] + env[node] = new_graph.node_copy(node, lambda x: env[x]) + elif node.op == "get_attr": + # pyrefly: ignore [unsupported-operation, bad-argument-type] + env[node] = new_graph.node_copy(node, lambda x: env[x]) + elif node.op == "output": + pass + output_values = [] + for x, x_desc in zip(outputs, outputs_descs): + if isinstance(x, fx.Node): + if x not in env: + raise RuntimeError(f"Node {x} couldn't be found in env") + if isinstance(env[x], InvalidNodeBase): + # For forward outputs that are invalid (depend on backward), try + # to find a valid replacement. + replacement = None + # For copy_ nodes that are backward-only, use the destination + # (first arg) which is the original input. + if ( + x.target is torch.ops.aten.copy_.default + and _must_be_in_backward(x) + and len(x.args) >= 1 + and isinstance(x.args[0], fx.Node) + and x.args[0] in env + and not isinstance(env[x.args[0]], InvalidNodeBase) + ): + replacement = env[x.args[0]] + # For view/reshape outputs that trace back to a getitem of a + # higher-order op that mutates an input, find that input. + # This handles custom_function_view outputs from triton kernels. + if replacement is None: + replacement = _find_input_for_invalid_output(x, env) + if replacement is not None: + output_values.append(replacement) + continue + raise AssertionError(f"Node {x} was invalid, but is output") + output_values.append(env[x]) + else: + output_values.append(x) + out = new_graph.output(tuple(output_values)) + out.meta["desc"] = outputs_descs + # Snapshot stack traces on the output node before passes run, + # as later passes may strip stack_trace from individual nodes. + out.meta["output_stack_traces"] = [ + v.meta.get("stack_trace") if isinstance(v, fx.Node) else None + for v in output_values + ] + + new_graph.eliminate_dead_code() + new_graph.lint() + return new_graph + + +def is_non_builtin_to_include(node: fx.Node) -> bool: + return config.is_non_builtin_to_include and ( + (isinstance(node.target, torch._ops.OpOverload) and not is_builtin(node.target)) + or node.target == torch.ops.higher_order.triton_kernel_wrapper_functional + ) + + +def _is_backward_state(node: fx.Node) -> bool: + return node.op == "placeholder" and isinstance(node.meta.get("val"), BackwardState) + + +def _has_tag_is_backward(node: fx.Node) -> bool: + return node.meta.get("partitioner_tag", None) == "is_backward" + + +def _has_tag_is_forward(node: fx.Node) -> bool: + return node.meta.get("partitioner_tag", None) == "is_forward" + + +def _has_tag_must_be_in_forward(node: fx.Node) -> bool: + return node.meta.get("partitioner_tag", None) == "must_be_in_forward" + + +def _has_tag_must_be_in_backward(node: fx.Node) -> bool: + return node.meta.get("partitioner_tag", None) == "must_be_in_backward" + + +def _must_be_in_forward(node: fx.Node) -> bool: + if _has_tag_must_be_in_forward(node): + return True + + is_mutable = ( + isinstance(node.target, torch._ops.OpOverload) + and node.target._schema.is_mutable + ) + return ( + not _has_tag_is_backward(node) + and not _has_tag_must_be_in_backward(node) + and is_mutable + ) + + +def _must_be_in_backward(node: fx.Node) -> bool: + if _has_tag_must_be_in_backward(node): + return True + is_mutable = ( + isinstance(node.target, torch._ops.OpOverload) + and node.target._schema.is_mutable + ) + return _has_tag_is_backward(node) and is_mutable + + +def _iter_input_exprs_without_replacements(val: Any) -> Iterator[sympy.Basic]: + # Keep this traversal in sync with symbolic_shapes._iterate_exprs. + if isinstance(val, py_sym_types): + if is_symbolic(val): + yield _get_placeholder_expr(val.node) + elif isinstance(val, SymNode): + yield _get_placeholder_expr(val) + elif isinstance(val, sympy.Basic): + yield val + elif isinstance(val, (int, float, bool, str)): + pass + elif isinstance(val, (tuple, list)): + for s in val: + yield from _iter_input_exprs_without_replacements(s) + elif isinstance(val, dict): + for s in itertools.chain(val.keys(), val.values()): + yield from _iter_input_exprs_without_replacements(s) + elif is_sparse_any(val): + yield from _iter_input_exprs_without_replacements(val.size()) + elif isinstance(val, torch.Tensor): + yield from _iter_input_exprs_without_replacements(val.size()) + yield from _iter_input_exprs_without_replacements(val.stride()) + yield from _iter_input_exprs_without_replacements(val.storage_offset()) + elif val is None: + pass + elif isinstance(val, torch.Generator) or is_opaque_value(val): + pass + elif isinstance(val, FakeScriptObject): + pass + else: + raise AssertionError(f"cannot extract sympy expressions from {val} {type(val)}") + + +def _free_symbols_without_replacements(val: Any) -> OrderedSet[sympy.Symbol]: + symbols: OrderedSet[sympy.Symbol] = OrderedSet() + for expr in _iter_input_exprs_without_replacements(val): + symbols.update(expr.free_symbols) + return symbols + + +def _extract_fwd_bwd_outputs( + joint_module: fx.GraphModule, *, num_fwd_outputs: int +) -> tuple[list[fx.Node], list[fx.Node], list[AOTOutput], list[AOTOutput]]: + outputs = pytree.arg_tree_leaves( + *(node.args for node in joint_module.graph.find_nodes(op="output")) + ) + outputs_descs = pytree.arg_tree_leaves( + next(iter(joint_module.graph.find_nodes(op="output"))).meta.get( + "desc", [None] * len(outputs) + ) + ) + fwd_outputs = outputs[:num_fwd_outputs] + bwd_outputs = outputs[num_fwd_outputs:] + fwd_outputs_descs = outputs_descs[:num_fwd_outputs] + bwd_outputs_descs = outputs_descs[num_fwd_outputs:] + return fwd_outputs, bwd_outputs, fwd_outputs_descs, bwd_outputs_descs + + +def _remove_by_name(saved_values: list[fx.Node], name: str) -> None: + for saved_value in saved_values: + if saved_value.name == name: + saved_values.remove(saved_value) + break + + +def find_first_sym_node( + fwd_module_outputs: list[fx.Node] | tuple[fx.Node, ...], +) -> int: + idx = len(fwd_module_outputs) + for i in range(len(fwd_module_outputs) - 1, -1, -1): + if not is_sym_node(fwd_module_outputs[i]): + idx = i + 1 + break + return idx + + +def calculate_quantization_scaling( + graph: torch.fx.Graph, + node: torch.fx.Node, + max: float = 57344.0, + min: float = 1e-12, + position: int = 0, +) -> torch.fx.Node: + with graph.inserting_after(node): + abs_node = graph.call_function( + torch.ops.aten.abs.default, + args=(node,), + ) + abs_node.meta["val"] = torch.ops.aten.abs.default(node.meta["val"]) + abs_node.meta["tensor_meta"] = extract_tensor_metadata(abs_node.meta["val"]) + with graph.inserting_after(abs_node): + amax_node = graph.call_function( + torch.ops.aten.amax.default, + args=(abs_node, [-1], True), + ) + amax_node.meta["val"] = torch.ops.aten.amax.default( + abs_node.meta["val"], [-1], True + ) + amax_node.meta["tensor_meta"] = extract_tensor_metadata(amax_node.meta["val"]) + with graph.inserting_after(amax_node): + amax_64_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(amax_node, torch.float64), + ) + amax_64_node.meta["val"] = torch.ops.prims.convert_element_type.default( + amax_node.meta["val"], torch.float64 + ) + amax_64_node.meta["tensor_meta"] = extract_tensor_metadata( + amax_64_node.meta["val"] + ) + with graph.inserting_after(amax_64_node): + clamp_min_node = graph.call_function( + torch.ops.aten.clamp_min.default, + args=(amax_64_node, min), + ) + clamp_min_node.meta["val"] = torch.ops.aten.clamp_min.default( + amax_64_node.meta["val"], min + ) + clamp_min_node.meta["tensor_meta"] = extract_tensor_metadata( + clamp_min_node.meta["val"] + ) + with graph.inserting_after(clamp_min_node): + reciprocal_node = graph.call_function( + torch.ops.aten.reciprocal.default, + args=(clamp_min_node,), + ) + reciprocal_node.meta["val"] = torch.ops.aten.reciprocal.default( + clamp_min_node.meta["val"] + ) + reciprocal_node.meta["tensor_meta"] = extract_tensor_metadata( + reciprocal_node.meta["val"] + ) + with graph.inserting_after(reciprocal_node): + mul_node = graph.call_function( + torch.ops.aten.mul.Tensor, + args=(reciprocal_node, max), + ) + mul_node.meta["val"] = torch.ops.aten.mul.Tensor( + reciprocal_node.meta["val"], max + ) + mul_node.meta["tensor_meta"] = extract_tensor_metadata(mul_node.meta["val"]) + with graph.inserting_after(mul_node): + scale_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(mul_node, torch.float32), + name=f"fp8_scale_pos_{position}_{node.name}", + ) + scale_node.meta["val"] = torch.ops.prims.convert_element_type.default( + mul_node.meta["val"], torch.float32 + ) + scale_node.meta["tensor_meta"] = extract_tensor_metadata(scale_node.meta["val"]) + return scale_node + + +def perform_quantization( + graph: torch.fx.Graph, + node: torch.fx.Node, + scale_node: torch.fx.Node, + quant_type: torch.dtype, + clamp_min: float, + clamp_max: float, + position: int, +) -> torch.fx.Node: + with graph.inserting_after(scale_node): + target_node_32 = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(node, torch.float32), + ) + target_node_32.meta["val"] = torch.ops.prims.convert_element_type.default( + node.meta["val"], torch.float32 + ) + target_node_32.meta["tensor_meta"] = extract_tensor_metadata( + target_node_32.meta["val"] + ) + with graph.inserting_after(target_node_32): + scaled_target_node = graph.call_function( + torch.ops.aten.mul.Tensor, + args=(target_node_32, scale_node), + ) + scaled_target_node.meta["val"] = torch.ops.aten.mul.Tensor( + target_node_32.meta["val"], scale_node.meta["val"] + ) + scaled_target_node.meta["tensor_meta"] = extract_tensor_metadata( + scaled_target_node.meta["val"] + ) + with graph.inserting_after(scaled_target_node): + clamp_min_scaled_node = graph.call_function( + torch.ops.aten.clamp_min.default, + args=(scaled_target_node, clamp_min), + ) + clamp_min_scaled_node.meta["val"] = torch.ops.aten.clamp_min.default( + scaled_target_node.meta["val"], clamp_min + ) + clamp_min_scaled_node.meta["tensor_meta"] = extract_tensor_metadata( + clamp_min_scaled_node.meta["val"] + ) + with graph.inserting_after(clamp_min_scaled_node): + clamp_max_scaled_node = graph.call_function( + torch.ops.aten.clamp_max.default, + args=(clamp_min_scaled_node, clamp_max), + ) + clamp_max_scaled_node.meta["val"] = torch.ops.aten.clamp_max.default( + clamp_min_scaled_node.meta["val"], clamp_max + ) + clamp_max_scaled_node.meta["tensor_meta"] = extract_tensor_metadata( + clamp_max_scaled_node.meta["val"] + ) + with graph.inserting_after(clamp_max_scaled_node): + quant_activation_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(clamp_max_scaled_node, quant_type), + name=f"fp8_quant_pos_{position}_{node.name}", + ) + quant_activation_node.meta["val"] = ( + torch.ops.prims.convert_element_type.default( + clamp_max_scaled_node.meta["val"], quant_type + ) + ) + quant_activation_node.meta["tensor_meta"] = extract_tensor_metadata( + quant_activation_node.meta["val"] + ) + return quant_activation_node + + +def calculate_tensor_size(tensor: torch.Tensor) -> float: + """ + Calculate the size of a PyTorch tensor in megabytes (MB). + + Args: + tensor (torch.Tensor): Input tensor + + Returns: + float: Memory size in MB + """ + # Get number of elements and size per element + num_elements = tensor.numel() + element_size = tensor.element_size() + + return (num_elements * element_size) / (1024 * 1024) + + +def get_allowed_dtypes() -> list[torch.dtype]: + allowed_dtypes = torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("allowed_dtypes", "torch.bfloat16") + allowed_dtypes = [ + getattr(torch, dtype.split(".")[-1]) for dtype in allowed_dtypes.split(";") + ] + return allowed_dtypes + + +def should_quantize(node: torch.fx.Node) -> bool: + allowed_dtypes = get_allowed_dtypes() + if not is_node_meta_valid(node) or node.meta["val"].dtype not in allowed_dtypes: + return False + size_threshold = torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("size_in_mb", 100) + # calculate the size of the node + size_in_mb = calculate_tensor_size(node.meta["val"]) + if not torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("skip_dynamo_guards", False): + return size_in_mb >= size_threshold + else: + # case 1: we always quantize tensors with dynamic shapes + if torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("quantize_dynamic_shape", False): + return statically_known_true( + size_in_mb >= size_threshold + ) or not statically_known_false(size_in_mb >= size_threshold) + else: + # case 2: we always not quantize tensors with dynamic shapes + return statically_known_true(size_in_mb >= size_threshold) + + +def get_quant_type() -> torch.dtype: + quant_type = torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("quant_type", "torch.float8_e5m2") + + return getattr(torch, quant_type.split(".")[-1]) + + +def calculate_range(dtype: torch.dtype) -> tuple[float, float]: + """ + Calculate the range of values for a given torch.dtype. + Args: + dtype (torch.dtype): The input dtype. + Returns: + tuple: A tuple containing the minimum and maximum values. + """ + info = torch.finfo(dtype) + return info.min, info.max + + +def quantize_activation_fw(graph: torch.fx.Graph, num_fwd_outputs: int = 0) -> None: + output = graph.find_nodes(op="output")[0] + fwd_outputs = output.args[0] + quant_type = get_quant_type() + clamp_min, clamp_max = calculate_range(quant_type) + position_to_quant = dict() + tensor_scale_nodes: list[fx.Node] = [] + sym_scale_nodes: list[fx.Node] = [] + for position, node in enumerate(fwd_outputs): + # Don't quantize user-visible forward outputs. A tensor may appear as + # both a user output and a saved-for-backward activation (same FX node + # at two positions). Quantizing the user output position would: + # 1. Return fp8 to the user instead of the original precision + # 2. Create duplicate fp8_quant/fp8_scale backward placeholders that + # shift the stride mapping in _aot_stage2b_bw_compile (T264303372) + if position < num_fwd_outputs: + continue + # check if the activation node is the node saved for quantization + if node.meta.get("saved_for_quantization", False): + # case: use scaling + if torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("use_scaling", True): + # calculating the scale + scale_node = calculate_quantization_scaling( + graph, node, clamp_max, 1e-12, position + ) + + # converting to fp8 + quant_node = perform_quantization( + graph, node, scale_node, quant_type, clamp_min, clamp_max, position + ) + if not is_sym_node(scale_node): + tensor_scale_nodes.append(scale_node) + else: + sym_scale_nodes.append(scale_node) + else: + # case: do not use scaling + with graph.inserting_after(node): + quant_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(node, quant_type), + name=f"fp8_quant_pos_{position}_{node.name}", + ) + quant_node.meta["val"] = ( + torch.ops.prims.convert_element_type.default( + node.meta["val"], quant_type + ) + ) + quant_node.meta["tensor_meta"] = extract_tensor_metadata( + quant_node.meta["val"] + ) + + position_to_quant[position] = quant_node + + # Use position-based lookup for building output + # only update the return node args, and remain all other users unchanged + output_updated_args = [ + position_to_quant.get(i, node) for i, node in enumerate(fwd_outputs) + ] + # add the scale nodes to the output find the first sym_node in the output + # pyrefly: ignore [bad-argument-type] + idx = find_first_sym_node(output_updated_args) + scale_nodes = tensor_scale_nodes + sym_scale_nodes + if scale_nodes: + output_updated_args = ( + output_updated_args[:idx] + scale_nodes + output_updated_args[idx:] + ) + + output.update_arg(0, tuple(output_updated_args)) + counters["inductor"]["activation_quantization_fwd_aten_pass"] += 1 + + +def quantize_activation_bw(graph: torch.fx.Graph) -> None: + bw_inputs = [node for node in graph.nodes if node.op == "placeholder"] + activation_node = None + for node in bw_inputs: + if node.meta.get("saved_for_quantization", False): + node.meta.pop("saved_for_quantization") + dequant_type = node.meta.pop("dequant_type") + # dequantize the node + if torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("use_scaling", False): + # case: use scaling + with graph.inserting_after(node): + # find corresponding scale node + scale_name = "fp8_scale_" + node.name.replace("fp8_quant_", "") + scale_node = next( + bwd_input + for bwd_input in bw_inputs + if bwd_input.name == scale_name + ) + with graph.inserting_after(scale_node): + activation_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(node, dequant_type), + ) + activation_node.meta["val"] = ( + torch.ops.prims.convert_element_type.default( + node.meta["val"], dequant_type + ) + ) + activation_node.meta["tensor_meta"] = extract_tensor_metadata( + activation_node.meta["val"] + ) + with graph.inserting_after(activation_node): + divided_target_node_32 = graph.call_function( + torch.ops.aten.div.Tensor, + args=(activation_node, scale_node), + ) + divided_target_node_32.meta["val"] = torch.ops.aten.div.Tensor( + activation_node.meta["val"], scale_node.meta["val"] + ) + divided_target_node_32.meta["tensor_meta"] = ( + extract_tensor_metadata(divided_target_node_32.meta["val"]) + ) + with graph.inserting_after(divided_target_node_32): + dequant_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(divided_target_node_32, dequant_type), + ) + dequant_node.meta["val"] = ( + torch.ops.prims.convert_element_type.default( + divided_target_node_32.meta["val"], dequant_type + ) + ) + dequant_node.meta["tensor_meta"] = extract_tensor_metadata( + dequant_node.meta["val"] + ) + else: + with graph.inserting_after(node): + dequant_node = graph.call_function( + torch.ops.prims.convert_element_type.default, + args=(node, dequant_type), + name="dequant_" + str(node.name), + ) + dequant_node.meta["val"] = ( + torch.ops.prims.convert_element_type.default( + node.meta["val"], dequant_type + ) + ) + dequant_node.meta["tensor_meta"] = extract_tensor_metadata( + dequant_node.meta["val"] + ) + # find the users of the node and replace them with the new node except the dequant_node + for user in list(node.users.keys()): + if user != dequant_node and user != activation_node: + user.replace_input_with(node, dequant_node) + + counters["inductor"]["activation_quantization_bwd_aten_pass"] += 1 + + +def perform_fp8_activation_quantization( + fwd_module: fx.GraphModule, + bwd_module: fx.GraphModule, + bwd_module_inputs: dict[str, fx.Node], + num_fwd_outputs: int = 0, +) -> None: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "before_activation_quantization_fwd_aten_pass", + "encoding": "string", + }, + payload_fn=lambda: fwd_module.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + quantize_activation_fw(fwd_module.graph, num_fwd_outputs) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "after_activation_quantization_fwd_aten_pass", + "encoding": "string", + }, + payload_fn=lambda: fwd_module.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "before_activation_quantization_bwd_aten_pass", + "encoding": "string", + }, + payload_fn=lambda: bwd_module.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + quant_fwd_module_outputs = fwd_module.graph.find_nodes(op="output")[0].args[0] + # update the corresponding bwd_inputs due to the fwd_outputs quantization + for fwd_node in quant_fwd_module_outputs: + if "fp8_quant_" in fwd_node.name: + bwd_input = bwd_module_inputs[ + re.sub(r"^fp8_quant_pos_\d+_", "", fwd_node.name) + ] + with bwd_module.graph.inserting_after(bwd_input): + quant_bwd_input = bwd_module.graph.placeholder(name=fwd_node.name) + dequant_type = bwd_input.meta["dequant_type"] + quant_bwd_input.meta.update(fwd_node.meta) + quant_bwd_input.meta["saved_for_quantization"] = True + quant_bwd_input.meta["dequant_type"] = dequant_type + bwd_input.replace_all_uses_with(quant_bwd_input) + bwd_module.graph.erase_node(bwd_input) + # update the bwd_inputs if quantization with scaling is used + if torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("use_scaling", True): + quant_bwd_module_inputs = list(bwd_module.graph.find_nodes(op="placeholder")) + # update the corresponding bwd input nodes find the last non-tangent node + bwd_input_loc = quant_bwd_module_inputs[-1] + for bw_input in reversed(quant_bwd_module_inputs): + if not _is_tangent(bw_input): + bwd_input_loc = bw_input + break + + scaled_fwd_module_outputs = fwd_module.graph.find_nodes(op="output")[0].args[0] + for fwd_node in scaled_fwd_module_outputs: + if "fp8_scale_" in fwd_node.name: + # fwd node is a scale node + with bwd_module.graph.inserting_after(bwd_input_loc): + scale_bwd_input = bwd_module.graph.placeholder(name=fwd_node.name) + scale_bwd_input.meta.update(fwd_node.meta) + bwd_input_loc = scale_bwd_input + + quantize_activation_bw(bwd_module.graph) + + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "after_activation_quantization_bwd_aten_pass", + "encoding": "string", + }, + payload_fn=lambda: bwd_module.print_readable( + print_output=False, include_stride=True, include_device=True + ), + ) + + +def enable_activation_quantization( + saved_values: list[fx.Node], + fwd_module: fx.GraphModule, + bwd_module: fx.GraphModule, + static_lifetime_input_nodes: OrderedSet[fx.Node] | None = None, + num_fwd_outputs: int = 0, +) -> None: + static_input_names: list[str] = ( + [node.name for node in static_lifetime_input_nodes] + if static_lifetime_input_nodes + else [] + ) + saved_values_names = {node.name: node for node in saved_values} + if torch._inductor.config.post_grad_fusion_options[ + "activation_quantization_aten_pass" + ].get("exclude_primals", False): + saved_values_names = { + node.name: node for node in saved_values if "primals" not in node.name + } + fwd_module_outputs = fwd_module.graph.find_nodes(op="output")[0].args[0] + bwd_module_inputs = { + node.name: node for node in bwd_module.graph.find_nodes(op="placeholder") + } + should_perform_fp8_quant = False + for node in fwd_module_outputs: + if node.name in saved_values_names and should_quantize(node): + if node.name in static_input_names: + log.debug("Skipping quantization of static input %s: ", node.name) + continue + node.meta["saved_for_quantization"] = True + node.meta["dequant_type"] = node.meta["val"].dtype + # some of the fwd outputs and bwd inputs are not share the same object + bwd_module_inputs[node.name].meta["saved_for_quantization"] = True + bwd_module_inputs[node.name].meta["dequant_type"] = node.meta["val"].dtype + should_perform_fp8_quant = True + + if should_perform_fp8_quant: + perform_fp8_activation_quantization( + fwd_module, bwd_module, bwd_module_inputs, num_fwd_outputs + ) + + +def _extract_fwd_bwd_modules( + joint_module: fx.GraphModule, + saved_values: list[fx.Node], + saved_sym_nodes: list[fx.Node], + saved_opaque_nodes: list[fx.Node] | None = None, + *, + num_fwd_outputs: int, + static_lifetime_input_nodes: OrderedSet[fx.Node] | None = None, + ignore_must_be_in_fw_bw: bool = False, + omit_aot_autograd_runtime: bool = False, +) -> tuple[fx.GraphModule, fx.GraphModule]: + """Extract forward and backward graph modules from a joint graph. + + Args: + ignore_must_be_in_fw_bw: When True, disables forward/backward placement + enforcement in _extract_graph_with_inputs_outputs. Needed when the + joint_module is not an original fwd+bwd joint graph (e.g. a backward + graph being re-partitioned for dI/dW splitting). + omit_aot_autograd_runtime: When True, skips postprocessing that is + only needed when the resulting modules will be wrapped in a custom + autograd.Function (the AOTAutograd path). This includes: tangent input + handling, version-counter check sorting of saved tensors, opaque object + (FakeScriptObject) separation, and fp8 activation quantization. Set this + to True when the fwd/bwd modules will be executed directly without autograd. + """ + fwd_outputs, bwd_outputs, fwd_outputs_descs, bwd_outputs_descs = ( + _extract_fwd_bwd_outputs(joint_module, num_fwd_outputs=num_fwd_outputs) + ) + placeholders = joint_module.graph.find_nodes(op="placeholder") + primal_inputs = [*filter(_is_primal, placeholders)] + tangent_inputs = ( + [] if omit_aot_autograd_runtime else [*filter(_is_tangent, placeholders)] + ) + fwd_seed_offset_inputs = [*filter(_is_fwd_seed_offset, placeholders)] + bwd_seed_offset_inputs = [*filter(_is_bwd_seed_offset, placeholders)] + backward_state_inputs = [*filter(_is_backward_state, placeholders)] + + if saved_opaque_nodes is None: + saved_opaque_nodes = [] + + bwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + saved_sym_nodes + + saved_opaque_nodes + + saved_values + + tangent_inputs + + bwd_seed_offset_inputs, + bwd_outputs, + bwd_outputs_descs, + "backward", + ignore_must_be_in_fw_bw=ignore_must_be_in_fw_bw, + ) + + distributed_enabled = torch.distributed.is_available() + + for node in bwd_graph.find_nodes(op="placeholder"): + # This is to filter out saved values that don't actually end up being used by the backwards pass + if not node.users: + _remove_by_name(saved_values, node.name) + _remove_by_name(saved_sym_nodes, node.name) + _remove_by_name(saved_opaque_nodes, node.name) + # wait_tensor is a bit special: if we have a "dead activation" that is not used in the bw, + # but this dead activation is actually a collective, + # then the collective will generally by followed by a wait_tensor() call. + # we need to peek one node further to see if this wait_tensor is dead as well. + elif distributed_enabled and all( + n.target is torch.ops._c10d_functional.wait_tensor.default + and len(n.users) == 0 + for n in node.users + ): + _remove_by_name(saved_values, node.name) + _remove_by_name(saved_sym_nodes, node.name) + _remove_by_name(saved_opaque_nodes, node.name) + elif _is_backward_state(node): + # BackwardState is saved directly + _remove_by_name(saved_values, node.name) + if not backward_state_inputs: + raise AssertionError("backward_state_inputs must not be empty") + + # Now that we have the finalized list of saved values, we need to ensure + # we propagate all symbols which are referenced by backwards inputs. + # These are not directly used in the graph but are required for downstream + # sizevar assignment + saved_symbols: OrderedSet[sympy.Symbol] = OrderedSet() + saved_sym_nodes_binding = [] + saved_sym_nodes_derived = [] + + # Some symbols may already be bound in the directly saved_sym_nodes, + # keep track of them so we don't re-bind them + for node in saved_sym_nodes: + symbol = is_symbol_binding_fx_node(node) + if symbol: + saved_symbols.add(symbol) + saved_sym_nodes_binding.append(node) + else: + saved_sym_nodes_derived.append(node) + + # Now go through all of the prospective backward inputs and track any + # other symbols we need to bind + symbol_bindings = find_symbol_binding_fx_nodes(joint_module.graph) + for node in itertools.chain(saved_sym_nodes_derived, saved_values, tangent_inputs): + if "val" not in node.meta: + continue + # Bind both the unreplaced symbols (needed by runtime assertions, which + # preserve raw placeholder expressions -- see #155468) and the replaced + # symbols (needed by sizevar codegen and FxGraphCache guards, which use + # ShapeEnv replacements). Binding only one side can leave the other's + # symbols undefined in the backward: e.g. an offsets size that is a + # symbol replaced to `s + 1` leaves the base symbol `s` unbound, which + # surfaces as a KeyError during backward FxGraphCache guard evaluation. + new_symbols = ( + _free_symbols_without_replacements(node.meta["val"]) + | free_symbols(node.meta["val"]) + ) - saved_symbols + # NB: Deterministic order please! + for s in sorted(new_symbols, key=lambda s: s.name): + # NB: For well formed graphs, the symbol should always be present, + # but we also have ways to produce ill-formed graphs, e.g., direct + # make_fx usages, so don't choke in this case + if s not in symbol_bindings: + continue + saved_sym_nodes_binding.append(symbol_bindings[s]) + saved_symbols |= new_symbols + + # Update saved_sym_nodes that are now reordered to have all bindings at + # front. This can also be used later on to figure out the position of saved + # sym nodes in the output of fwd graph. + saved_sym_nodes.clear() + saved_sym_nodes.extend(saved_sym_nodes_binding + saved_sym_nodes_derived) + + if not omit_aot_autograd_runtime: + # See Note [Activations with no version counter checks in eager] + # Sort saved_values so that tensors with saved_tensor_with_no_vc_check=True + # are at the end. This allows us to have two consecutive slices: + # 1. tensors_saved_with_vc_check_slice - tensors saved via save_for_backward + # 2. tensors_saved_with_no_vc_check_slice - tensors stashed on ctx without save_for_backward + # The sort is stable, so the relative order within each group is preserved. + # + # Additionally, separate out opaque objects (FakeScriptObject) from tensors. + # Opaque objects should be placed after tensors in the forward outputs. + saved_values_with_vc_check = [] + saved_values_no_vc_check = [] + saved_opaque_objects = [] + for node in saved_values: + # Check if this is an opaque object + if isinstance(node.meta.get("val"), FakeScriptObject): + saved_opaque_objects.append(node) + elif node.meta.get("saved_tensor_with_no_vc_check", False): + saved_values_no_vc_check.append(node) + else: + saved_values_with_vc_check.append(node) + saved_values.clear() + saved_values.extend(saved_values_with_vc_check + saved_values_no_vc_check) + no_vc_check_start_idx = len(saved_values_with_vc_check) + + # debug assert: given saved_values where the last k of them are expected to not + # require VC checks, they should all have node metadata indicating so. + for i, node in enumerate(saved_values): + if i >= no_vc_check_start_idx: + if not node.meta.get("saved_tensor_with_no_vc_check", False): + raise AssertionError( + f"i={i}, no_vc_check_start_idx={no_vc_check_start_idx}, len(saved_values)={len(saved_values)}" + ) + + # Now, we re-generate the fwd/bwd graphs. + # NB: This might increase compilation time, but I doubt it matters + # Convention for saved acts is (tensors_with_vc_check, tensors_no_vc_check, opaque_objects, symints, opaque_nodes) + fwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + primal_inputs + fwd_seed_offset_inputs, + fwd_outputs + + saved_values + + saved_opaque_objects + + saved_opaque_nodes + + saved_sym_nodes, + fwd_outputs_descs + + [ + SavedForBackwardsNoVcCheckAOTOutput(i) + if i >= no_vc_check_start_idx and i < len(saved_values) + else SavedForBackwardsAOTOutput(i) + for i in range( + len(saved_values) + + len(saved_opaque_objects) + + len(saved_opaque_nodes) + + len(saved_sym_nodes) + ) + ], + "forward", + ignore_must_be_in_fw_bw=ignore_must_be_in_fw_bw, + ) + bwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + saved_sym_nodes + + saved_values + + saved_opaque_objects + + saved_opaque_nodes + + tangent_inputs + + bwd_seed_offset_inputs + + backward_state_inputs, + bwd_outputs, + bwd_outputs_descs, + "backward", + ignore_must_be_in_fw_bw=ignore_must_be_in_fw_bw, + ) + else: + # Raw fwd/bwd split for direct execution without autograd + fwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + primal_inputs + fwd_seed_offset_inputs, + fwd_outputs + saved_values + saved_sym_nodes, + fwd_outputs_descs + + [ + SavedForBackwardsAOTOutput(i) + for i in range(len(saved_values) + len(saved_sym_nodes)) + ], + "forward", + ignore_must_be_in_fw_bw=ignore_must_be_in_fw_bw, + ) + bwd_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, + saved_values + + saved_sym_nodes + + bwd_seed_offset_inputs + + backward_state_inputs, + bwd_outputs, + bwd_outputs_descs, + "backward", + ignore_must_be_in_fw_bw=ignore_must_be_in_fw_bw, + ) + + for node in bwd_graph.nodes: + if node.op in ("call_function", "get_attr"): + node.meta["autograd_backward"] = True + + fwd_module = fx._lazy_graph_module._make_graph_module(joint_module, fwd_graph) + bwd_module = fx._lazy_graph_module._make_graph_module(joint_module, bwd_graph) + if ( + inductor_config.post_grad_fusion_options.get( + "activation_quantization_aten_pass", None + ) + is not None + ): + enable_activation_quantization( + saved_values, + fwd_module, + bwd_module, + static_lifetime_input_nodes, + num_fwd_outputs, + ) + return fwd_module, bwd_module + + +def default_partition( + joint_module: fx.GraphModule, + _joint_inputs: Any, + *, + num_fwd_outputs: int, + static_lifetime_input_indices: list[int] | None = None, + static_lifetime_input_nodes: OrderedSet[fx.Node] | None = None, +) -> tuple[fx.GraphModule, fx.GraphModule]: + """ + Partitions the :attr:`joint_module` in a manner that closely resembles the + behavior observed in the original ``.forward()`` and ``.backward()`` of the + callable, i.e., the resulting forward graph contains those operators that + are executed in the original ``.forward()`` callable passed to + :func:`aot_function`. + + The default partitioner collects the operators that are between the forward + inputs and the forward outputs. This helps in finding the tensors which have + to be stashed for the backward pass. These stashed tensors become the output + of the generated forward graph. The remaining operators are then placed in + the backward graph. + + .. warning:: + This API is experimental and likely to change. + + Args: + joint_module(fx.GraphModule): The joint forward and backward graph. This + is the result of AOT Autograd tracing. + + Returns: + Returns the generated forward and backward Fx graph modules. + """ + # Respect the original placement of ops rather than rely on dataflow. + forward_nodes = [] + last_node = None + for node in joint_module.graph.nodes: + if _has_tag_is_forward(node) or _is_primal(node) or _is_fwd_seed_offset(node): + last_node = node + if last_node is None: + raise AssertionError("last_node must not be None") + for node in joint_module.graph.nodes: + if not _is_tangent(node): + forward_nodes.append(node) + if node is last_node: + break + forward_node_names = OrderedSet( + node.name for node in forward_nodes if node.op != "output" + ) + graph_has_recomputable_ops = has_recomputable_ops(joint_module) + graph_has_recomputable_rng_ops = has_recomputable_rng_ops(joint_module) + if graph_has_recomputable_ops: + if _is_functional_graph(joint_module.graph)[0] is not None: + # Fall-back to previous behavior to avoid bc-breaking, although can + # eventually flip the switch to make this a hard error. + warnings.warn( + "Trying to unsafely apply AC to a non-functional graph with the " + "default partitioner. Falling back to min-cut partitioner." + ) + return min_cut_rematerialization_partition( + joint_module, + _joint_inputs, + num_fwd_outputs=num_fwd_outputs, + static_lifetime_input_indices=static_lifetime_input_indices, + ) + + joint_module = cleanup_recompute_tags(joint_module, is_default_partition=True) + + if not config.unsafe_allow_optimization_of_collectives: + force_save_collectives(joint_module) + + force_save_effectful_ops(joint_module) + force_save_bw_mutation_src(joint_module) + + if static_lifetime_input_indices is None: + static_lifetime_input_indices = [] + node_info = classify_nodes( + joint_module, static_lifetime_input_indices, num_fwd_outputs + ) + + saved_values = [] + saved_sym_nodes = [] + saved_opaque_nodes = [] + + distributed_enabled = torch.distributed.is_available() + + def is_tensor(node: fx.Node) -> bool: + return "tensor_meta" in node.meta or isinstance( + node.meta.get("val"), torch._subclasses.FakeTensor + ) + + def is_multi_output(node: fx.Node) -> bool: + return ( + all(user.target == operator.getitem for user in node.users) + and len(node.users) > 0 + ) + + def is_impure(node: fx.Node) -> bool: + # wait tensor is an "impure" op according to DCE's definition of impure + # (see is_impure in torch/fx/node.py), but it survives past + # functionalization and can be safely dup'd and reordered under the + # assumption SPMD. + return ( + node.is_impure(impure_random=False) + and node.op + not in ( + "placeholder", + "output", + ) + and ( + not distributed_enabled + or node.target is not torch.ops._c10d_functional.wait_tensor.default + ) + ) + + for node in joint_module.graph.nodes: + if node.name not in forward_node_names: + continue + if node.op == "get_attr" and node.name in ( + k for k, v in joint_module.named_modules() + ): + continue + if node.target in ( + torch.ops.aten._assert_scalar.default, + torch.ops.aten._assert_async.default, + torch.ops.aten._assert_async.msg, + # Profiler record_function ops are technically impure (they set up + # profiling spans), but they're safe to duplicate during AC recompute. + # We skip both enter and exit to keep profiling spans balanced. + torch.ops.profiler._record_function_enter_new.default, + torch.ops.profiler._record_function_enter.default, + torch.ops.profiler._record_function_exit.default, + torch.ops.profiler._record_function_exit._RecordFunction, + ): + continue + if is_sym_node(node): + # Symints must be kept separate from tensors so that PythonFunction only calls + # save_for_backward on tensors and stashes symints in autograd .ctx + saved_sym_nodes.append(node) + continue + if is_multi_output(node): + # Must be ordered before MUST_SAVE tags to avoid saving tuples marked MUST_SAVE. + continue + if node.meta.get("recompute") == CheckpointPolicy.MUST_SAVE: + if is_opaque_node(node): + saved_opaque_nodes.append(node) + else: + saved_values.append(node) + continue + if is_impure(node): + if graph_has_recomputable_ops: + raise AssertionError( + f"Trying to apply AC on a graph with impure op: {node}, {node.target}" + ) + if is_opaque_node(node): + saved_opaque_nodes.append(node) + else: + saved_values.append(node) + continue + if is_opaque_node(node): + saved_opaque_nodes.append(node) + continue + if not is_tensor(node) and node.op == "call_function": + raise AssertionError(f"Expected {node} to be a tensor") + backward_usages = [n for n in node.users if n.name not in forward_node_names] + if all(is_sym_node(n) for n in backward_usages): + # If we have a tensor in the forward, where only its sizes/strides are needed in the backward, + # and not the actual tensor data, + # then it will be a lot cheaper to save only the sizes/strides, and not the actual tensor. + # + # Note that saving the tensor could also cause compilation problems: + # If the user mutated an input in the forward and uses its sizes/strides in the backward, + # then we would be obligated to clone the input before saving it to appease autograd. + # (This is how we originally found this bug). + saved_sym_nodes.extend(backward_usages) + continue + if not must_recompute(node): + saved_values.append(node) + + saved_values = list(dict.fromkeys(saved_values).keys()) + saved_sym_nodes = list(dict.fromkeys(saved_sym_nodes).keys()) + # Skip SymBool nodes whose only consumers are _assert_scalar calls. + # These are runtime assertion intermediates and are not needed in backward + # for any real computation. + saved_sym_nodes = [ + node for node in saved_sym_nodes if not _is_assert_only_symbool(node) + ] + saved_opaque_nodes = list(dict.fromkeys(saved_opaque_nodes).keys()) + + if config._sync_decision_cross_ranks: + saved_values = _sync_decision_cross_ranks(joint_module.graph, saved_values) + + if static_lifetime_input_nodes is None: + static_lifetime_input_nodes = node_info.static_lifetime_input_nodes + fw_module, bw_module = _extract_fwd_bwd_modules( + joint_module, + saved_values, + saved_sym_nodes=saved_sym_nodes, + saved_opaque_nodes=saved_opaque_nodes, + num_fwd_outputs=num_fwd_outputs, + static_lifetime_input_nodes=static_lifetime_input_nodes, + ) + + # Run DCE while overriding the definition of is_impure_node + fw_module.graph.eliminate_dead_code(is_impure_node=is_not_collective) + bw_module.graph.eliminate_dead_code(is_impure_node=is_not_collective) + + if graph_has_recomputable_ops: + if graph_has_recomputable_rng_ops: + fw_module, bw_module = functionalize_rng_ops( + joint_module, fw_module, bw_module, len(saved_sym_nodes) + ) + bw_module = reordering_to_mimic_autograd_engine(bw_module) + + # pyrefly: ignore [unbound-name] + if config.enable_activation_offloading: + from ._activation_offloading.activation_offloading import ( + enable_activation_offloading, + ) + + enable_activation_offloading( + fw_module, + bw_module, + num_fwd_outputs, + static_lifetime_input_nodes, + ) + + # raise all getitem ops to as early as possible + # this is helpful for memory, especially in the case of aot_eager backend + fw_module = raise_getitems(fw_module) + bw_module = raise_getitems(bw_module) + + fw_module = thread_graphsafe_rng_from_hops(fw_module, is_backward=False) + if len(node_info.required_bw_nodes) > 0: + bw_module = thread_graphsafe_rng_from_hops(bw_module, is_backward=True) + + return fw_module, bw_module + + +INT_INF = int(1e6) + + +def _tensor_nbytes(numel: int, dtype: torch.dtype) -> int: + return numel * dtype.itemsize + + +def _size_of(node: fx.Node) -> int: + def object_nbytes(x: object) -> int: + if not isinstance(x, torch.Tensor): + return 0 + return _tensor_nbytes(optimization_hint(x.numel(), fallback=4096), x.dtype) + + if "val" in node.meta: + val = node.meta["val"] + if isinstance(val, py_sym_types): + return 1 + # NB: The fallback values here are meaningless, maybe we should respect + # torch._inductor.config.unbacked_symint_fallback (but this is a + # layering violation) + elif isinstance(val, (list, tuple)): + return sum(object_nbytes(n) for n in val) + elif isinstance(val, dict): + return sum(object_nbytes(n) for n in val.values()) + elif isinstance(val, torch.Tensor): + return object_nbytes(val) + elif isinstance(val, (torch.ScriptObject, FakeScriptObject)): + # A (Fake)ScriptObject may hold tensors internally, so we cannot + # soundly compute its size here. Only treat it as zero size when the + # user has explicitly opted in via this escape hatch. + if config.unsafe_treat_script_objects_as_zero_size: + return 0 + raise RuntimeError( + f"Cannot compute the size of {type(val)} on node {node}. A " + "ScriptObject may hold tensors internally and the partitioner " + "has no general way to measure its memory footprint. Set " + "torch._functorch.config.unsafe_treat_script_objects_as_zero_size" + " = True to assume such objects are zero size (unsound)." + ) + + raise RuntimeError(f"Unknown metadata type {type(val)} on node {node}") + if node.op == "get_attr" or ( + isinstance(node.target, torch._ops.OpOverload) + and len(node.target._schema.returns) == 0 + ): + return 0 + raise RuntimeError( + f"Node {node} didn't have `val` metadata; we should always have `val` metadata on the nodes." + ) + + +# Used for some investigative purposes +def _count_ops(graph: fx.Graph) -> None: + from collections import defaultdict + + cnt: dict[str, int] = defaultdict(int) + for node in graph.nodes: + if node.op == "call_function": + cnt[node.target.__name__] += 1 + log.info("%s", sorted(cnt.items(), key=operator.itemgetter(1), reverse=True)) + + +@functools.cache +def pointwise_ops() -> list[torch._ops.OpOverloadPacket]: + ops: list[torch._ops.OpOverloadPacket] = [] + for attr_name in dir(torch.ops.aten): + opoverloadpacket = getattr(torch.ops.aten, attr_name) + if not isinstance(opoverloadpacket, torch._ops.OpOverloadPacket): + continue + + for op_overload in opoverloadpacket.op_overloads(): + if torch.Tag.pointwise in op_overload.tags: + # currently aot autograd uses packet not overload + ops.append(opoverloadpacket) + break + + return ops + + +def sort_depths( + args: tuple[Any, ...], depth_map: dict[fx.Node, int] +) -> list[tuple[fx.Node, int]]: + arg_depths = { + arg: depth_map[arg] for arg in args if isinstance(arg, torch.fx.node.Node) + } + return sorted(arg_depths.items(), key=operator.itemgetter(1), reverse=True) + + +def reordering_to_mimic_autograd_engine(gm: fx.GraphModule) -> fx.GraphModule: + """ + This pass finds the first bwd node in the graph (by looking at users of + tangents) and then reorders the graph by walking from this node to all the + way to the end of the graph. At each op in this traversal, we insert this op + in a new graph and try to bring only the relevant subgraph from the other + non-bwd edges relevant for this op. This closely mimics the behavior of + autograd engine. + + Why is this pass required in the first place? + + This is an artifact of how partitioners work today. The starting point of + partitioner is a joint graph, which is fwd and then bwd graph. In the case + of checkpointing, we keep portions of fwd graph in their original place in + the joint graph, while obtaining a bwd graph. As a result, the resulting bwd + graph has copies of recomputed fwd subgraphs followed by the original bwd + graph. If we run this naively, this leads to bad memory footprint, because + the fwd subgraphs are live for way longer duration than necessary. This pass + reorders the operations such that we prioritize the ops for the original bwd + graph while only realizing those ops from the fwd graph that are necessary + at any given point in the graph. + """ + + new_graph = fx.Graph() + env: dict[fx.Node, fx.Node] = {} + + # Add new placeholder nodes in the order specified by the inputs + for node in gm.graph.find_nodes(op="placeholder"): + env[node] = new_graph.node_copy(node, lambda x: env[x]) + + order = {node: idx for idx, node in enumerate(gm.graph.nodes)} + + def insert_node_in_graph(node: fx.Node) -> None: + cur_nodes = [node] + insertable_nodes: OrderedSet[fx.Node] = OrderedSet() + while len(cur_nodes) > 0: + node = cur_nodes.pop() + if node in insertable_nodes or node in env: + continue + insertable_nodes.add(node) + + # Bias traversal towards the nodes that have higher depth - prioritizes + # critical path first. + cur_nodes += node.all_input_nodes + + # pyrefly: ignore [bad-assignment] + insertable_nodes = sorted(insertable_nodes, key=lambda n: order[n]) + for node in insertable_nodes: + env[node] = new_graph.node_copy(node, lambda x: env[x]) + + # Find first bwd node in the graph + tangent_inputs = list(filter(_is_tangent, gm.graph.nodes)) + first_node_in_bwd = None + minimum_order = math.inf + for tangent in tangent_inputs: + for user in tangent.users: + if order[user] < minimum_order: + minimum_order = order[user] + first_node_in_bwd = user + + # If gradInp does not depend upon gradOut, we may not find any nodes in the "backwards pass" + if first_node_in_bwd is None: + return gm + + # Build the graph op-by-op by starting from the node all the way to the end + # copy_ can be not using tangents at all, we must copy it. + for node in list(gm.graph.nodes)[: order[first_node_in_bwd]]: + if node.op == "call_function" and node.target is torch.ops.aten.copy_.default: + insert_node_in_graph(node) + + for node in list(gm.graph.nodes)[order[first_node_in_bwd] :]: + insert_node_in_graph(node) + + # The output node is already built by the traversal. + new_gm = torch.fx.GraphModule(gm, new_graph) + return new_gm + + +def apply_graphsafe_rng_functionalization( + fw_module: torch.fx.GraphModule, + bw_module: torch.fx.GraphModule, + fw_node: torch.fx.Node, + bw_node: torch.fx.Node, + device: torch.device, + rng_count: int, + last_fwd_input: torch.fx.Node, + last_bwd_input: torch.fx.Node, +) -> tuple[torch.fx.Node, torch.fx.Node]: + """ + Note [CUDA Graph Safe RNG Functionalization] + + CUDA Graph capture doesn't work with get_rng_state and set_rng_state because these functions operate on CPU values, + while CUDA Graph RNG capture uses on-device CUDA tensors. To solve this, we use graphsafe_set_state with a + CUDA Generator registered to the CUDA Graph before capture begins. graphsafe_set_state updates the generator's pointer + to reference a different GeneratorImpl, ensuring subsequent calls are correctly forwarded to the desired generator + (and its cuda-tensor RNG state during graph capture). + + For each RNG operation's forward/backward pair: + + - We create two generators initialized with identical values + - Each forward and backward call advances its respective generator equally + - This keeps generators synchronized so forward and backward operations use matching RNG values + + When forward is called multiple times before backward (causing desynchronization): + + - We save the forward RNG state + - We update the backward Generator's state before executing backward + + This function modifies both forward and backward computation graphs by: + + Creating RNG state placeholders for both passes + Updating the forward node to use graph-safe RNG state + Updating the backward node to use graph-safe RNG state + + For more details: https://github.com/pytorch/pytorch/issues/113541 + """ + device_idx = device.index + if device_idx is None: + raise AssertionError("device_idx must not be None") + fw_graph = fw_module.graph + bw_graph = bw_module.graph + graphsafe_run_with_rng_state = torch._prims.rng_prims.graphsafe_run_with_rng_state + + # Handle forward pass + + # Note: [Generator arguments in AOTDispatcher] + # Generator arguments in AOTDispatcher are added to support graphsafe rng + # functionalization. See note above [CUDA Graph Safe RNG Functionalization] + with fw_module.graph.inserting_after(last_fwd_input): + fwd_rng_state = fw_module.graph.placeholder(f"fwd_rng_state_{rng_count}") + fwd_rng_state.meta["val"] = get_default_generator(device).clone_state() + last_fwd_input = fwd_rng_state + + # Handle backward pass + with bw_module.graph.inserting_after(last_bwd_input): + bwd_rng_state = bw_module.graph.placeholder(f"bwd_rng_state_{rng_count}") + # as above, clone so that meta val generator will not contain tensors + bwd_rng_state.meta["val"] = get_default_generator(device).clone_state() + last_bwd_input = bwd_rng_state + + # Update forward node + fw_kwargs = dict(fw_node.kwargs) + fw_kwargs["rng_state"] = fwd_rng_state + with fw_module.graph.inserting_after(fw_node): + functional_fw_node = fw_graph.create_node( + "call_function", + graphsafe_run_with_rng_state, + args=(fw_node.target, *fw_node.args), # type: ignore[arg-type] + kwargs=fw_kwargs, + ) + fw_node.replace_all_uses_with(functional_fw_node) + fw_graph.erase_node(fw_node) + + # Update backward node + bwd_kwargs = dict(bw_node.kwargs) + bwd_kwargs["rng_state"] = bwd_rng_state + with bw_graph.inserting_before(bw_node): + rng_output = bw_graph.create_node( + "call_function", + graphsafe_run_with_rng_state, + args=(bw_node.target, *bw_node.args), # type: ignore[arg-type] + kwargs=bwd_kwargs, + ) + bw_node.replace_all_uses_with(rng_output) + bw_graph.erase_node(bw_node) + + return last_fwd_input, last_bwd_input + + +def functionalize_rng_ops( + joint_module: fx.GraphModule, + fw_module: fx.GraphModule, + bw_module: fx.GraphModule, + num_sym_nodes: int, +) -> tuple[fx.GraphModule, fx.GraphModule]: + # During user-driven activation checkpointing, we have to ensure that a rng + # op in fwd yields the same output as the recomputed rng op in the bwd. To + # do this, we use functionalize wrappers to wrap the random ops and share + # rng state between the fwd and bwd graphs. + + # There are 3 main steps to do this + # Step 1 - Construct a mapping of rng node between the fwd and its counterpart in bwd. + # Step 2 - Modify the fwd pass such that + # 1) Replace rand with run_and_save_rng_state wrapper + # 2) Replace the users of the original op with the output[1] of this op. + # 3) Collect all the rng_state - output[0] of each op, and make them + # output nodes. Special care needs to be taken here because fwd outputs + # has symints at the very end. + # Step 3 - Modify the bwd pass such that + # 1) Add the input nodes just before the tangents for the stashed rng states + # 2) Replace rand with run_with_save_rng_state wrappers + # 3) Use the stashed states as inputs to these ops + + # Unique id to generate name + uid = itertools.count() + + def get_rng_ops(gmod: fx.GraphModule) -> dict[str, fx.Node]: + random_nodes: dict[str, fx.Node] = {} + for node in gmod.graph.nodes: + if node.op == "call_function" and is_rng_op(node): + random_nodes[node.name] = node + return random_nodes + + def get_device(node: fx.Node) -> torch.device | None: + """ + Check the example value of the node outputs to find the device type. + """ + if "val" not in node.meta: + return None + + candidates = node.meta["val"] + if not isinstance(candidates, tuple): + candidates = (candidates,) + + for candidate in candidates: + if isinstance(candidate, torch.Tensor): + if supports_graphsafe_rng(candidate.device): + return candidate.device + + return torch.device("cpu") + + def get_sample_rng_state(device: torch.device | None) -> torch.Tensor: + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode() + if fake_mode is None: + raise AssertionError("fake_mode must not be None") + with fake_mode: + if device is not None and supports_graphsafe_rng(device): + return fake_mode.from_tensor(get_device_rng_state(device)) + return fake_mode.from_tensor(torch.get_rng_state()) + + # Step 1 - Construct a mapping of rng node between the fwd and its counterpart in bwd. + joint_graph_rng_ops = get_rng_ops(joint_module) + fw_graph_rng_ops = get_rng_ops(fw_module) + bw_graph_rng_ops = get_rng_ops(bw_module) + recomputable_rng_ops_map = {} + for node in joint_module.graph.nodes: + if must_recompute(node) and is_rng_op(node): + # Skip if the node doesn't exist in both forward and backward graphs. + # This can happen when the RNG op's output is not needed for gradient + # computation and gets eliminated by dead code elimination. + if node.name not in fw_graph_rng_ops or node.name not in bw_graph_rng_ops: + continue + base_node = joint_graph_rng_ops[node.name] + fw_node = fw_graph_rng_ops[node.name] + bw_node = bw_graph_rng_ops[node.name] + recomputable_rng_ops_map[base_node] = {"fwd": fw_node, "bwd": bw_node} + + run_and_save_rng = torch._prims.rng_prims.run_and_save_rng_state + run_with_rng_state = torch._prims.rng_prims.run_with_rng_state + + bw_tangent_start_node = None + for node in bw_module.graph.find_nodes(op="placeholder"): + if "tangent" in node.name: + bw_tangent_start_node = node + break + if bw_tangent_start_node is None: + raise RuntimeError( + "Couldn't find tangent node in graph inputs. This is unexpected, please file a bug if you see this" + ) + + fw_rng_state_outputs: list[fx.Node] = [] + + last_fwd_input = next(reversed(fw_module.graph.find_nodes(op="placeholder"))) + last_bwd_input = next(reversed(bw_module.graph.find_nodes(op="placeholder"))) + + devices = OrderedSet( + get_device(node_pair["fwd"]) for node_pair in recomputable_rng_ops_map.values() + ) + # pyrefly: ignore [unbound-name] + devices.discard(torch.device("cpu")) + # multiple graphsafe devices won't work with cudagraphs anyway, + # fallback to non graphsafe rng checkpointing + multi_graphsafe_devices = len(devices) > 1 + + # this changes numerics, so if fallback_random is set we will not use it + # pyrefly: ignore [unbound-name] + ind_config = torch._inductor.config + use_rng_graphsafe_rng_functionalization = ( + config.graphsafe_rng_functionalization + and not multi_graphsafe_devices + and ( + not ind_config.fallback_random + or ind_config.test_configs.graphsafe_rng_func_ignores_fallback_random + ) + ) + + for rng_count, node_pair in enumerate(recomputable_rng_ops_map.values()): + # Step 2 - Modify the fwd pass such that + fw_node = node_pair["fwd"] + bw_node = node_pair["bwd"] + device = get_device(fw_node) + + fw_graph = fw_module.graph + bw_graph = bw_module.graph + + if ( + use_rng_graphsafe_rng_functionalization + and device is not None + and supports_graphsafe_rng(device) + ): + last_fwd_input, last_bwd_input = apply_graphsafe_rng_functionalization( + fw_module, + bw_module, + fw_node, + bw_node, + device, + rng_count, + last_fwd_input, + last_bwd_input, + ) + else: + with fw_graph.inserting_before(fw_node): + functional_fw_node = fw_graph.create_node( + "call_function", + run_and_save_rng, + # pyrefly: ignore [bad-argument-type] + args=( + fw_node.target, + *fw_node.args, + ), # pyrefly: ignore[bad-argument-type] + kwargs=fw_node.kwargs, + ) + state = fw_graph.create_node( + "call_function", + operator.getitem, + args=(functional_fw_node, 0), + kwargs={}, + ) + state.meta["val"] = get_sample_rng_state(device) + + rng_output = fw_graph.create_node( + "call_function", + operator.getitem, + args=( + functional_fw_node, + 1, + ), + kwargs={}, + ) + # Copy the meta data from the original node + rng_output.meta = copy.copy(fw_node.meta) + + fw_node.replace_all_uses_with(rng_output) + fw_graph.erase_node(fw_node) + fw_rng_state_outputs.append(state) + + # Step 3 - Modify the bwd pass such that + with bw_graph.inserting_before(bw_tangent_start_node): + state_name = f"rng_state_output_{next(uid)}" + bw_rng_state_node = bw_graph.placeholder(state_name) + bw_rng_state_node.meta["val"] = get_sample_rng_state(device) + + with bw_graph.inserting_before(bw_node): + rng_output = bw_graph.create_node( + "call_function", + run_with_rng_state, + # pyrefly: ignore [bad-argument-type] + args=( + bw_rng_state_node, + bw_node.target, + *bw_node.args, + ), # pyrefly: ignore[bad-argument-type] + kwargs=bw_node.kwargs, + ) + + bw_node.replace_all_uses_with(rng_output) + bw_graph.erase_node(bw_node) + + # Add the rng states in the output of the fwd graph. AOT Autograd assumes + # that symints are at the end of forward graph outputs. So, insert the new + # rng states accordingly. + if fw_rng_state_outputs: + fw_output_node = next(iter(fw_module.graph.find_nodes(op="output"))) + fw_outputs = fw_output_node.args[0] + sym_node_start_idx = len(fw_outputs) - num_sym_nodes + outputs = ( + fw_outputs[:sym_node_start_idx] + + tuple(fw_rng_state_outputs) + + fw_outputs[sym_node_start_idx:] + ) + fw_module.graph.output(outputs) + fw_module.graph.erase_node(fw_output_node) + fw_module.recompile() + bw_module.recompile() + return fw_module, bw_module + + +def force_save_collectives(joint_module: fx.GraphModule) -> None: + """ + By default, the partitioner is not allowed to recompute collectives + unless they come from a user-annotated AC region. + See Note [Recomputing collectives in the partitioner] + """ + for node in joint_module.graph.nodes: + if ( + isinstance(node.target, torch._ops.OpOverload) + and node.target.namespace == "_c10d_functional" + and not must_recompute(node) + ): + node.meta["recompute"] = CheckpointPolicy.MUST_SAVE + + +def force_save_effectful_ops(joint_module: fx.GraphModule) -> None: + """ + Force save outputs from with_effects nodes wrapping effectful ops. + + Effectful ops (registered via _register_effectful_op) should not be recomputed + because they may have arbitrary global side effects (I/O, RNG state, collectives, + etc.). We mark the tensor outputs of with_effects as MUST_SAVE to prevent + recomputation of the effectful op. + + The with_effects node returns a tuple (token, result). We recursively find all + leaf outputs extracted via getitem and mark them as MUST_SAVE. Since these are + saved, the with_effects op doesn't need to be recomputed in backward. + """ + + def mark_getitem_outputs(node: fx.Node) -> None: + for user in node.users: + if user.target is operator.getitem: + mark_getitem_outputs(user) + if not isinstance(user.meta.get("val"), (tuple, list)): + user.meta["recompute"] = CheckpointPolicy.MUST_SAVE + + for node in joint_module.graph.nodes: + if ( + is_with_effects(node) + and not must_recompute(node) + and not _has_tag_is_backward(node) + ): + mark_getitem_outputs(node) + + +def force_save_bw_mutation_src(joint_module: fx.GraphModule) -> None: + # If we have mutations of the same primal in forward and backward, + # We must not recompute the source of mutation to not apply twice. + has_mutation_in_bw: OrderedSet[torch.fx.Node] = OrderedSet() + for node in reversed(joint_module.graph.nodes): + if node.op == "output": + continue + + is_copy_ = node.target is torch.ops.aten.copy_.default + if is_copy_: + if _has_tag_must_be_in_backward(node): + has_mutation_in_bw.add(node.args[0]) + + if _has_tag_must_be_in_forward(node) and node.args[0] in has_mutation_in_bw: + node.args[1].meta["recompute"] = CheckpointPolicy.MUST_SAVE + else: + # We use invariant of aotdispatch joint graph, + # That we emit copy_ only in the end of it. + # We do not want to iterate through all the joint graph, + # so break at the first non-output, non-copy_ node. + break + + +def is_getitem_of_multi_output(node: fx.Node) -> bool: + if node.target != operator.getitem: + return False + parent = node.args[0] + if type(parent) is not fx.Node: + raise AssertionError(f"expected parent to be fx.Node, got {type(parent)}") + return "tensor_meta" not in parent.meta and node.op == "call_function" + + +def cleanup_recompute_tags( + joint_module: fx.GraphModule, *, is_default_partition: bool +) -> fx.GraphModule: + """ + If there are two consecutive checkpointed blocks with no operator in + between, we would still want to stash the tensor at the boundary of + checkpointed blocks. The following pass makes the last output node + non-recomputable to allow for that. + """ + for node in joint_module.graph.nodes: + if must_recompute(node): + for user in node.users: + if ( + must_recompute(user) + and "ac_graph_id" in user.meta + and "ac_graph_id" in node.meta + and user.meta["ac_graph_id"] > node.meta["ac_graph_id"] + ): + node.meta["recompute"] = CheckpointPolicy.MUST_SAVE + if node.meta.get("has_backward_hook", False) and not any( + must_recompute(user) for user in node.users + ): + # If node is AC region output and has a backward hook on it, we intentionally choose to save it. + # This is to work around circular dependencies with backward hooks + AC. + # Example: + # ``` + # out = fully_shard(utils.checkpoint(module))(x) + # norm_out = layer_norm(out) + # ``` + # Here there is a circular dependency: + # 1. In backward, grad_input of layer_norm aka. `out_grad` is actually dependent on `out`. + # 2. `out` depends on `out`'s backward hook created by FSDP2 (which does all-gather for `module` weights) + # in order to be recomputed. + # 3. `out`'s backward hook, as is the case for all eager backward hooks, depends on `out_grad` + # -> circular dependency with (1)! + # + # Solution: check whether `out` has a backward hook, and if so, intentionally save `out` + # in forward graph outputs. With this, we can break the above circular dependency. + node.meta["recompute"] = CheckpointPolicy.MUST_SAVE + elif ( + "ac_graph_id" not in node.meta + and any(must_recompute(user) for user in node.users) + and not ( + # Avoid saving getitem nodes which are not labeled with "ac_graph_id" + is_getitem_of_multi_output(node) and "ac_graph_id" in node.args[0].meta + ) + and is_default_partition + ): + # This node is not part of the AC region and a user is marked as recompute. + # This means it's an input to the AC region and we should save it. + # For ease of landing, gate this to default partitioner only, but we should think + # about flipping the switch in general as well. + node.meta["recompute"] = CheckpointPolicy.MUST_SAVE + return joint_module + + +def solve_min_cut( + joint_graph: fx.Graph, + node_info: NodeInfo, + min_cut_options: MinCutOptions, + dont_ban: OrderedSet[fx.Node] | None = None, +) -> tuple[list[fx.Node], OrderedSet[fx.Node]]: + if dont_ban is None: + dont_ban = OrderedSet() + op_types = get_default_op_list() + + if AOT_PARTITIONER_DEBUG: + joint_module_ops = OrderedSet( + str(node.target._overloadpacket) + for node in joint_graph.nodes + if node.op == "call_function" and hasattr(node.target, "_overloadpacket") + ) + ops_ignored = joint_module_ops - OrderedSet( + str(i) for i in op_types.recomputable_ops + ) + log.info("Ops banned from re-materialization: %s", ops_ignored) + + def can_fuse_into_auto_functionalized(a: fx.Node, b: fx.Node) -> bool: + if b.target != torch.ops.higher_order.auto_functionalized: + return False + mutable_op = b.args[0] + ( + mutable_arg_names, + _, + ) = torch._higher_order_ops.auto_functionalize.get_mutable_args( + # pyrefly: ignore[bad-argument-type] + mutable_op + ) + for name in mutable_arg_names: # pyrefly: ignore [not-iterable] + arg = b.kwargs[name] + if a is arg: + return True + if isinstance(arg, list): + if a in arg: + return True + return False + + def can_fuse_into_triton_kernel_wrapper_functional(a: fx.Node, b: fx.Node) -> bool: + if b.target != torch.ops.higher_order.triton_kernel_wrapper_functional: + return False + mutable_arg_names = b.kwargs["tensors_to_clone"] + for name in mutable_arg_names: # pyrefly: ignore [not-iterable] + kwargs: Any = b.kwargs["kwargs"] + if kwargs is None: + raise AssertionError("kwargs must not be None") + arg = kwargs[name] + if a is arg: + return True + return False + + def is_fusible(a: fx.Node, b: fx.Node) -> bool: + # We can perform "memory fusion" into a cat, but cat cannot be a + # producer to a fusion + if get_aten_target(b) == aten.cat: + return True + if can_fuse_into_auto_functionalized(a, b): + return True + if can_fuse_into_triton_kernel_wrapper_functional(a, b): + return True + if ( + a.target is operator.getitem + and a.args[0].target # pyrefly: ignore [missing-attribute] + is torch.ops.higher_order.triton_kernel_wrapper_functional + ): + # if a is the output of a user triton kernel, + # then (by default) we will not be able to fuse b into it + return False + return op_types.is_fusible(a) and op_types.is_fusible(b) + + try: + import networkx as nx + except ImportError as e: + raise RuntimeError( + "Need networkx installed to perform smart recomputation heuristics" + ) from e + + def is_materialized_backwards(node: fx.Node) -> bool: + if op_types.is_view(node): + return False + cur_nodes = OrderedSet([node]) + while len(cur_nodes) > 0: + cur = cur_nodes.pop() + for user in cur.users: + if not node_info.is_required_fw(user) and not is_fusible(cur, user): + return True + if op_types.is_view(user): + cur_nodes.add(user) + + return False + + def should_ban_recomputation(node: fx.Node) -> str | None: + """Returns reason string if node should be banned from recomputation, None otherwise.""" + if node.op != "call_function": + return None + if node.target is operator.getitem: + return None + if node.meta.get("recompute", None) == CheckpointPolicy.MUST_SAVE: + return "marked MUST_SAVE" + if config.recompute_views and op_types.is_view(node): + return None + if node.target in [aten.lift_fresh_copy.default, aten.lift_fresh.default]: + return None + + if min_cut_options.ban_if_not_in_allowlist: + if not op_types.is_recomputable(node): + return "not in recomputable allowlist" + else: + if op_types.is_random(node): + return "random op" + if op_types.is_compute_intensive(node): + return "compute intensive op" + if is_non_builtin_to_include(node): + return "non-builtin op" + + # If a node *must* be materialized in the backwards pass, then we + # should never recompute it. This is a pretty subtle point. In + # general, the assumption we make is that recomputing a node in the + # backwards pass is "free". However, if a node must be materialized + # in the backwards pass, then recomputing it is never free. + if min_cut_options.ban_if_materialized_backward and is_materialized_backwards( + node + ): + log.debug("materialized backwards: %s %s", node, tuple(node.users)) + return "materialized in backward" + + # Arbitrary hack that sometimes seems to help things. The above + # modification appears to have made this heuristic a lot less critical + # for performance. + # NB: As of PR #121692, this hack no longer seems necessary. + if ( + # pyrefly: ignore [missing-attribute] + node.dist_from_bw < 1000 and node.dist_from_bw > config.max_dist_from_bw + ): + return "too far from backward" + + # If the output of an op is 4x smaller (arbitrary choice), + # then we don't allow recomputation. The idea here is that for + # things like reductions, saving the output of the reduction is very + # cheap/small, and it makes sure we don't do things like recompute + # normalizations in the backwards. + if min_cut_options.ban_if_reduction: + input_tensors_size = sum( + _size_of(i) for i in node.args if isinstance(i, fx.Node) + ) + output_size = _size_of(node) + if output_size * 4 < input_tensors_size: + return "reduction op" + return None + + def is_materialized(node: fx.Node) -> bool: + if node.op == "placeholder": + return True + + return not all(is_fusible(node, user) for user in node.users) + + def get_node_weight( + node: fx.Node, static_lifetime_input_nodes: OrderedSet[fx.Node] + ) -> tuple[float, str | None]: + """Returns (weight, cannot_save_reason). + + cannot_save_reason is None for finite weights, or a string explaining + why the node cannot be saved for infinite weights. + """ + if ( + config.treat_parameters_as_free_to_save + and node in static_lifetime_input_nodes + ): + return 0, None + mem_sz = _size_of(node) + if config.recompute_views and op_types.is_view(node): + # If `config.recompute_views=True`, we don't save views. This is generally + # a good idea since views are free to recompute, and it makes it a bit simpler + # to analyze. + # NB: If they're not free to recompute (e.g. nested tensors)... I + # think we should modify checks for view_ops to `is_view` and check + # that. Basically, with nested tensors, `aten.view` is not a "view + # op". + return math.inf, "view op (recompute_views=True)" + + if isinstance(node.meta["val"], py_sym_types): + # We never want to save symfloats + if not isinstance(node.meta["val"], torch.SymInt): + return INT_INF, "SymFloat (non-SymInt symbolic value)" + + # Heuristic to bias towards nodes closer to the backwards pass + # Complete guess about current value + mem_sz = int( + # pyrefly: ignore [missing-attribute] + mem_sz * (1.1 ** max(min(node.dist_from_bw, 100), 1)) + ) + if is_materialized(node): + return mem_sz, None + else: + return mem_sz * 2, None + + nx_graph = nx.DiGraph() + banned_nodes: OrderedSet[fx.Node] = OrderedSet() + + def ban_recomputation_if_allowed(node: fx.Node, reason: str = "") -> bool: + if op_types.is_view(node): + return False + if node in dont_ban: + # collectives are *always* banned from recompute, overriding `dont_ban` + # (in particular, the activation memory budget logic is not allowed to recompute collectives) + is_collective = ( + isinstance(node.target, torch._ops.OpOverload) + and node.target.namespace == "_c10d_functional" + ) + if config.unsafe_allow_optimization_of_collectives or not is_collective: + return False + # This bans recomputation of the node unless we've been forced not to by + # user annotation + if must_recompute(node): + return False + + if "val" in node.meta and isinstance(node.meta["val"], torch.SymFloat): + return False + banned_nodes.add(node) + # A node will only ever be recomputed if there is a path from an + # ancestor of this node to the backwards path through this node that + # doesn't go through any saved value. If this node is saved, then that + # condition is not possible. + nx_graph.add_edge( + "source", + node.name + "_in", + capacity=math.inf, + reason=f"cannot recompute: {reason}" if reason else "cannot recompute", + ) + return True + + for node in joint_graph.nodes: + if node.op == "output": + continue + + if node in node_info.required_bw_nodes: + # See Note: [tangents_closure vs required_bw_nodes] + if node not in node_info.tangents_closure: + nx_graph.add_edge( + node.name + "_out", + "sink", + capacity=math.inf, + reason="must be available for backward: input required for gradient", + ) + else: + nx_graph.add_edge( + node.name + "_in", + "sink", + capacity=math.inf, + reason="must be computed in backward: required for gradient", + ) + continue + + if must_recompute(node): + # If user explicitly says they want to recompute a node, we honor it + # by adding an inf-capacity edge from X_in to the sink. + # This way, X_in node is guaranteed to be part of the subgraph that contains "sink" + # after the cut, thus guaranteeing that X op will be recomputed. + nx_graph.add_edge( + node.name + "_in", + "sink", + capacity=math.inf, + reason="must recompute: marked by checkpoint policy", + ) + continue + + if _is_primal(node): + ban_recomputation_if_allowed(node, "primal input") + elif _is_fwd_seed_offset(node): + ban_recomputation_if_allowed(node, "forward RNG seed") + + # If a node can't be recomputed (too expensive or involves randomness), + # we prevent it from being recomputed by adding an inf edge to the source + # We only need to ban nodes in the fw pass, as those are the only ones that would be recomputed. + ban_reason = should_ban_recomputation(node) + if node_info.is_required_fw(node) and ban_reason: + ban_recomputation_if_allowed(node, ban_reason) + + # Checks if a node is actually a tuple. Can be simplified to just an isinstance check if we always use faketensors. + is_non_tensor_node = ( + "val" not in node.meta and "tensor_meta" not in node.meta + ) or ("val" in node.meta and not isinstance(node.meta["val"], torch.Tensor)) + + if is_sym_node(node): + weight = float(sym_node_size(node)) + cannot_save_reason = None + elif is_non_tensor_node: + # FakeScriptObjects and opaque objects should have weight 0.0 + # so they can be properly partitioned between forward and + # backward, like BackwardState. + if isinstance( + node.meta.get("val"), (BackwardState, FakeScriptObject) + ) or is_opaque_node(node): + weight = 0.0 + cannot_save_reason = None + else: + weight = math.inf + cannot_save_reason = "non-tensor output" + else: + weight, cannot_save_reason = get_node_weight( + node, node_info.static_lifetime_input_nodes + ) + + # Creates the weights on the "node" edge + if cannot_save_reason and (weight == math.inf or weight == INT_INF): + nx_graph.add_edge( + node.name + "_in", + node.name + "_out", + capacity=weight, + reason=f"cannot save: {cannot_save_reason}", + ) + else: + nx_graph.add_edge(node.name + "_in", node.name + "_out", capacity=weight) + + for user in node.users: + nx_graph.add_edge( + node.name + "_out", + user.name + "_in", + capacity=math.inf, + reason="data dependency", + ) + + # todo(chilli): This is the most questionable of the 3 heuristics for banning recompute. + # Some example models to look at where this helps perf: poolformer_m36, + # mixer_b16_224, cait_m36_384 + + # The "rough" idea here is that if you have some node that is used by both a + # node nearby downstream as well as a node far downstream, if we recompute + # both of the downstream nodes, we're unlikely to be able to fuse both + # downstream nodes together. + + # Thus, we shouldn't aim to recompute far downstream nodes that depend on + # this node. That intuition of "far downstream" is captured by whether + # there's an unfusible op along the chain somewhere + + # It could probably be improved by properly analyzing what's going on in the + # backwards pass instead of only relying on whether it's unfusible in the + # forwards. + + def find_first_unfusible(start_nodes: list[fx.Node], max_range: int) -> int: + """ + Finds the first unfusible node in the chain of nodes starting from + `start_nodes` and returns its position. + """ + sorted_nodes: list[tuple[int, fx.Node, bool]] = [] + for n in start_nodes: + heapq.heappush(sorted_nodes, (node_info.get_fw_order(n), n, True)) + + while len(sorted_nodes) > 0: + _, node, node_is_fusible = heapq.heappop(sorted_nodes) + if not node_is_fusible: + return node_info.get_fw_order(node) + for user in node.users: + if node_info.is_required_fw(user): + if node_info.get_fw_order(user) > max_range: + continue + val: tuple[int, fx.Node, bool] = ( + node_info.get_fw_order(user), + user, + is_fusible(node, user), + ) + if val not in sorted_nodes: + heapq.heappush(sorted_nodes, val) + return max_range + + if min_cut_options.ban_if_used_far_apart: + for used_node in node_info.required_fw_nodes: + orders = [ + node_info.get_fw_order(user) + for user in used_node.users + if node_info.is_required_fw(user) + ] + fw_users = [ + user for user in used_node.users if node_info.is_required_fw(user) + ] + if len(orders) > 0: + first_unfusible_use = find_first_unfusible(fw_users, max(orders)) + for user in tuple(used_node.users): + if ( + node_info.is_required_fw(user) + and node_info.get_fw_order(user) > first_unfusible_use + and is_fusible(used_node, user) + ): + if user in banned_nodes: + continue + log.info( + "used above/below fusible %s:(%s) -> %s -> %s:(%s)", + used_node, + node_info.get_fw_order(used_node), + first_unfusible_use, + user, + node_info.get_fw_order(user), + ) + ban_recomputation_if_allowed(user) + + # This heuristic is fairly straightforward. The idea is that although it is + # cheap to recompute bandwidth-bound ops, we don't want to end up in a situation + # where we have a long chain of pointwise ops from the beginning to the end + # of the model (like say, residual connections) + + # todo: I'm not totally sure why this heuristic matters. It's possible that this is + # working around Inductor fusion decisions, or that it's a patch over + # suboptimal partitioning decisions + + # Some models it improves perf on are cait_m36_384, mixer_b16_224, poolformer_m36 + + if min_cut_options.ban_if_long_fusible_chains: + visited: OrderedSet[fx.Node] = OrderedSet() + for start_node in joint_graph.nodes: + if not node_info.is_required_fw(start_node): + continue + fusible: list[tuple[int, fx.Node]] = [ + (node_info.get_fw_order(start_node), start_node) + ] + start_order = node_info.get_fw_order(start_node) + while len(fusible) > 0: + _, cur = heapq.heappop(fusible) + if cur in visited: + continue + visited.add(cur) + # 100 is arbitrary choice to try and prevent degenerate cases + if ( + node_info.get_fw_order(cur) > start_order + 100 + and len(fusible) == 0 + ): + log.info( + "too long %s %s %s %s", + cur, + start_node, + node_info.get_fw_order(cur), + node_info.get_fw_order(start_node), + ) + ban_recomputation_if_allowed(cur) + break + + for user in cur.users: + if ( + node_info.is_required_fw(user) + and is_fusible(cur, user) + and user not in banned_nodes + ): + heapq.heappush(fusible, (node_info.get_fw_order(user), user)) + + try: + cut_value, partition = nx.minimum_cut(nx_graph, "source", "sink") + except nx.NetworkXUnbounded as unbounded_exc: + # Check if structured tracing is enabled (for production job debugging via tlparse) + structured_tracing_enabled = bool(trace_log.handlers) + + # Dump the FX graph for debugging + fx_graph_file: str | None = None + fx_graph_str: str | None = None + joint_module = joint_graph.owning_module + try: + fx_graph_str = ( + joint_module.print_readable( + print_output=False, include_stride=True, include_device=True + ) + if joint_module is not None + else str(joint_graph) + ) + # Always log to structured trace for production debugging + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "min_cut_failed_fx_graph", + "encoding": "string", + }, + payload_fn=lambda: fx_graph_str, + ) + # Also write to local file for local debugging + fx_graph_file = _get_unique_path("min_cut_failed_graph", ".txt") + with open(fx_graph_file, "w") as f: + f.write(fx_graph_str) + except Exception as e: + fx_graph_file = f"(failed to write: {e})" + + # Dump the min-cut edge list to structured trace + edge_list_str = "\n".join(nx.readwrite.edgelist.generate_edgelist(nx_graph)) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "min_cut_failed_edge_list", + "encoding": "string", + }, + payload_fn=lambda: edge_list_str, + ) + + # Find and report the infinite-capacity path + inf_path = _find_infinite_capacity_path(nx_graph) + if inf_path: + # Group edges by FX node and format for user understanding + # inf_path is a list of (from_node, to_node, reason) tuples + # + # Edge types and what they mean: + # - source -> X_in: X cannot be recomputed + # - X_in -> X_out (inf): X's output cannot be saved + # - X_out -> Y_in: Y depends on X (data flow) + # - X_in -> sink: X must be computed in backward + # - X_out -> sink: X's output must be available for backward + + # Build a user-friendly explanation grouped by FX node + node_constraints: dict[str, list[str]] = {} + raw_path_nodes = ["source"] + + def get_base_name(node_name: str) -> str: + for suffix in ("_in", "_out"): + if node_name.endswith(suffix): + return node_name[: -len(suffix)] + return node_name + + for from_node, to_node, reason in inf_path: + raw_path_nodes.append(to_node) + + # Skip source/sink, focus on FX nodes + if from_node == "source": + base = get_base_name(to_node) + node_constraints.setdefault(base, []).append(reason) + elif to_node == "sink": + base = get_base_name(from_node) + node_constraints.setdefault(base, []).append(reason) + elif get_base_name(from_node) == get_base_name(to_node): + # Internal edge (X_in -> X_out) + base = get_base_name(from_node) + node_constraints.setdefault(base, []).append(reason) + else: + # Data dependency edge (X_out -> Y_in) + from_base = get_base_name(from_node) + to_base = get_base_name(to_node) + node_constraints.setdefault(to_base, []).append( + f"depends on {from_base}" + ) + + # Format the constraints nicely + constraint_lines: list[str] = [] + for node_name, constraints in node_constraints.items(): + constraint_lines.append(f" {node_name}:") + for c in constraints: + constraint_lines.append(f" - {c}") + + constraints_str = "\n".join(constraint_lines) + raw_path_str = " -> ".join(raw_path_nodes) + + # Try to visualize (logs to structured trace and writes local file) + svg_path, svg_content = visualize_min_cut_graph(nx_graph) + if svg_content: + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "min_cut_failed_svg", + "encoding": "string", + }, + payload_fn=lambda: svg_content, + ) + + # Build file location messages + local_files_msg = ( + f"FX graph dump: {fx_graph_file}\n" if fx_graph_file else "" + ) + if svg_path: + local_files_msg += f"Min-cut graph visualization: {svg_path}\n" + + # Suggest tlparse if structured tracing is enabled + tlparse_msg = "" + if structured_tracing_enabled: + tlparse_msg = ( + "[Production debugging: Use tlparse to extract debug artifacts " + "(min_cut_failed_fx_graph, min_cut_failed_edge_list, min_cut_failed_svg)]\n" + ) + + raise RuntimeError( + f"AOT Autograd failed to partition the joint forward-backward graph.\n\n" + f"The partitioner determines which intermediate values to save from the " + f"forward pass vs recompute in the backward pass. This error means a value " + f"is required for backward, but cannot be saved AND cannot be recomputed.\n\n" + f"This is a bug in PyTorch. Please file an issue at " + f"https://github.com/pytorch/pytorch/issues\n\n" + f"Nodes involved in the conflict:\n" + f"{constraints_str}\n\n" + f"[For PyTorch developers: one of the above constraints is wrong. " + f"Either the node should be recomputable, saveable, or not required for backward.]\n\n" + f"[Debug: min-cut path] {raw_path_str}\n" + f"{local_files_msg}" + f"{tlparse_msg}" + ) from unbounded_exc + + # Fallback if we couldn't find the path + log.info("Failed to compute min-cut on following graph:") + log.info( + "%s", + LazyString( + lambda: "\n".join(nx.readwrite.edgelist.generate_edgelist(nx_graph)) + ), + ) + visualize_min_cut_graph(nx_graph) + raise + except Exception: + log.info("Failed to compute min-cut on following graph:") + log.info( + "%s", + LazyString( + lambda: "\n".join(nx.readwrite.edgelist.generate_edgelist(nx_graph)) + ), + ) + visualize_min_cut_graph(nx_graph) + raise + + reachable, non_reachable = partition + cutset: OrderedSet[tuple[str, str]] = OrderedSet() + for u, nbrs in ((n, nx_graph[n]) for n in reachable): + cutset.update((u, v) for v in nbrs if v in non_reachable) + + cut_nodes: OrderedSet[str] = OrderedSet() + for node_in, node_out in cutset: + if node_in[:-3] != node_out[:-4]: + raise AssertionError( + f"node_in[:-3]={node_in[:-3]} != node_out[:-4]={node_out[:-4]}" + ) + node_name = node_in[:-3] + cut_nodes.add(node_name) + + name_to_node = get_name_to_node(joint_graph) + # To make this stuff deterministic + node_idx = {node: idx for idx, node in enumerate(joint_graph.nodes)} + saved_values = sorted( + (name_to_node[node] for node in cut_nodes), key=lambda x: node_idx[x] + ) + return saved_values, banned_nodes + + +def _find_infinite_capacity_path( + nx_graph: nx.DiGraph[str, dict[str, Any]], +) -> list[tuple[str, str, str]] | None: + """BFS from source to sink following only infinite-capacity edges. + + Returns a list of (from_node, to_node, reason) tuples representing the path, + or None if no such path exists. + """ + + visited = OrderedSet(["source"]) + # Each queue item: (current_node, path_of_edges) + # where path_of_edges is a list of (from_node, to_node, reason) tuples + queue: deque[tuple[str, list[tuple[str, str, str]]]] = deque([("source", [])]) + + while queue: + node, edge_path = queue.popleft() + for neighbor in nx_graph.successors(node): + if neighbor in visited: + continue + edge_data = nx_graph[node][neighbor] + capacity = edge_data.get("capacity", 0) + # Check for infinite capacity (either math.inf or INT_INF) + if capacity == math.inf or capacity == INT_INF: + reason = edge_data.get("reason", "unknown") + new_edge = (node, neighbor, reason) + new_path = edge_path + [new_edge] + if neighbor == "sink": + return new_path + visited.add(neighbor) + queue.append((neighbor, new_path)) + return None + + +def _get_unique_path(base_name: str, extension: str) -> str: + """Get a unique file path, appending a counter if the file already exists. + + For example, if "min_cut_failed.svg" exists, returns "min_cut_failed_1.svg". + """ + path = f"{base_name}{extension}" + if not os.path.exists(path): + return path + + counter = 1 + while os.path.exists(f"{base_name}_{counter}{extension}"): + counter += 1 + return f"{base_name}_{counter}{extension}" + + +def visualize_min_cut_graph( + nx_graph: nx.DiGraph[str, dict[str, Any]], +) -> tuple[str | None, str | None]: + """Visualize the min-cut graph to an SVG file. + + Returns (path_to_svg, svg_content) tuple. Both are None if pydot is unavailable. + """ + import networkx as nx + + try: + import pydot + except ImportError: + log.info( + "Install pydot to visualize the min-cut graph for debugging: pip install pydot", + exc_info=True, + ) + return None, None + + dot_format = nx.nx_pydot.to_pydot(nx_graph).to_string() + dot_graph = pydot.graph_from_dot_data(dot_format)[0] # type: ignore[index] + for edge in dot_graph.get_edges(): + weight = nx_graph[edge.get_source()][edge.get_destination()]["capacity"] + # Set edge label to weight + edge.set_label(str(weight)) # type: ignore[union-attr] + # Color edges with weight 'inf' as red + if weight == float("inf"): + edge.set_color("red") # type: ignore[union-attr] + + # Generate SVG content + svg_content = dot_graph.create_svg().decode("utf-8") # type: ignore[union-attr] + + # Write to local file + svg_path = _get_unique_path("min_cut_failed", ".svg") + with open(svg_path, "w") as f: + f.write(svg_content) + + return svg_path, svg_content + + +def get_default_op_list() -> OpTypes: + default_recomputable_ops: list[Callable[..., Any]] = [ + aten.add, + aten.sub, + aten.div, + aten.atan2, + aten.mul, + aten.max, + aten.min, + aten.pow, + aten.remainder, + aten.fmod, + aten.__and__, + aten.__or__, + aten.__xor__, + aten.__lshift__, + aten.__rshift__, + aten.eq, + aten.ne, + aten.ge, + aten.gt, + aten.le, + aten.lt, + aten.abs, + aten.bitwise_not, + aten.ceil, + aten.floor, + aten.frac, + aten.neg, + aten.relu, + aten.round, + aten.silu, + aten.trunc, + aten.log, + aten.log10, + aten.log1p, + aten.log2, + aten.lgamma, + aten.exp, + aten.expm1, + aten.erf, + aten.erfc, + aten.cos, + aten.acos, + aten.cosh, + aten.sin, + aten.asin, + aten.sinh, + aten.tan, + aten.atan, + aten.tanh, + aten.atanh, + aten.sqrt, + aten.rsqrt, + aten.reciprocal, + aten.sigmoid, + aten.softplus, + aten.threshold, + aten.threshold_backward, + aten.clamp, + aten.where, + aten.lerp, + aten.addcmul, + aten.gelu, + aten.gelu_backward, + aten.sum, + aten.mean, + aten._grad_sum_to_size, + aten.sum_to_size, + aten.amax, + aten.to, + aten.type_as, + operator.getitem, + aten.squeeze, + aten.unsqueeze, + aten.rsub, + aten._to_copy, + ] + recomputable_view_ops = [aten.squeeze, aten.unsqueeze, aten.alias] + recomputable_view_ops += [ + aten.view, + aten.slice, + aten.t, + prims.broadcast_in_dim, + aten.expand, + aten.as_strided, + aten.permute, + aten.select, + aten.split, + ] + view_ops = recomputable_view_ops + default_recomputable_ops += [ + prims.div, + prims.convert_element_type, + prims.prepare_softmax_online, + aten.clone, + aten._to_copy, + aten.full_like, + prims.var, + prims.sum, + aten.var, + aten.std, + prims.broadcast_in_dim, + aten.select, + aten._unsafe_view, + aten.view, + aten.expand, + aten.slice, + aten.reshape, + aten.broadcast_tensors, + aten.scalar_tensor, + aten.ones, + aten.new_zeros, + aten.lift_fresh_copy, + aten.arange, + aten.triu, + aten.var_mean, + aten.isinf, + aten.any, + aten.full, + aten.as_strided, + aten.zeros, + aten.empty, + aten.empty_like, + aten.argmax, + aten.maximum, + prims.iota, + prims._low_memory_max_pool_offsets_to_indices, + ] + # Natalia said that we should allow recomputing indexing :) + default_recomputable_ops += [aten.index, aten.gather] + default_recomputable_ops += view_ops + + default_recomputable_ops += pointwise_ops() + + default_recomputable_ops += [ + aten.zeros_like, + ] + + default_recomputable_ops += [method_to_operator(m) for m in magic_methods] + recomputable_ops = OrderedSet(default_recomputable_ops) + + random_ops = OrderedSet[Callable[..., Any]]( + [aten.native_dropout, aten.rand_like, aten.randn_like] + ) + compute_intensive_ops = [ + aten.mm, + aten.convolution, + aten.convolution_backward, + aten.bmm, + aten.addmm, + aten._scaled_dot_product_flash_attention, + aten._scaled_dot_product_efficient_attention, + aten._flash_attention_forward, + aten._efficient_attention_forward, + aten.upsample_bilinear2d, + aten._scaled_mm, + ] + + fusible_ops = recomputable_ops | random_ops + return OpTypes( + fusible_ops, + OrderedSet(compute_intensive_ops), + random_ops, + OrderedSet(view_ops), + recomputable_ops, + ) + + +def get_name_to_node(graph: fx.Graph) -> dict[str, fx.Node]: + name_to_node: dict[str, fx.Node] = {} + for node in graph.nodes: + name_to_node[node.name] = node + return name_to_node + + +def _optimize_runtime_with_given_memory( + joint_graph: fx.Graph, + memory: list[float], + runtimes: list[float], + max_memory: float, + node_info: NodeInfo, + all_recomputable_banned_nodes: list[fx.Node], +) -> tuple[float, list[int], list[int]]: + SOLVER = config.activation_memory_budget_solver + if SOLVER == "greedy": + return greedy_knapsack(memory, runtimes, max_memory) + elif SOLVER == "ilp": + return ilp_knapsack(memory, runtimes, max_memory) + elif SOLVER == "dp": + return dp_knapsack(memory, runtimes, max_memory) + elif SOLVER == "dp_knapsack_sliding_hirschberg": + return dp_knapsack_sliding_hirschberg(memory, runtimes, max_memory) + elif SOLVER == "dynamic_memory_budget_dp": + log.warning( + "dynamic_memory_budget_dp is an experimental solver. " + "It does not guarantee performance improvements. " + "Additionally, it is not guaranteed to be stable." + ) + graph_info_provider = GraphInfoProvider.inialize_from_graph( + joint_graph=joint_graph, + all_recomputable_banned_nodes=all_recomputable_banned_nodes, + recorded_knapsack_input_memories=memory, + recorded_knapsack_input_runtimes=runtimes, + ) + return dp_knapsack( + memory, + runtimes, + KnapsackEvaluator( + graph_info_provider=graph_info_provider, + ).get_knee_point_memory_budget( + knapsack_algo=dp_knapsack, + max_mem_budget=max_memory, + ), + ) + elif isinstance(SOLVER, CustomKnapsackSolver): + saved_node_idx, recomp_node_idx = SOLVER( + memory, joint_graph, max_memory, node_info, all_recomputable_banned_nodes + ) + return (0.0, saved_node_idx, recomp_node_idx) + else: + raise RuntimeError(f"Not aware of memory budget knapsack solver: {SOLVER}") + + +from torch.utils._mode_utils import no_dispatch + + +# replace symbols in size and strides with their hints without guarding. +def _remove_symbols_without_guarding(x: torch.Tensor, fallback: int) -> torch.Tensor: + shape = list(x.shape) + + def realize_symbol(d: torch.SymInt | int) -> int: + return optimization_hint(d, fallback=fallback) + + shape = [realize_symbol(s) for s in shape] + stride = [realize_symbol(s) for s in x.stride()] + return x.new_empty_strided(shape, stride=stride) + + +def estimate_runtime(node: fx.Node) -> float: + RUNTIME_MODE = config.activation_memory_budget_runtime_estimator + + def materialize_arg(x: Any) -> Any: + if isinstance(x, fx.Node) and isinstance(x.meta["val"], torch.Tensor): + return _remove_symbols_without_guarding(x.meta["val"], fallback=4096) + elif isinstance(x, fx.Node) and isinstance(x.meta["val"], torch.SymInt): + return optimization_hint(x.meta["val"], fallback=4096) + elif isinstance(x, fx.Node) and isinstance(x.meta["val"], torch.SymFloat): + return 1.0 + elif isinstance(x, fx.Node) and isinstance(x.meta["val"], torch.SymBool): + return True + else: + return x + + if RUNTIME_MODE == "testing": + return 1 + + elif RUNTIME_MODE == "profile": + with no_dispatch(): + from torch._inductor.runtime.benchmarking import benchmarker + + args, kwargs = pytree.tree_map(materialize_arg, (node.args, node.kwargs)) + # pyrefly: ignore[not-callable] + ms = benchmarker.benchmark_gpu(lambda: node.target(*args, **kwargs)) + return ms + + elif RUNTIME_MODE == "flops": + # todo(chilli): Normalize this to also return ms + from torch.utils.flop_counter import FlopCounterMode + + args, kwargs = pytree.tree_map(materialize_arg, (node.args, node.kwargs)) + with FlopCounterMode(display=False) as mode: + # pyrefly: ignore[not-callable] + node.target(*args, **kwargs) + counted_flops = mode.get_total_flops() + return max(counted_flops, 1) + + elif isinstance(RUNTIME_MODE, CustomRuntimeEstimator): + return RUNTIME_MODE(node) + + else: + raise RuntimeError(f"Not aware of runtime estimator: {RUNTIME_MODE}") + + +def choose_saved_values_set( + joint_graph: fx.Graph, + node_info: NodeInfo, + memory_budget: float = 1, +) -> list[fx.Node]: + if memory_budget > 1 or memory_budget < 0: + raise RuntimeError( + f"The valid ranges for memory budget are 0 <= m <= 1. The provided value is {memory_budget}" + ) + min_cut_options = MinCutOptions( + ban_if_used_far_apart=config.ban_recompute_used_far_apart, + ban_if_long_fusible_chains=config.ban_recompute_long_fusible_chains, + ban_if_materialized_backward=config.ban_recompute_materialized_backward, + ban_if_not_in_allowlist=config.ban_recompute_not_in_allowlist, + ban_if_reduction=config.ban_recompute_reductions, + ) + + if config.aggressive_recomputation: + min_cut_options = replace( + min_cut_options, + ban_if_used_far_apart=False, + ban_if_long_fusible_chains=False, + ban_if_materialized_backward=False, + ban_if_not_in_allowlist=False, + ) + if memory_budget == 0: + return node_info.inputs + + runtime_optimized_saved_values, _ = solve_min_cut( + joint_graph, + node_info, + min_cut_options, + ) + # return runtime_optimized_saved_values + if memory_budget == 1: + return runtime_optimized_saved_values + + def estimate_activations_size(saved_values: list[fx.Node]) -> float: + return sum(map(_size_of, saved_values)) / 1e9 + + min_act_size = estimate_activations_size(node_info.inputs) + max_act_size = estimate_activations_size(runtime_optimized_saved_values) + # The optimized choice is smaller than the inputs anyways + if max_act_size <= min_act_size: + return runtime_optimized_saved_values + + def get_normalized_size(sz: float) -> float: + return (sz / 1e9) / (max_act_size - min_act_size) + + def get_mem_ratio(activations: list[fx.Node]) -> float: + return (estimate_activations_size(activations) - min_act_size) / ( + max_act_size - min_act_size + ) + + more_aggressive_options = replace( + min_cut_options, + ban_if_used_far_apart=False, + ban_if_long_fusible_chains=False, + ban_if_materialized_backward=False, + ) + more_aggressive_saved_values, _ = solve_min_cut( + joint_graph, node_info, more_aggressive_options + ) + more_aggressive_saved_values_mem_ratio = get_mem_ratio(more_aggressive_saved_values) + if more_aggressive_saved_values_mem_ratio < memory_budget: + return more_aggressive_saved_values + + aggressive_options = replace( + more_aggressive_options, + ban_if_not_in_allowlist=False, + ) + aggressive_recomputation_saved_values, banned_nodes = solve_min_cut( + joint_graph, node_info, aggressive_options + ) + + aggressive_recomputation_saved_values_mem_ratio = get_mem_ratio( + aggressive_recomputation_saved_values + ) + if aggressive_recomputation_saved_values_mem_ratio < memory_budget: + return aggressive_recomputation_saved_values + + from torch._inductor.fx_utils import get_node_storage + + input_storages = OrderedSet(get_node_storage(node) for node in node_info.inputs) + + def get_recomputable_banned_nodes( + banned_nodes: OrderedSet[fx.Node], + ) -> list[fx.Node]: + return [ + i + for i in banned_nodes + if ( + # Only allow recomputing nodes that are actually required for BW + i.dist_from_bw < int(1e9) # type: ignore[attr-defined] + and ( + get_node_storage(i) not in input_storages + or is_non_builtin_to_include(i) + ) + ) + ] + + recomputable_banned_nodes = get_recomputable_banned_nodes(banned_nodes) + must_save_nodes = [ + i + for i in recomputable_banned_nodes + if i.meta.get("recompute", False) == CheckpointPolicy.MUST_SAVE + ] + recomputable_banned_nodes = [ + i for i in recomputable_banned_nodes if i not in must_save_nodes + ] + + # default: runtime_optimized_saved_values + # more aggressive: more_aggressive_saved_values + # full aggressive: aggressive_recomputation_saved_values + + all_recomputable_banned_nodes = sorted( + recomputable_banned_nodes, key=_size_of, reverse=True + ) + if len(all_recomputable_banned_nodes) == 0: + # Nothing left for the knapsack to trade off, so this is the same cut the + # knapsack would return with an empty dont_ban. + return aggressive_recomputation_saved_values + memories_banned_nodes = [ + get_normalized_size(_size_of(i)) for i in all_recomputable_banned_nodes + ] + runtimes_banned_nodes = [ + estimate_runtime(node) for node in all_recomputable_banned_nodes + ] + from torch.utils._mode_utils import no_dispatch + + def get_saved_values_knapsack( + memory_budget: float, node_info: NodeInfo, joint_graph: fx.Graph + ) -> tuple[list[fx.Node], float]: + with no_dispatch(): + ( + expected_runtime, + saved_node_idxs, + recomputable_node_idxs, + ) = _optimize_runtime_with_given_memory( + joint_graph, + memories_banned_nodes, + runtimes_banned_nodes, + max(memory_budget, 0), + node_info, + all_recomputable_banned_nodes, + ) + dont_ban: OrderedSet[fx.Node] = OrderedSet() + for idx in recomputable_node_idxs: + # if idx in all_recomputable_banned_nodes: + try: + dont_ban.add(all_recomputable_banned_nodes[idx]) + except BaseException: + pass + + if not dont_ban.issubset(all_recomputable_banned_nodes): + raise AssertionError( + "dont_ban must be a subset of all_recomputable_banned_nodes" + ) + + saved_values, _ = solve_min_cut( + joint_graph, + node_info, + aggressive_options, + dont_ban, + ) + if AOT_PARTITIONER_DEBUG: + create_structured_trace_for_min_cut_info( + joint_graph=joint_graph, + all_recomputable_banned_nodes=all_recomputable_banned_nodes, + saved_node_idxs=saved_node_idxs, + recomputable_node_idxs=recomputable_node_idxs, + expected_runtime=expected_runtime, + memories_banned_nodes=[ + _size_of(i) for i in all_recomputable_banned_nodes + ], + normalized_memories_banned_nodes=memories_banned_nodes, + runtimes_banned_nodes=runtimes_banned_nodes, + min_cut_saved_values=saved_values, + memory_budget=memory_budget, + min_act_size=min_act_size, + max_act_size=max_act_size, + saved_values_act_size=estimate_activations_size(saved_values), + more_aggressive_saved_values_mem_ratio=more_aggressive_saved_values_mem_ratio, + aggressive_recomputation_saved_values_mem_ratio=aggressive_recomputation_saved_values_mem_ratio, + ) + return saved_values, expected_runtime + + if config.visualize_memory_budget_pareto: + + def estimate_for_budget(b: float) -> tuple[float, float, float]: + saved_values, expected_runtime = get_saved_values_knapsack( + b, node_info=node_info, joint_graph=joint_graph + ) + return ( + b, + sum(runtimes_banned_nodes) - expected_runtime, + get_mem_ratio(saved_values), + ) + + options = [estimate_for_budget(0.0), estimate_for_budget(1.0)] + + if options[0][1:] != options[1][1:]: + bisects = [(options[0], options[1])] + while bisects: + lhs, rhs = bisects.pop() + if rhs[0] - lhs[0] < 1e-3: + options.append(lhs) + options.append(rhs) + continue + mid = estimate_for_budget((lhs[0] + rhs[0]) / 2) + if mid[1:] != lhs[1:]: + bisects.append((lhs, mid)) + if mid[1:] != rhs[1:]: + bisects.append((mid, rhs)) + options.sort() + + import matplotlib.pyplot as plt + + x_values = [item[2] for item in options] + y_values = [item[1] for item in options] + + # Plotting the values with updated axis labels and chart title + plt.figure(figsize=(10, 6)) + plt.plot(x_values, y_values, marker="o") + + # Adding labels for each point + for i, txt in enumerate(x_values): + plt.annotate( + f"{txt:.4f}", + (txt, y_values[i]), + textcoords="offset points", + xytext=(0, 10), + ha="center", + ) + + plt.xlabel("Memory Budget") + plt.ylabel("Runtime of Recomputed Components") + plt.title("Pareto Frontier of Memory Budget vs. Recomputation Runtime") + plt.grid(True) + fig = plt.gcf() + plt.show() + fig_dir = os.getcwd() + if config.memory_budget_pareto_dir is not None: + fig_dir = config.memory_budget_pareto_dir + os.makedirs(fig_dir, exist_ok=True) + rank_suffix = "" + if torch.distributed.is_available() and torch.distributed.is_initialized(): + rank_suffix = f"_rank_{torch.distributed.get_rank()}" + fig_name = os.path.join( + fig_dir, f"memory_budget_pareto{rank_suffix}_{get_aot_graph_name()}.svg" + ) + fig.savefig(fig_name) + log.warning("Generated Pareto frontier curve at %s", fig_name) + + # todo(chilli): Estimated doesn't align exactly with actual - actual is + # usually less memory than estimated. i'm guessing (actually quite + # unsure about this) that's because estimated is just only including + # tensors we actually banned from recompute, but there may be other + # tensors that we choose to save. + + return get_saved_values_knapsack( + memory_budget=memory_budget, node_info=node_info, joint_graph=joint_graph + )[0] + + +def _stable_target_str(target: Any) -> str: + """Stringify a node target stably across processes. + + ``str()`` on a plain Python-function target (e.g. ``torch.sym_not``) renders + its ``repr`` including the object's memory address (````), which differs per process. That poisons cross-rank graph hashing. + Use FX's qualified name for callables so equal graphs hash equally. + """ + from torch.fx.node import _get_qualified_name + + if callable(target): + try: + return _get_qualified_name(target) + except Exception: + return str(target) + return str(target) + + +def _cone_hashes(graph: torch.fx.Graph) -> dict[torch.fx.Node, str]: + """Compute a forward-looking structural hash for each node. + + Each node's hash captures its "role" in the graph toward the output: + hash(self_key, sorted(cone_hash(user) for user in users)). + + For placeholders, self_key uses tensor metadata instead of the node name + (which varies across ranks). This makes the hash invariant to the original + node naming and ordering. + """ + hashes: dict[torch.fx.Node, str] = {} + for node in reversed(list(graph.nodes)): + if node.op == "placeholder": + val = node.meta.get("val") + if isinstance(val, torch.Tensor): + # Exclude shape: different ranks may have different input + # shapes (e.g., shard sizes) for structurally identical graphs. + self_key: tuple[Any, ...] = ( + "placeholder", + str(val.dtype), + val.requires_grad, + ) + elif isinstance(val, torch.SymInt): + self_key = ("placeholder", "symint") + else: + self_key = ("placeholder",) + elif node.op == "output": + self_key = ("output",) + else: + self_key = (node.op, _stable_target_str(node.target)) + + user_hashes = tuple(sorted(hashes[u] for u in node.users)) + hashes[node] = hashlib.sha256( + str((self_key, user_hashes)).encode("utf-8") + ).hexdigest() + + return hashes + + +def _canonical_node_names(graph: torch.fx.Graph) -> dict[torch.fx.Node, str]: + """Build a canonical name mapping for graph nodes using Kahn's algorithm. + + Returns a dict mapping each node to a deterministic name like "node_0", + "node_1", etc. The mapping is invariant to the original node ordering and + naming, so structurally equivalent graphs (e.g., traced with different dict + iteration orders across distributed ranks) produce identical mappings. + + Does NOT modify the graph. + """ + cone = _cone_hashes(graph) + + indeg: dict[torch.fx.Node, int] = dict.fromkeys(graph.nodes, 0) + for node in graph.nodes: + for user in node.users: + indeg[user] += 1 + + canonical_idx: dict[torch.fx.Node, int] = {} + + def _canonical_key(node: torch.fx.Node) -> tuple[Any, ...]: + if node.op == "placeholder": + val = node.meta.get("val") + if isinstance(val, torch.Tensor): + # Exclude shape: different ranks may have different input + # shapes (e.g., shard sizes) for structurally identical graphs. + meta_key: tuple[Any, ...] = ( + str(val.dtype), + val.requires_grad, + ) + elif isinstance(val, torch.SymInt): + meta_key = ("symint",) + else: + meta_key = () + return (0, meta_key, cone[node]) + elif node.op == "get_attr": + return (1, str(node.target)) + elif node.op == "output": + return (3,) + else: + input_indices = tuple(canonical_idx[n] for n in node.all_input_nodes) + return (2, _stable_target_str(node.target), input_indices) + + # Seed the heap with nodes that have no dependencies. + # The counter ensures deterministic ordering when keys are equal. + counter = 0 + ready: list[tuple[tuple[Any, ...], int, fx.Node]] = [] + for node in graph.nodes: + if indeg[node] == 0: + heapq.heappush(ready, (_canonical_key(node), counter, node)) + counter += 1 + + canonical_order: list[fx.Node] = [] + + while ready: + _, _, cur = heapq.heappop(ready) + canonical_order.append(cur) + canonical_idx[cur] = len(canonical_idx) + + for user in cur.users: + indeg[user] -= 1 + if indeg[user] == 0: + heapq.heappush(ready, (_canonical_key(user), counter, user)) + counter += 1 + + return {node: f"node_{i}" for i, node in enumerate(canonical_order)} + + +def _sync_decision_cross_ranks( + joint_graph: torch.fx.Graph, saved_values: list[torch.fx.Node] +) -> list[torch.fx.Node]: + # use the same policy across different GPUs + from torch._subclasses.fake_tensor import unset_fake_temporarily + + def has_collectives(joint_graph: torch.fx.Graph) -> bool: + for node in joint_graph.nodes: + if isinstance( + node.target, torch._ops.OpOverload + ) and node.target.namespace in {"_c10d_functional", "c10d_functional"}: + return True + return False + + if not ( + torch.distributed.is_available() + and torch.distributed.is_initialized() + and torch.distributed.get_world_size() > 1 + and has_collectives(joint_graph) + ): + return saved_values + + canonical = _canonical_node_names(joint_graph) + reverse_canonical = {v: k for k, v in canonical.items()} + + def has_same_nodes(joint_graph: torch.fx.Graph) -> bool: + # Use canonical names for a hash that is invariant to node ordering + # and naming. This correctly identifies structurally equivalent graphs + # even when different ranks trace with different dict iteration orders. + def _node_hash_str(n: torch.fx.Node) -> str: + # For placeholders, n.target is the rank-local name (e.g., + # primals_1) which may refer to different inputs on different + # ranks. Use only the canonical name and op for these. + if n.op == "placeholder": + return f"{canonical[n]}:{n.op}" + return f"{canonical[n]}:{n.op}:{_stable_target_str(n.target)}" + + node_str = "/".join( + _node_hash_str(n) + for n in sorted(joint_graph.nodes, key=lambda n: canonical[n]) + ) + inputs = hashlib.sha256(node_str.encode("utf-8")).hexdigest() + all_inputs = [None for _ in range(torch.distributed.get_world_size())] + with no_dispatch(), unset_fake_temporarily(): + # TODO: maybe use a different process group? + torch.distributed.all_gather_object(all_inputs, inputs) + for rank, x in enumerate(all_inputs): + if all_inputs[0] != x: + log.debug( + "Skipping sync decision cross rank due to different inputs between rank 0 and rank %s", + rank, + ) + return False + return True + + if has_same_nodes(joint_graph): + with no_dispatch(), unset_fake_temporarily(): + # Communicate saved values using canonical names so that + # node names (which may differ across ranks) don't matter. + objects = [[canonical[x] for x in saved_values]] + saved_ops_names_all_ranks: list[list[str]] = [ + [] for _ in range(torch.distributed.get_world_size()) + ] + torch.distributed.all_gather_object(saved_ops_names_all_ranks, objects[0]) + saved_sizes: list[int] = [] + saved_ops_with_sizes: dict[str, int] = {} + + for idx, saved_ops_names in enumerate(saved_ops_names_all_ranks): + saved_nodes = [ + reverse_canonical[op_name] for op_name in saved_ops_names + ] + saved_size = 0 + for node in saved_nodes: + size_of_node = _size_of(node) + saved_size += size_of_node + if idx == torch.distributed.get_rank(): + saved_ops_with_sizes[node.name] = size_of_node + saved_ops_with_sizes["total size"] = saved_size + saved_sizes.append(saved_size) + + saved_sizes_tensor = torch.tensor( + saved_sizes, + device=torch.distributed.distributed_c10d._get_object_coll_device(), + ) + torch.distributed.all_reduce( + saved_sizes_tensor, op=torch.distributed.distributed_c10d.ReduceOp.MAX + ) + + picked_rank_idx = int(torch.argmin(saved_sizes_tensor).item()) + sync_decision_cross_ranks_str = f"picked_rank_idx={picked_rank_idx}, saved_nodes of current rank={saved_ops_with_sizes}" + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "aot_joint_graph_sync_decision_cross_ranks", + "encoding": "string", + }, + payload_fn=lambda: sync_decision_cross_ranks_str, + ) + + saved_values = [ + reverse_canonical[n] for n in saved_ops_names_all_ranks[picked_rank_idx] + ] + + return saved_values + + +def thread_graphsafe_rng_from_hops( + module: fx.GraphModule, is_backward: bool +) -> fx.GraphModule: + """ + Graph-safe RNG lets torch.compile use CUDA Graphs for graphs with RNG ops. + For graphs without HOPs, the partitioner adds placeholder nodes + fwd_rng_state_* and bw_rng_state_* to the forward and backward graphs. At + runtime, the AOTDispatcher retrieves these RNG states and passes them to the + compiled graphs. + + This works well for no-HOP graphs. With HOPs, the partitioner runs + recursively: it first partitions the HOP (producing forward/backward HOP + subgraphs) and then stitches them back into the outer joint graph. For HOPs + that contain RNG ops, the outer joint graph now includes HOP subgraph + modules with extra RNG placeholders. We must thread these placeholders + through the outer module partitioned forward and backward graphs—this + function does exactly that. It collects the RNG placeholder nodes from the + HOPs and creates corresponding placeholders in the outer forward and + backward graphs. + + There is a catch: for a short period, the joint graph is in a “bad” state. + The HOP subgraphs expect additional inputs (because of the new + placeholders), but the outer graph call sites don't yet provide them. We + can't fix this in the joint graph because the joint graph's input signature + is fixed (primals, tangents). As a compromise, we keep the joint graph in + somewhat of a bad state for some time and, once the outer forward and + backward graphs are partitioned, insert the corresponding RNG placeholders + and wire up the calls. + """ + + rng_count = 0 + rng_string = "bwd_rng_state" if is_backward else "fwd_rng_state" + last_input = next(reversed(module.graph.find_nodes(op="placeholder"))) + for hop_node in module.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ): + subgraph = getattr(module, hop_node.args[0].target) + if isinstance(subgraph, fx.GraphModule): + new_rng_inputs: list[fx.Node] = [] + for placeholder_node in subgraph.graph.find_nodes(op="placeholder"): + if rng_string in placeholder_node.name: + # Found a rng state placeholder in the hop graph, lets add + # the corresponding node in the outer graph + with module.graph.inserting_after(last_input): + rng_state = module.graph.placeholder( + f"{rng_string}_{rng_count}" + ) + rng_count += 1 + rng_state.meta["val"] = placeholder_node.meta["val"] + last_input = rng_state + new_rng_inputs.append(rng_state) + + if new_rng_inputs: + # Pass on the new args that include the new_rng_inputs + with module.graph.inserting_after(hop_node): + new_hop_node_with_fixed_args = module.graph.create_node( + "call_function", + torch.ops.higher_order.invoke_subgraph, + (*hop_node.args, *new_rng_inputs), # type: ignore[arg-type] + {}, + ) + hop_node.replace_all_uses_with( + new_hop_node_with_fixed_args, propagate_meta=True + ) + + # Setup the eager_input_vals + eager_vals = hop_node.meta.get("eager_input_vals") + if eager_vals: + eager_args, eager_kwargs = eager_vals + new_eager_args = ( + *eager_args, + *[inp.meta["val"] for inp in new_rng_inputs], + ) + new_hop_node_with_fixed_args.meta["eager_input_vals"] = ( + new_eager_args, + eager_kwargs, + ) + module.graph.erase_node(hop_node) + + return module + + +def classify_nodes( + joint_module: fx.GraphModule, + static_lifetime_input_indices: list[int], + num_fwd_outputs: int, +) -> NodeInfo: + name_to_node = get_name_to_node(joint_module.graph) + required_bw_nodes: OrderedSet[fx.Node] = OrderedSet() + for node in joint_module.graph.nodes: + if node.op == "placeholder" and "tangents" in node.target: + required_bw_nodes.add(node) + elif _must_be_in_backward(node): + required_bw_nodes.add(node) + + if node in required_bw_nodes: + if node.op == "call_function" and node.target is control_deps_hop: + # control_deps mixes forward and backward deps. Only + # propagate required_bw to getitem users that extract a + # backward-only dep. getitem(cd, k) with k>=1 maps to + # deps[k-1] (args[k+1]). + deps = node.args[2:] + for user in node.users: + if ( + user.target is operator.getitem + and isinstance(user.args[1], int) + and 1 <= user.args[1] <= len(deps) + ): + dep = deps[user.args[1] - 1] + if isinstance(dep, fx.Node) and dep in required_bw_nodes: + required_bw_nodes.add(user) + else: + # Chained control_deps (e.g. wait/sync cd depends on + # the record's cd via additional_deps) -- taint + # conservatively. + required_bw_nodes.add(user) + else: + required_bw_nodes.update(node.users) + + primal_inputs = list(filter(_is_primal, joint_module.graph.nodes)) + fwd_seed_offset_inputs = list(filter(_is_fwd_seed_offset, joint_module.graph.nodes)) + inputs = primal_inputs + fwd_seed_offset_inputs + fwd_outputs, bwd_outputs, fwd_outputs_descs, bwd_outputs_descs = ( + _extract_fwd_bwd_outputs(joint_module, num_fwd_outputs=num_fwd_outputs) + ) + # Note: [tangents_closure vs required_bw_nodes] + # + # required_bw_nodes is used to determine which nodes need edges to + # the sink. It is important to also track tangents closure because + # that determines whether you can save that tensor, i.e., whether you + # want to connect x_in or x_out to the sink. + tangents_closure = required_bw_nodes.copy() + required_bw_nodes.update( + o for o in bwd_outputs if o is not None and o.op != "output" + ) + forward_only_graph = _extract_graph_with_inputs_outputs( + joint_module.graph, inputs, fwd_outputs, fwd_outputs_descs, "forward" + ) + required_fw_nodes: OrderedSet[fx.Node] = OrderedSet( + name_to_node[node.name] + for node in forward_only_graph.nodes + if node.op != "output" and node.name in name_to_node + ) + unclaimed_nodes: OrderedSet[fx.Node] = OrderedSet( + node + for node in joint_module.graph.nodes + if node not in required_fw_nodes and node not in required_bw_nodes + ) + static_lifetime_input_nodes = OrderedSet( + p for i, p in enumerate(primal_inputs) if i in static_lifetime_input_indices + ) + fw_cnt = 0 + fw_order = {} + for node in joint_module.graph.nodes: + if node in required_fw_nodes: + fw_order[node] = fw_cnt + fw_cnt += 1 + return NodeInfo( + inputs, + required_fw_nodes, + required_bw_nodes, + tangents_closure, + unclaimed_nodes, + fw_order, + static_lifetime_input_nodes, + ) + + +def min_cut_rematerialization_partition( + joint_module: fx.GraphModule, + _joint_inputs: Any, + compiler: str = "inductor", + *, + num_fwd_outputs: int, + static_lifetime_input_indices: list[int] | None = None, +) -> tuple[fx.GraphModule, fx.GraphModule]: + """ + Partitions the joint graph such that the backward recomputes the forward. + Recomputing helps in trading off memory bandwidth with computation. + + To create the fwd and bwd graph, we copy the joint graph, manually set the + outputs to just original forward or backward outputs. And then we run the + resulting graphs through dead code elimination. + + .. warning:: + This API is experimental and likely to change. + + Args: + joint_module(fx.GraphModule): The joint forward and backward graph. This + is the result of AOT Autograd tracing. + _joint_inputs: The inputs to the joint graph. This is unused. + compiler: This option determines the default set of recomputable ops. + Currently, there are two options: ``nvfuser`` and ``inductor``. + recomputable_ops: This is an optional set of recomputable ops. If this + is not None, then this set of ops will be used instead of the + default set of ops. + num_fwd_outputs: The number of outputs from the forward graph. + + Returns: + Returns the generated forward and backward Fx graph modules. + """ + + joint_module.graph.eliminate_dead_code() + joint_module.recompile() + + fx_g = joint_module.graph + + # add the CSE pass + if config.cse: + # CSE runs before partitioning, so do not merge a forward-only value + # with a value that is also needed by the backward graph. Otherwise the + # partitioner may save the merged value as an extra forward output. + _, bwd_outputs, _, _ = _extract_fwd_bwd_outputs( + joint_module, num_fwd_outputs=num_fwd_outputs + ) + backward_dependencies: OrderedSet[fx.Node] = OrderedSet() + + backward_dependency_stack = [ + output + for output in bwd_outputs + if output is not None and output.op != "output" + ] + while backward_dependency_stack: + node = backward_dependency_stack.pop() + if node in backward_dependencies: + continue + backward_dependencies.add(node) + backward_dependency_stack.extend(node.all_input_nodes) + + def partition_key(node: fx.Node) -> bool: + return node in backward_dependencies + + cse_graph = fx_graph_cse(fx_g, extra_node_key=partition_key) + joint_module.graph = cse_graph + joint_graph = joint_module.graph + + graph_has_recomputable_ops = has_recomputable_ops(joint_module) + graph_has_recomputable_rng_ops = has_recomputable_rng_ops(joint_module) + if graph_has_recomputable_ops: + joint_module = cleanup_recompute_tags(joint_module, is_default_partition=False) + if not config.unsafe_allow_optimization_of_collectives: + force_save_collectives(joint_module) + + force_save_effectful_ops(joint_module) + force_save_bw_mutation_src(joint_module) + + if static_lifetime_input_indices is None: + static_lifetime_input_indices = [] + node_info = classify_nodes( + joint_module, static_lifetime_input_indices, num_fwd_outputs + ) + + # networkx blows up on graphs with no required backward nodes + # Since there's nothing to partition anyway, and the default partitioner can "handle" + # this case, send our graph over to the default partitioner. + if len(node_info.required_bw_nodes) == 0: + return default_partition( + joint_module, + _joint_inputs, + num_fwd_outputs=num_fwd_outputs, + static_lifetime_input_indices=static_lifetime_input_indices, + static_lifetime_input_nodes=node_info.static_lifetime_input_nodes, + ) + + for node in reversed(joint_module.graph.nodes): + if node.op == "output": + node.dist_from_bw = int(1e9) + elif not node_info.is_required_fw(node): + node.dist_from_bw = 0 + else: + node.dist_from_bw = int(1e9) + for user in node.users: + node.dist_from_bw = min(node.dist_from_bw, user.dist_from_bw + 1) + + # memory_budget override resolution, in increasing precedence: + # 1. config.activation_memory_budget (global default). + # 2. Legacy node.meta["memory_budget"], set by the old + # `MemoryBudgetMode` / `set_memory_budget` allow_in_graph marker. First + # matching node wins (preserves prior behavior); we may want to remove + # this path later. + # 3. `torch.autograd.graph.region_activation_memory_budget(...)`, read off + # node.meta["custom"] via `_get_memory_budget_annotation` and propagated + # onto every annotated node via _COPY_META_FIELDS["custom"]; overrides + # the legacy reader. + memory_budget = config.activation_memory_budget + for node in joint_graph.nodes: + if isinstance(node.meta.get("memory_budget", None), float): + memory_budget = node.meta["memory_budget"] + break + + # The partitioner applies a single budget per joint graph, so all annotated + # nodes must agree and the annotation must cover every forward op; otherwise + # the caller mixed budgets or annotated only part of a graph (across a graph + # break each graph is resolved independently). Collect both in one pass. + region_budgets: OrderedSet[float] = OrderedSet() + unannotated_fw_ops: list[fx.Node] = [] + for node in joint_graph.nodes: + budget = _get_memory_budget_annotation(node) + if budget is not None: + region_budgets.add(budget) + elif node.op == "call_function" and node_info.is_required_fw(node): + unannotated_fw_ops.append(node) + + # A budget must consistently cover the entire forward, including HOP bodies. + # Recurse into nested subgraph modules: collect their budgets (for the + # agreement check) and flag any unannotated call_function (for coverage). In + # a consistent graph every node in every body carries the budget, so an + # unannotated body op means the budget did not cover that HOP. + all_budgets: OrderedSet[float] = OrderedSet(region_budgets) + for _, sub in joint_module.named_modules(): + if isinstance(sub, fx.GraphModule) and sub.graph is not joint_graph: + for node in sub.graph.nodes: + b = _get_memory_budget_annotation(node) + if b is not None: + all_budgets.add(b) + elif node.op == "call_function": + unannotated_fw_ops.append(node) + if len(all_budgets) > 1: + raise RuntimeError( + f"torch.autograd.graph.region_activation_memory_budget: " + f"conflicting budgets within a single joint graph (including nested " + f"subgraphs): {sorted(all_budgets)}. Use a graph break to separate " + f"regions that need different budgets." + ) + + if all_budgets: + if unannotated_fw_ops: + raise RuntimeError( + f"torch.autograd.graph.region_activation_memory_budget: must " + f"cover the entire forward of a graph (including HOP bodies), but " + f"{len(unannotated_fw_ops)} forward op(s) are unannotated. Wrap " + f"the whole forward in a single region; use a graph break to scope " + f"different budgets to different graphs. Note that a graph break " + f"inside the annotated region can also cause unannotated ops here. " + f"Unannotated ops: {[n.name for n in unannotated_fw_ops]}." + ) + memory_budget = next(iter(all_budgets)) + saved_values = choose_saved_values_set( + joint_graph, + node_info, + memory_budget=memory_budget, + ) + # pyrefly: ignore [unbound-name] + if config._sync_decision_cross_ranks: + saved_values = _sync_decision_cross_ranks(joint_graph, saved_values) + + saved_sym_nodes = list( + filter( + lambda n: is_sym_node(n) and not _is_assert_only_symbool(n), saved_values + ) + ) + saved_opaque_nodes = list(filter(is_opaque_node, saved_values)) + saved_values = list( + filter(lambda n: not is_sym_node(n) and not is_opaque_node(n), saved_values) + ) + + # NB: saved_sym_nodes will be mutated to reflect the actual saved symbols + fw_module, bw_module = _extract_fwd_bwd_modules( + joint_module, + saved_values, + # pyrefly: ignore [bad-argument-type] + saved_sym_nodes=saved_sym_nodes, + saved_opaque_nodes=saved_opaque_nodes, + num_fwd_outputs=num_fwd_outputs, + static_lifetime_input_nodes=node_info.static_lifetime_input_nodes, + ) + if graph_has_recomputable_ops: + if graph_has_recomputable_rng_ops: + fw_module, bw_module = functionalize_rng_ops( + joint_module, fw_module, bw_module, len(saved_sym_nodes) + ) + bw_module = reordering_to_mimic_autograd_engine(bw_module) + + # pyrefly: ignore [unbound-name] + if config.enable_activation_offloading: + from ._activation_offloading.activation_offloading import ( + enable_activation_offloading, + ) + + enable_activation_offloading( + fw_module, + bw_module, + num_fwd_outputs, + node_info.static_lifetime_input_nodes, + ) + + # raise all getitem ops to as early as possible + # this is helpful for memory, especially in the case of aot_eager backend + fw_module = raise_getitems(fw_module) + bw_module = raise_getitems(bw_module) + + fw_module = thread_graphsafe_rng_from_hops(fw_module, is_backward=False) + bw_module = thread_graphsafe_rng_from_hops(bw_module, is_backward=True) + + if AOT_PARTITIONER_DEBUG: + # Calculate sorted sizes of saved values + sorted_sizes = sorted([(_size_of(i), str(i)) for i in saved_values]) + + # Log total theoretical activations stored + total_activations_size_gb = sum(_size_of(i) for i in saved_values) / 1e9 + log.info("Theoretical Activations Stored: %.2f GB", total_activations_size_gb) + + # Log theoretical per activation storage sizes + log.info("Theoretical Per Activation Storage Sizes: %s", sorted_sizes) + fw_module_nodes = OrderedSet( + node.name for node in fw_module.graph.nodes if node.op == "call_function" + ) + bw_module_nodes = OrderedSet( + node.name for node in bw_module.graph.nodes if node.op == "call_function" + ) + remat_nodes = fw_module_nodes & bw_module_nodes + + counts: dict[str, int] = defaultdict(int) + for node in fw_module.graph.nodes: + if node.name in remat_nodes and hasattr(node.target, "_overloadpacket"): + counts[str(node.target._overloadpacket)] += 1 + log.info( + "# remat/fw/bw: %d/%d/%d", + len(remat_nodes), + len(fw_module_nodes), + len(bw_module_nodes), + ) + rematerialized_ops = sorted( + counts.items(), key=operator.itemgetter(1), reverse=True + ) + log.info("Count of Ops Rematerialized: %s", rematerialized_ops) + return fw_module, bw_module + + +def draw_graph( + traced: torch.fx.GraphModule, + fname: str, + figname: str = "fx_graph", + clear_meta: bool = True, + prog: str | list[str] | None = None, + parse_stack_trace: bool = False, + dot_graph_shape: str | None = None, +) -> None: + if clear_meta: + new_graph = copy.deepcopy(traced.graph) + traced = fx.GraphModule(traced, new_graph) + for node in traced.graph.nodes: + node.meta = {} # pyrefly: ignore[implicit-any] + base, ext = os.path.splitext(fname) + if not ext: + ext = "." + config.torch_compile_graph_format + log.info("Writing FX graph to file: %s%s", base, ext) + g = graph_drawer.FxGraphDrawer( + traced, + figname, + parse_stack_trace=parse_stack_trace, + dot_graph_shape=dot_graph_shape, + ) + x = g.get_main_dot_graph() + fname = f"{base}{ext}" + graph_format = ext.lstrip(".") + if graph_format in {"dot", "raw"}: + # pydot's write_dot() invokes Graphviz with -Tdot. For large FX graphs + # that layout step can dominate compile debugging, so write raw DOT + # source directly for text graph dumps. + x.write(fname) + elif prog is None: + write_method = getattr(x, "write_" + graph_format) + write_method(fname) + else: + write_method = getattr(x, "write_" + graph_format) + write_method(fname, prog=prog) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/predispatch.py b/.venv/lib/python3.12/site-packages/torch/_functorch/predispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..c482ff18cefa595786d7c9c9f9a672bb7def8673 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/predispatch.py @@ -0,0 +1,297 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +""" +This module contains pre-dispatch wrappers for functorch operations +that enable proper tracing in PT2 non-strict export/compile fx graph. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from torch._C import ( + _enter_dual_level as _enter_dual_level_impl, + _exit_dual_level as _exit_dual_level_impl, +) +from torch._C._functorch import ( + _add_batch_dim as _add_batch_dim_impl, + _jvp_decrement_nesting as _jvp_decrement_nesting_impl, + _jvp_increment_nesting as _jvp_increment_nesting_impl, + _remove_batch_dim as _remove_batch_dim_impl, + _unwrap_for_grad as _unwrap_for_grad_impl, + _vmap_decrement_nesting as _vmap_decrement_nesting_impl, + _vmap_increment_nesting as _vmap_increment_nesting_impl, +) +from torch._VF import ( # type: ignore[attr-defined] + _make_dual as _make_dual_impl, + _unpack_dual as _unpack_dual_impl, +) + + +if TYPE_CHECKING: + import threading + + +def _add_batch_dim(self: torch.Tensor, batch_dim: int, level: int) -> torch.Tensor: + """ + Thin wrapper around torch._C._add_batch_dim that is used to proxy in + PT2 export/compile fx graph + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + batch_dim = self.ndim + batch_dim if batch_dim < 0 else batch_dim + + if mode: + return torch.overrides.handle_torch_function( + _add_batch_dim, (self,), self, batch_dim, level + ) + + res = _add_batch_dim_impl(self, batch_dim, level) + return res + + +def _remove_batch_dim( + self: torch.Tensor, level: int, batch_size: int, out_dim: int +) -> torch.Tensor: + """ + Thin wrapper around torch._C._remove_batch_dim that is used to proxy in + PT2 export/compile fx graph + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _remove_batch_dim, (self,), self, level, batch_size, out_dim + ) + + res = _remove_batch_dim_impl(self, level, batch_size, out_dim) + return res + + +def _vmap_increment_nesting(batch_size: int, randomness: str) -> int: + """ + Thin wrapper around torch._C._vmap_increment_nesting that is used + to proxy in export/compile graph + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _vmap_increment_nesting, (batch_size,), batch_size, randomness + ) + res = _vmap_increment_nesting_impl(batch_size, randomness) + return res + + +def _vmap_decrement_nesting() -> int: + """ + Thin wrapper around torch._C._vmap_increment_nesting that is used + to proxy in export/compile graph + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _vmap_decrement_nesting, + (), + ) + return _vmap_decrement_nesting_impl() + + +# Global variables for lazy_load_decompositions +DECOMPOSITIONS_LOADED: bool = False +DECOMPOSITIONS_LOCK: threading.Lock | None = None +VMAP_DECOMPOSITIONS_LIB: torch.library.Library | None = None + + +def lazy_load_decompositions() -> None: + """ + Lazy loading of vmap decompositions with pre-dispatch support. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function(lazy_load_decompositions, ()) + + global DECOMPOSITIONS_LOADED, DECOMPOSITIONS_LOCK, VMAP_DECOMPOSITIONS_LIB + + if DECOMPOSITIONS_LOADED: + return + + # Initialize lock if needed + if DECOMPOSITIONS_LOCK is None: + import threading + + DECOMPOSITIONS_LOCK = threading.Lock() + + with DECOMPOSITIONS_LOCK: + if DECOMPOSITIONS_LOADED: + return + + import os + + if not (os.environ.get("PYTORCH_JIT", "1") == "1" and __debug__): + DECOMPOSITIONS_LOADED = True + return + + # use an alternate way to register an operator into the decomposition table + # _register_jit_decomposition doesn't work for some operators, e.g. addr, + # because the Tensor types generated cannot be unioned by torchscript + # decomp should be type OpOverload + VMAP_DECOMPOSITIONS_LIB = torch.library.Library( + "aten", "IMPL", "FuncTorchBatched" + ) + + from torch._decomp import decomposition_table + + def _register_python_decomposition_vmap(decomp: torch._ops.OpOverload) -> None: + if VMAP_DECOMPOSITIONS_LIB is None: + raise AssertionError("VMAP_DECOMPOSITIONS_LIB must not be None") + if decomp in decomposition_table: + VMAP_DECOMPOSITIONS_LIB.impl(decomp, decomposition_table[decomp]) + else: + raise RuntimeError(f"could not find decomposition for {decomp}") + + _register_python_decomposition_vmap(torch.ops.aten.mse_loss_backward.default) + _register_python_decomposition_vmap( + torch.ops.aten.smooth_l1_loss_backward.default + ) + _register_python_decomposition_vmap(torch.ops.aten.huber_loss_backward.default) + _register_python_decomposition_vmap(torch.ops.aten.nll_loss_forward.default) + _register_python_decomposition_vmap(torch.ops.aten.nll_loss2d_forward.default) + _register_python_decomposition_vmap(torch.ops.aten.nll_loss_backward.default) + _register_python_decomposition_vmap(torch.ops.aten.nll_loss2d_backward.default) + _register_python_decomposition_vmap(torch.ops.aten.addr.default) + + DECOMPOSITIONS_LOADED = True + + +def _make_dual( + tensor: torch.Tensor, tangent: torch.Tensor, *, level: int = 0 +) -> torch.Tensor: + """ + Thin wrapper around torch._VF._make_dual that is used to proxy in + PT2 export/compile fx graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _make_dual, (tensor, tangent), tensor, tangent, level=level + ) + + return _make_dual_impl(tensor, tangent, level=level) + + +def _unpack_dual( + tensor: torch.Tensor, *, level: int = 0 +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Thin wrapper around torch._VF._unpack_dual that is used to proxy in + PT2 export/compile fx graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _unpack_dual, (tensor,), tensor, level=level + ) + + return _unpack_dual_impl(tensor, level=level) + + +def _jvp_increment_nesting() -> int: + """ + Thin wrapper around torch._C._functorch._jvp_increment_nesting that is + used to proxy in export/compile graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _jvp_increment_nesting, + (), + ) + return _jvp_increment_nesting_impl() + + +def _jvp_decrement_nesting() -> int: + """ + Thin wrapper around torch._C._functorch._jvp_decrement_nesting that is + used to proxy in export/compile graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _jvp_decrement_nesting, + (), + ) + return _jvp_decrement_nesting_impl() + + +def _unwrap_for_grad(tensor: torch.Tensor, level: int) -> torch.Tensor: + """ + Thin wrapper around torch._C._functorch._unwrap_for_grad that is used + to proxy in PT2 export/compile fx graph for functorch transforms (grad, vjp, jvp). + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function( + _unwrap_for_grad, (tensor,), tensor, level + ) + + return _unwrap_for_grad_impl(tensor, level) + + +def _enter_dual_level() -> int: + """ + Thin wrapper around torch._C._enter_dual_level that is used to proxy in + PT2 export/compile fx graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function(_enter_dual_level, ()) + return _enter_dual_level_impl() + + +def _exit_dual_level(*, level: int) -> None: + """ + Thin wrapper around torch._C._exit_dual_level that is used to proxy in + PT2 export/compile fx graph for forward-mode AD. + """ + from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export + + mode = _maybe_find_pre_dispatch_tf_mode_for_export() + + if mode: + return torch.overrides.handle_torch_function(_exit_dual_level, (), level=level) + return _exit_dual_level_impl(level=level) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/pyfunctorch.py b/.venv/lib/python3.12/site-packages/torch/_functorch/pyfunctorch.py new file mode 100644 index 0000000000000000000000000000000000000000..f3b09a6adb06bd1a50ce44fafaa76afc83f21f9e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/pyfunctorch.py @@ -0,0 +1,338 @@ +from __future__ import annotations + +import contextlib +from abc import ABC, abstractmethod +from functools import cached_property +from typing import Any, TYPE_CHECKING + +import torch +import torch.utils._pytree as pytree +from torch._C._functorch import ( + CFunctionalizeInterpreterPtr, + CGradInterpreterPtr, + CInterpreter, + CJvpInterpreterPtr, + CVmapInterpreterPtr, + pop_dynamic_layer_stack, + push_dynamic_layer_stack, + RandomnessType, + TransformType, +) +from torch.autograd.forward_ad import _set_fwd_grad_enabled + + +if TYPE_CHECKING: + from collections.abc import Generator + + +""" +This file contains the functorch integration with PyDispatcher. + +PyDispatcher does not understand functorch's DynamicLayerStack dispatching +logic because it is entirely implemented in C++ in the fallbacks for two +dispatch keys, FuncTorchDynamicLayer{Front, Back}Mode (PyDispatcher is unable +to directly reuse C++ boxed fallbacks). + +Instead of trying to hammer PyDispatcher into understanding those fallbacks, +we re-implement the logic of peeking the top of the stack for an interpreter, +selecting the interpreter to dispatch on, etc, in Python. This leads to a +simpler design. + +The main difference between C++ functorch and PyDispatcher's functorch logic +is that: +- C++ functorch needs to manually tweak dispatch keys to ping-pong between + DynamicLayerFrontMode and DynamicLayerBackMode. +- PyDispatcher's functorch logic pops an Interpreter from the top of the stack + and asks it to execute the rule associated with the Interpreter. + +In C++ we do the ping-pong because e.g. vmap rules are associated with the +batched DispatchKey, but in PyDispatcher we are able to avoid this by asking +the user to register a batching rule directly to a transform that an +interpreter then invokes. +""" + + +# FuncTorchInterpreter is the Python version of Interpreter (recall that +# the DynamicLayerStack is a stack of interpreters). +# It is a wrapper around the actual C++ Interpreter object. +# +# Keep the methods in sync with aten/src/ATen/functorch/Interpreter.h +class FuncTorchInterpreter(ABC): + def __init__(self, cptr: Any) -> None: + self._cptr = cptr + + # Process an operation. eg for vmap, this is invoking a batching rule. + # Conceptually this is analogous to Interpreter::process in C++ + @abstractmethod + def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + pass + + # lower an operation from this Interpreter to the next Interpreter on the stack. + # Concretely, this involves temporarily popping the current Interpreter. + # Conceptually this is analogous to Interpreter::sendToNextInterpreter in C++ + def lower(self) -> contextlib.AbstractContextManager[Any]: + return temporarily_pop_interpreter_stack() + + def level(self) -> int: + return self._cptr.level() + + def key(self) -> TransformType: + return self._cptr.key() + + def get_state(self) -> tuple[Any, ...]: + raise NotImplementedError + + def check_state(self, state: tuple[Any, ...]) -> bool: + return state == self.get_state() + + def __getstate__(self) -> dict[str, Any]: + state = self.__dict__.copy() + state.pop("_cptr", None) + return state + + +@contextlib.contextmanager +def temporarily_pop_interpreter_stack() -> Generator[None, None, None]: + try: + saved = pop_dynamic_layer_stack() + yield + finally: + push_dynamic_layer_stack(saved) + + +@contextlib.contextmanager +def temporarily_clear_interpreter_stack() -> Generator[list[Any], None, None]: + stack: list[Any] = [] + try: + while torch._C._functorch.peek_interpreter_stack() is not None: + stack.append(pop_dynamic_layer_stack()) + yield list(stack) + finally: + while stack: + push_dynamic_layer_stack(stack.pop()) + + +@contextlib.contextmanager +def temporarily_restore_interpreter_stack( + stack: list[Any] | None, +) -> Generator[None, None, None]: + pushed: list[Any] = [] + if stack is None: + return + try: + for s in reversed(stack): + push_dynamic_layer_stack(s) + pushed.append(s) + yield + finally: + for _ in reversed(pushed): + # TODO: would be nice to assert that the layers are the same, but + # Python object identity is not preserved + pop_dynamic_layer_stack() + + +class VmapInterpreter(FuncTorchInterpreter): + def __init__(self, cdata: CInterpreter) -> None: + if cdata.key() != TransformType.Vmap: + raise AssertionError(f"expected TransformType.Vmap, got {cdata.key()}") + # NOTE: [Interpreter cdata vs cptr] + # cdata is a generic CInterpreter. We wrap it in a CVmapInterpreterPtr + # so that we can access methods specific to the vmap interpreter + self._cdata = cdata + + @cached_property + # pyrefly: ignore [bad-override] + def _cptr(self) -> CVmapInterpreterPtr: + return CVmapInterpreterPtr(self._cdata) + + def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + kernel = op.functorch_table[TransformType.Vmap] + return kernel(self, *args, **kwargs) + + def batch_size(self) -> int: + return self._cptr.batchSize() + + def randomness(self) -> str: + typ = self._cptr.randomness() + if typ == RandomnessType.Error: + return "error" + elif typ == RandomnessType.Same: + return "same" + elif typ == RandomnessType.Different: + return "different" + raise RuntimeError(f"Unknown RandomnessType: {typ}") + + def get_state(self) -> tuple[Any, ...]: + return (self.key().name, self.level(), self.randomness()) + + +@contextlib.contextmanager +def nested( + *contexts: contextlib.AbstractContextManager[Any], +) -> Generator[tuple[contextlib.AbstractContextManager[Any], ...], None, None]: + with contextlib.ExitStack() as stack: + for ctx in contexts: + stack.enter_context(ctx) + yield contexts + + +class GradInterpreter(FuncTorchInterpreter): + def __init__(self, cdata: CInterpreter) -> None: + if cdata.key() != TransformType.Grad: + raise AssertionError(f"expected TransformType.Grad, got {cdata.key()}") + # See NOTE: [Interpreter cdata vs cptr] + self._cdata = cdata + + @cached_property + # pyrefly: ignore [bad-override] + def _cptr(self) -> CGradInterpreterPtr: + return CGradInterpreterPtr(self._cdata) + + def lift( + self, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> tuple[tuple[Any, ...], dict[str, Any]]: + args, kwargs = pytree.tree_map_only( + torch.Tensor, self._cptr.lift, [args, kwargs] + ) + return args, kwargs + + def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + kernel = op.functorch_table[TransformType.Grad] + args, kwargs = self.lift(args, kwargs) + return kernel(self, *args, **kwargs) + + # GradInterpreter has custom lower because of the no_grad interaction + # See NOTE [grad and vjp interaction with no_grad] + # This logic is mirrored from C++ GradInterpreterPtr::sendToNextInterpreter + def lower(self) -> contextlib.AbstractContextManager[Any]: + prev_grad_mode = self.prev_grad_mode() + if not prev_grad_mode: + return nested(torch.no_grad(), super().lower()) + return super().lower() + + def prev_grad_mode(self) -> bool: + return self._cptr.prevGradMode() + + def get_state(self) -> tuple[Any, ...]: + return (self.key().name, self.level(), self.prev_grad_mode()) + + +class JvpInterpreter(FuncTorchInterpreter): + def __init__(self, cdata: CInterpreter) -> None: + if cdata.key() != TransformType.Jvp: + raise AssertionError(f"expected TransformType.Jvp, got {cdata.key()}") + # See NOTE: [Interpreter cdata vs cptr] + self._cdata = cdata + + @cached_property + # pyrefly: ignore [bad-override] + def _cptr(self) -> CJvpInterpreterPtr: + return CJvpInterpreterPtr(self._cdata) + + def lift( + self, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> tuple[tuple[Any, ...], dict[str, Any]]: + args, kwargs = pytree.tree_map_only( + torch.Tensor, self._cptr.lift, [args, kwargs] + ) + return args, kwargs + + def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + kernel = op.functorch_table[TransformType.Jvp] + args, kwargs = self.lift(args, kwargs) + return kernel(self, *args, **kwargs) + + # Jvp has custom lower because of the no_fwd_grad interaction + # See NOTE [grad and vjp interaction with no_grad] for related info. + # This logic is mirrored from C++ JvpInterpreterPtr::sendToNextInterpreter + def lower(self) -> contextlib.AbstractContextManager[Any]: + prev_fwd_grad_mode = self.prev_fwd_grad_mode() + if not prev_fwd_grad_mode: + return nested(_set_fwd_grad_enabled(False), super().lower()) + return super().lower() + + def prev_fwd_grad_mode(self) -> bool: + return self._cptr.prevFwdGradMode() + + def get_state(self) -> tuple[Any, ...]: + return (self.key().name, self.level(), self.prev_fwd_grad_mode()) + + +class FunctionalizeInterpreter(FuncTorchInterpreter): + def __init__(self, cdata: CInterpreter) -> None: + if cdata.key() != TransformType.Functionalize: + raise AssertionError( + f"expected TransformType.Functionalize, got {cdata.key()}" + ) + self._cdata = cdata + + @cached_property + # pyrefly: ignore [bad-override] + def _cptr(self) -> CFunctionalizeInterpreterPtr: + return CFunctionalizeInterpreterPtr(self._cdata) + + def process(self, op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + kernel = op.functorch_table[TransformType.Functionalize] + return kernel(self, *args, **kwargs) + + def functionalize_add_back_views(self) -> bool: + return self._cptr.functionalizeAddBackViews() + + def get_state(self) -> tuple[Any, ...]: + return (self.key().name, self.level()) + + +def coerce_cinterpreter(cinterpreter: CInterpreter) -> FuncTorchInterpreter: + key = cinterpreter.key() + if key == TransformType.Grad: + return GradInterpreter(cinterpreter) + if key == TransformType.Vmap: + return VmapInterpreter(cinterpreter) + if key == TransformType.Jvp: + return JvpInterpreter(cinterpreter) + if key == TransformType.Functionalize: + return FunctionalizeInterpreter(cinterpreter) + raise RuntimeError(f"NYI: PyDispatcher has not implemented support for {key}") + + +def retrieve_current_functorch_interpreter() -> FuncTorchInterpreter: + interpreter = torch._C._functorch.peek_interpreter_stack() + if interpreter is None: + raise AssertionError("interpreter must not be None") + return coerce_cinterpreter(interpreter) + + +def retrieve_all_functorch_interpreters() -> list[FuncTorchInterpreter]: + cis = torch._C._functorch.get_interpreter_stack() + if cis is None: + return [] + return [coerce_cinterpreter(ci) for ci in cis] + + +def compare_functorch_state(states: list[tuple[Any, ...]]) -> bool: + # There are four possible cases covered here: + # 1. Current stack empty AND stack when generated not empty -> Invalidate + # 2. Current stack not empty AND stack when generated empty -> Invalidate + # 3. Current stack and generated stack empty -> Valid FX graph + # 4. Current stack and generated stack not empty -> Valid if both states match + peek = torch._C._functorch.peek_interpreter_stack() + if (peek is None and len(states) != 0) or (peek is not None and len(states) == 0): + return False + + cis = retrieve_all_functorch_interpreters() + return len(cis) == len(states) and all( + ci.check_state(state) for ci, state in zip(cis, states) + ) + + +def dispatch_functorch(op: Any, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + interpreter = retrieve_current_functorch_interpreter() + # In traditional PyTorch operators, DispatchKey::FuncTorchTensorWrapper's + # unwrap_dead_tensors fallback handles unwrapping dead tensor wrappers. + # PyDispatcher sidesteps the PyTorch dispatcher when dealing with functorch + # transforms, so we manually unwrap the dead tensors here. + # This logic won't need to exist when we have mode-only functorch. + args, kwargs = pytree.tree_map_only( + torch.Tensor, torch._C._functorch.unwrap_if_dead, (args, kwargs) + ) + return interpreter.process(op, args, kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/python_key.py b/.venv/lib/python3.12/site-packages/torch/_functorch/python_key.py new file mode 100644 index 0000000000000000000000000000000000000000..557334f68928a057a6a9e036c904c8c0bd3231c1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/python_key.py @@ -0,0 +1,15 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. +__all__ = ["make_fx", "dispatch_trace", "PythonKeyTracer", "pythonkey_decompose"] +from torch.fx.experimental.proxy_tensor import ( + decompose, + dispatch_trace, + make_fx, + PythonKeyTracer, +) + + +pythonkey_decompose = decompose diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/pytree_hacks.py b/.venv/lib/python3.12/site-packages/torch/_functorch/pytree_hacks.py new file mode 100644 index 0000000000000000000000000000000000000000..96dea7ad100705ae53139aa5ae729fd2206182af --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/pytree_hacks.py @@ -0,0 +1,23 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +import warnings + +# TODO: remove this file when the migration of the pytree utility is done +from torch.utils._pytree import tree_map_, treespec_pprint + + +__all__ = ["tree_map_", "treespec_pprint"] + + +with warnings.catch_warnings(): + warnings.simplefilter("always") + warnings.warn( + "`torch._functorch.pytree_hacks` is deprecated and will be removed in a future release. " + "Please `use torch.utils._pytree` instead.", + DeprecationWarning, + stacklevel=2, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/top_operators_github_usage.py b/.venv/lib/python3.12/site-packages/torch/_functorch/top_operators_github_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..2e11b6b9cdcbe4aab352a5f206f3b957e8026df3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/top_operators_github_usage.py @@ -0,0 +1,630 @@ +from __future__ import annotations + + +""" +From https://docs.google.com/spreadsheets/d/12R3nCOLskxPYjjiNkdqy4OdQ65eQp_htebXGODsjSeA/edit#gid=0 +Try to keep this list in sync with that. +""" + +import operator + + +top_torch: list[tuple[str, int]] = [ + ("t", 6837449), + ("tensor", 585786), + ("mode", 462182), + ("cat", 394818), + ("max", 368038), + ("zeros", 329495), + ("load", 327756), + ("no_grad", 294694), + ("save", 265130), + ("from_numpy", 243063), + ("manual_seed", 165044), + ("ones", 153696), + ("randn", 150796), + ("stack", 133358), + ("sum", 130772), + ("arange", 98087), + ("rand", 94715), + ("mean", 88546), + ("exp", 73883), + ("zeros_like", 72831), + ("min", 72248), + ("sigmoid", 66798), + ("log", 62135), + ("matmul", 47811), + ("clamp", 45304), + ("sqrt", 44911), + ("abs", 43535), + ("tanh", 42793), + ("empty", 40311), + ("argmax", 38435), + ("bmm", 33984), + ("pow", 33571), + ("norm", 31125), + ("mm", 30995), + ("is_tensor", 29546), + ("ones_like", 29512), + ("nonzero", 28681), + ("full", 28373), + ("unsqueeze", 27911), + ("where", 26585), + ("randperm", 26450), + ("eye", 24342), + ("mul", 23236), + ("topk", 22537), + ("as_tensor", 21967), + ("sort", 21412), + ("squeeze", 20863), + ("randint", 20771), + ("linspace", 20041), + ("add", 19201), + ("transpose", 18663), + ("split", 18325), + ("gather", 17904), + ("set_grad_enabled", 16013), + ("sin", 15669), + ("cos", 15562), + ("div", 15513), + ("index_select", 14866), + ("multinomial", 14331), + ("flatten", 14267), + ("isnan", 14170), + ("randn_like", 13096), + ("eq", 12680), + ("einsum", 12480), + ("round", 12367), + ("floor", 11628), + ("allclose", 11000), + ("reshape", 10605), + ("diag", 10167), + ("chunk", 9581), + ("std", 9379), + ("set_default_tensor_type", 9281), + ("triu", 8559), + ("meshgrid", 8292), + ("set_num_threads", 8126), + ("unique", 7964), + ("full_like", 7780), + ("tril", 7538), + ("dot", 7275), + ("sign", 6943), + ("equal", 6916), + ("normal", 6750), + ("cumsum", 6556), + ("dist", 6058), + ("isfinite", 6030), + ("gt", 5935), + ("set_printoptions", 5888), + ("range", 5491), + ("empty_like", 5351), + ("flip", 5342), + ("masked_select", 5341), + ("bernoulli", 5262), + ("atan", 5253), + ("var", 5247), + ("prod", 5200), + ("erf", 5088), + ("inverse", 5072), + ("addmm", 4854), + ("logsumexp", 4582), + ("fft", 4436), + ("lt", 4421), + ("log2", 4316), + ("enable_grad", 4238), + ("rand_like", 4187), + ("argsort", 3972), + ("seed", 3932), + ("mv", 3547), + ("ger", 3309), + ("ge", 3248), + ("atan2", 3210), + ("ceil", 3202), + ("ne", 3075), + ("bincount", 3063), + ("acos", 3055), + ("rsqrt", 3031), + ("svd", 3029), + ("numel", 3003), + ("log1p", 2840), + ("unbind", 2808), + ("le", 2714), + ("isinf", 2707), + ("cross", 2646), + ("set_default_dtype", 2536), + ("argmin", 2535), + ("sparse_coo_tensor", 2489), + ("log10", 2304), + ("kthvalue", 2192), + ("set_rng_state", 2158), + ("get_rng_state", 1996), + ("get_default_dtype", 1879), + ("det", 1868), + ("qr", 1864), + ("histc", 1852), + ("symeig", 1832), + ("trace", 1801), + ("median", 1795), + ("addcmul", 1751), + ("remainder", 1717), + ("baddbmm", 1693), + ("lgamma", 1665), + ("repeat_interleave", 1598), + ("fmod", 1576), + ("reciprocal", 1575), + ("tan", 1560), + ("initial_seed", 1532), + ("take", 1529), + ("stft", 1487), + ("get_num_threads", 1477), + ("real", 1459), + ("quantize_per_tensor", 1392), + ("diag_embed", 1364), + ("lerp", 1363), + ("asin", 1345), + ("eig", 1333), + ("trunc", 1290), + ("diagonal", 1287), + ("cosh", 1279), + ("rfft", 1269), + ("cumprod", 1260), + ("addr", 1211), + ("roll", 1198), + ("narrow", 1188), + ("digamma", 1172), + ("square", 1163), + ("sinh", 1131), + ("logspace", 1084), + ("broadcast_tensors", 1070), + ("irfft", 1013), + ("frac", 997), + ("hann_window", 994), + ("solve", 989), + ("logdet", 977), + ("expm1", 968), + ("cdist", 946), + ("addmv", 903), + ("randint_like", 888), + ("tensordot", 888), + ("ifft", 877), + ("true_divide", 854), + ("erfinv", 830), + ("addcdiv", 819), + ("addbmm", 813), + ("renorm", 781), + ("pinverse", 753), + ("isclose", 740), + ("erfc", 729), + ("is_storage", 725), + ("triangular_solve", 723), + ("rot90", 709), + ("logical_not", 686), + ("geqrf", 681), + ("slogdet", 677), + ("lu", 665), + ("hamming_window", 659), + ("orgqr", 651), + ("ormqr", 622), + ("is_floating_point", 602), + ("diagflat", 562), + ("cholesky_solve", 559), + ("tril_indices", 552), + ("chain_matmul", 551), + ("triu_indices", 548), + ("angle", 522), + ("poisson", 505), + ("matrix_power", 485), + ("unique_consecutive", 471), + ("quantize_per_channel", 465), + ("std_mean", 458), + ("bartlett_window", 447), + ("var_mean", 428), + ("lstsq", 421), + ("logical_and", 419), + ("mvlgamma", 411), + ("blackman_window", 400), + ("bitwise_not", 395), + ("cholesky_inverse", 388), + ("as_strided", 384), + ("floor_divide", 353), + ("cartesian_prod", 321), + ("lu_solve", 317), + ("set_flush_denormal", 310), + ("empty_strided", 283), + ("logical_xor", 282), + ("polygamma", 282), + ("logical_or", 280), + ("set_num_interop_threads", 278), + ("combinations", 274), + ("trapz", 270), + ("matrix_rank", 260), + ("lu_unpack", 255), + ("result_type", 244), + ("conj", 231), + ("cummax", 230), + ("lobpcg", 229), + ("bitwise_xor", 217), + ("promote_types", 213), + ("get_num_interop_threads", 211), + ("cummin", 205), + ("bitwise_and", 198), + ("dequantize", 192), + ("bitwise_or", 191), + ("imag", 191), + ("can_cast", 184), + ("istft", 180), + ("compiled_with_cxx11_abi", 159), + ("is_complex", 151), + ("block_diag", 136), + ("pca_lowrank", 124), + ("absolute", 122), + ("svd_lowrank", 108), + ("neg", 2), +] + +top_nn_functional: list[tuple[str, int]] = [ + ("nn.functional.softmax", 10522), + ("nn.functional.relu", 8572), + ("nn.functional.interpolate", 7277), + ("nn.functional.pad", 5207), + ("nn.functional.log_softmax", 4699), + ("nn.functional.normalize", 2338), + ("nn.functional.cross_entropy", 2083), + ("nn.functional.grid_sample", 1970), + ("nn.functional.one_hot", 1967), + ("nn.functional.mse_loss", 1920), + ("nn.functional.conv2d", 1593), + ("nn.functional.dropout", 1516), + ("nn.functional.softplus", 1385), + ("nn.functional.sigmoid", 1128), + ("nn.functional.linear", 1036), + ("nn.functional.gelu", 930), + ("nn.functional.avg_pool2d", 899), + ("nn.functional.max_pool2d", 876), + ("nn.functional.nll_loss", 863), + ("nn.functional.embedding", 737), + ("nn.functional.tanh", 664), + ("nn.functional.leaky_relu", 640), + ("nn.functional.adaptive_avg_pool2d", 633), + ("nn.functional.cosine_similarity", 627), + ("nn.functional.unfold", 609), + ("nn.functional.conv1d", 596), + ("nn.functional.binary_cross_entropy_with_logits", 591), + ("nn.functional.l1_loss", 571), + ("nn.functional.binary_cross_entropy", 492), + ("nn.functional.elu", 416), + ("nn.functional.batch_norm", 413), + ("nn.functional.upsample", 413), + ("nn.functional.fold", 305), + ("nn.functional.affine_grid", 298), + ("nn.functional.max_pool1d", 297), + ("nn.functional.torch", 294), + ("nn.functional.threshold", 263), + ("nn.functional.smooth_l1_loss", 262), + ("nn.functional.pairwise_distance", 253), + ("nn.functional.logsigmoid", 243), + ("nn.functional.adaptive_max_pool2d", 235), + ("nn.functional.relu6", 213), + ("nn.functional.pixel_shuffle", 209), + ("nn.functional.avg_pool3d", 203), + ("nn.functional.bilinear", 203), + ("nn.functional.conv_transpose2d", 201), + ("nn.functional.gumbel_softmax", 197), + ("nn.functional.max_unpool2d", 196), + ("nn.functional.kl_div", 191), + ("nn.functional.hardtanh", 189), + ("nn.functional.ctc_loss", 185), + ("nn.functional.layer_norm", 178), + ("nn.functional.conv3d", 172), + ("nn.functional.max_unpool3d", 167), + ("nn.functional.hardshrink", 165), + ("nn.functional.hardswish", 156), + ("nn.functional.selu", 156), + ("nn.functional.glu", 155), + ("nn.functional.assert_int_or_pair", 150), + ("nn.functional.hardsigmoid", 146), + ("nn.functional.upsample_bilinear", 146), + ("nn.functional.max_pool3d", 140), + ("nn.functional.adaptive_avg_pool3d", 139), + ("nn.functional.instance_norm", 124), + ("nn.functional.embedding_bag", 122), + ("nn.functional.upsample_nearest", 110), + ("nn.functional.avg_pool1d", 105), + ("nn.functional.prelu", 102), + ("nn.functional.celu", 92), + ("nn.functional.dropout2d", 86), + ("nn.functional.hinge_embedding_loss", 82), + ("nn.functional.softsign", 81), + ("nn.functional.max_unpool1d", 74), + ("nn.functional.silu", 74), + ("nn.functional.softshrink", 70), + ("nn.functional.leaky_relu_", 68), + ("nn.functional.softmin", 67), + ("nn.functional.channel_shuffle", 66), + ("nn.functional.multilabel_margin_loss", 66), + ("nn.functional.dropout3d", 65), + ("nn.functional.multi_margin_loss", 65), + ("nn.functional.lp_pool2d", 64), + ("nn.functional.conv_transpose1d", 62), + ("nn.functional.triplet_margin_loss", 62), + ("nn.functional.tanhshrink", 61), + ("nn.functional.adaptive_max_pool1d", 59), + ("nn.functional.cosine_embedding_loss", 58), + ("nn.functional.multi_head_attention_forward", 58), + ("nn.functional.max_pool1d_with_indices", 53), + ("nn.functional.poisson_nll_loss", 53), + ("nn.functional.margin_ranking_loss", 52), + ("nn.functional.soft_margin_loss", 52), + ("nn.functional.adaptive_max_pool3d", 51), + ("nn.functional.group_norm", 51), + ("nn.functional.local_response_norm", 51), + ("nn.functional.multilabel_soft_margin_loss", 51), + ("nn.functional.relu_", 50), + ("nn.functional.alpha_dropout", 49), + ("nn.functional.feature_alpha_dropout", 49), + ("nn.functional.lp_pool1d", 49), + ("nn.functional.adaptive_max_pool1d_with_indices", 48), + ("nn.functional.adaptive_max_pool2d_with_indices", 48), + ("nn.functional.adaptive_max_pool3d_with_indices", 48), + ("nn.functional.fractional_max_pool2d", 48), + ("nn.functional.fractional_max_pool2d_with_indices", 48), + ("nn.functional.fractional_max_pool3d", 48), + ("nn.functional.fractional_max_pool3d_with_indices", 48), + ("nn.functional.max_pool2d_with_indices", 48), + ("nn.functional.max_pool3d_with_indices", 48), + ("nn.functional.handle_torch_function", 47), + ("nn.functional.has_torch_function", 47), + ("nn.functional.adaptive_avg_pool1d", 43), + ("nn.functional.pdist", 43), + ("nn.functional.rrelu_", 37), + ("nn.functional.elu_", 34), + ("nn.functional.boolean_dispatch", 33), + ("nn.functional.hardtanh_", 26), + ("nn.functional.triplet_margin_with_distance_loss", 23), + ("nn.functional.selu_", 20), + ("nn.functional.pixel_unshuffle", 19), + ("nn.functional.conv_transpose3d", 18), + ("nn.functional.gaussian_nll_loss", 15), + ("nn.functional.has_torch_function_unary", 15), + ("nn.functional.has_torch_function_variadic", 15), + ("nn.functional.celu_", 13), + ("nn.functional.huber_loss", 7), + ("nn.functional.mish", 4), + ("nn.functional.threshold_", 3), + ("nn.functional.grad", 2), + ("nn.functional.conv_tbc", 1), + ("nn.functional.math", 1), +] + +top_nn_module: list[tuple[str, int, str | None]] = [ + ("nn.Module", 927129, None), + ("nn.Linear", 530688, "nn.functional.linear"), + ("nn.Sequential", 384968, None), + ("nn.Conv2d", 383320, "nn.functional.conv2d"), + ("nn.ReLU", 318877, "nn.functional.relu"), + ("nn.BatchNorm2d", 233265, "nn.functional.batch_norm"), + ("nn.Dropout", 179268, "nn.functional.dropout"), + ("nn.ModuleList", 171225, None), + ("nn.Parameter", 153291, None), + ("nn.CrossEntropyLoss", 152696, "nn.functional.cross_entropy"), + ("nn.MaxPool2d", 138619, "nn.functional.max_pool2d"), + ("nn.Embedding", 111844, "nn.functional.embedding"), + ("nn.DataParallel", 104238, None), + ("nn.MSELoss", 82954, "nn.functional.mse_loss"), + ("nn.Sigmoid", 75810, "nn.functional.sigmoid"), + ("nn.LeakyReLU", 65632, "nn.functional.leaky_relu"), + ("nn.BatchNorm1d", 65374, "nn.functional.batch_norm"), + ("nn.Softmax", 65114, "nn.functional.softmax"), + ("nn.Tanh", 59445, "nn.functional.tanh"), + ("nn.AdaptiveAvgPool2d", 59071, "nn.functional.adaptive_avg_pool2d"), + ("nn.AvgPool2d", 58377, "nn.functional.avg_pool2d"), + ("nn.ConvTranspose2d", 57524, "nn.functional.conv_transpose2d"), + ("nn.LSTM", 57411, None), + ("nn.Conv1d", 41108, "nn.functional.conv1d"), + ("nn.LayerNorm", 36089, "nn.functional.layer_norm"), + ("nn.BCELoss", 34005, "nn.functional.binary_cross_entropy"), + ("nn.Upsample", 32527, "nn.functional.interpolate"), + ("nn.BCEWithLogitsLoss", 29944, "nn.functional.binary_cross_entropy_with_logits"), + ("nn.GRU", 25421, None), + ("nn.Dropout2d", 23512, "nn.functional.dropout2d"), + ("nn.LogSoftmax", 22897, "nn.functional.log_softmax"), + ("nn.L1Loss", 22778, "nn.functional.l1_loss"), + ("nn.GroupNorm", 22183, "nn.functional.group_norm"), + ("nn.NLLLoss", 21751, "nn.functional.nll_loss"), + ("nn.Conv3d", 20874, "nn.functional.conv3d"), + ("nn.Identity", 17911, None), + ("nn.InstanceNorm2d", 16426, "nn.functional.instance_norm"), + ("nn.BatchNorm3d", 16378, "nn.functional.batch_norm"), + ("nn.PReLU", 13472, "nn.functional.prelu"), + ("nn.ReLU6", 12622, "nn.functional.relu6"), + ("nn.ELU", 12508, "nn.functional.elu"), + ("nn.LSTMCell", 10885, None), + ("nn.Flatten", 10384, "torch.flatten"), + ("nn.ModuleDict", 10255, None), + ("nn.ReflectionPad2d", 9954, "nn.functional.pad"), + ("nn.MaxPool3d", 9526, "nn.functional.max_pool3d"), + ("nn.MaxPool1d", 9154, "nn.functional.max_pool1d"), + ("nn.RNN", 9154, None), + ("nn.ZeroPad2d", 8847, "nn.functional.pad"), + ("nn.ParameterList", 7702, None), + ("nn.SyncBatchNorm", 6814, None), + ("nn.PixelShuffle", 6571, "nn.functional.pixel_shuffle"), + ("nn.SmoothL1Loss", 6517, "nn.functional.smooth_l1_loss"), + ("nn.Hardswish", 6458, "nn.functional.hardswish"), + ("nn.AdaptiveMaxPool2d", 6071, "nn.functional.adaptive_max_pool2d"), + ("nn.SELU", 6043, "nn.functional.selu"), + ("nn.ConvTranspose3d", 6039, "nn.functional.conv_transpose3d"), + ("nn.GRUCell", 5840, None), + ("nn.ReplicationPad2d", 5600, "nn.functional.pad"), + ("nn.KLDivLoss", 5541, "nn.functional.kl_div"), + ("nn.ConvTranspose1d", 5183, "nn.functional.conv_transpose1d"), + ("nn.Softplus", 5120, "nn.functional.softplus"), + ("nn.SiLU", 4895, "nn.functional.silu"), + ("nn.AvgPool3d", 4523, "nn.functional.avg_pool3d"), + ("nn.CosineSimilarity", 4058, "nn.functional.cosine_similarity"), + ("nn.GELU", 3932, "nn.functional.gelu"), + ("nn.UpsamplingBilinear2d", 3673, "nn.functional.interpolate"), + ("nn.InstanceNorm1d", 3658, "nn.functional.instance_norm"), + ("nn.Transformer", 3604, None), + ("nn.MultiheadAttention", 3435, "nn.functional.multi_head_attention_forward"), + ("nn.AvgPool1d", 3195, "nn.functional.avg_pool1d"), + ("nn.Dropout3d", 2964, "nn.functional.dropout3d"), + ("nn.AdaptiveAvgPool3d", 2915, "nn.functional.adaptive_avg_pool3d"), + ("nn.InstanceNorm3d", 2893, "nn.functional.instance_norm"), + ("nn.Hardtanh", 2613, "nn.functional.hardtanh"), + ("nn.MarginRankingLoss", 2568, "nn.functional.margin_ranking_loss"), + ("nn.GLU", 2526, "nn.functional.glu"), + ("nn.AdaptiveAvgPool1d", 2481, "nn.functional.adaptive_avg_pool1d"), + ("nn.EmbeddingBag", 2344, "nn.functional.embedding_bag"), + ("nn.TransformerEncoderLayer", 2292, None), + ("nn.TransformerEncoder", 2091, None), + ("nn.MaxUnpool2d", 2031, "nn.functional.max_unpool2d"), + ("nn.UpsamplingNearest2d", 2004, "nn.functional.interpolate"), + ("nn.ConstantPad1d", 1904, "nn.functional.pad"), + ("nn.ConstantPad2d", 1791, "nn.functional.pad"), + ("nn.CTCLoss", 1789, "nn.functional.ctc_loss"), + ("nn.AdaptiveMaxPool1d", 1713, "nn.functional.adaptive_max_pool1d"), + ("nn.AdaptiveLogSoftmaxWithLoss", 1665, None), + ("nn.Bilinear", 1664, "nn.functional.bilinear"), + ("nn.RNNCell", 1653, None), + ("nn.MultiLabelSoftMarginLoss", 1624, "nn.functional.multilabel_soft_margin_loss"), + ("nn.Unfold", 1452, "nn.functional.unfold"), + ("nn.RReLU", 1431, "nn.functional.rrelu"), + ("nn.CosineEmbeddingLoss", 1357, "nn.functional.cosine_embedding_loss"), + ("nn.LocalResponseNorm", 1331, "nn.functional.local_response_norm"), + ("nn.Softmax2d", 1300, "nn.functional.softmax"), + ("nn.PairwiseDistance", 1241, "nn.functional.pairwise_distance"), + ("nn.LogSigmoid", 1235, "nn.functional.logsigmoid"), + ("nn.TripletMarginLoss", 1230, "nn.functional.triplet_margin_loss"), + ("nn.RNNBase", 1133, None), + ("nn.Threshold", 1043, "nn.functional.threshold"), + ("nn.AdaptiveMaxPool3d", 1025, "nn.functional.adaptive_max_pool3d"), + ("nn.CELU", 1018, "nn.functional.celu"), + ("nn.NLLLoss2d", 966, "nn.functional.nll_loss"), + ("nn.Softsign", 877, "nn.functional.softsign"), + ("nn.ReplicationPad1d", 862, "nn.functional.pad"), + ("nn.SoftMarginLoss", 856, "nn.functional.soft_margin_loss"), + ("nn.ParameterDict", 742, None), + ("nn.ReflectionPad1d", 731, "nn.functional.pad"), + ("nn.Softshrink", 713, "nn.functional.softshrink"), + ("nn.AlphaDropout", 710, "nn.functional.alpha_dropout"), + ("nn.Tanhshrink", 681, "nn.functional.tanhshrink"), + ("nn.PoissonNLLLoss", 676, "nn.functional.poisson_nll_loss"), + ("nn.MaxUnpool3d", 660, "nn.functional.max_unpool3d"), + ("nn.Fold", 630, "nn.functional.fold"), + ("nn.MultiMarginLoss", 622, "nn.functional.multi_margin_loss"), + ("nn.TransformerDecoderLayer", 614, None), + ("nn.TransformerDecoder", 607, None), + ("nn.Hardshrink", 592, "nn.functional.hardshrink"), + ("nn.ConstantPad3d", 582, "nn.functional.pad"), + ("nn.MultiLabelMarginLoss", 580, "nn.functional.multilabel_margin_loss"), + ("nn.LPPool2d", 550, "nn.functional.lp_pool2d"), + ("nn.Softmin", 537, "nn.functional.softmin"), + ("nn.MaxUnpool1d", 518, "nn.functional.max_unpool1d"), + ("nn.FractionalMaxPool2d", 484, "nn.functional.fractional_max_pool2d"), + ("nn.Hardsigmoid", 477, "nn.functional.hardsigmoid"), + ("nn.ReplicationPad3d", 470, "nn.functional.pad"), + ("nn.HingeEmbeddingLoss", 442, "nn.functional.hinge_embedding_loss"), + ("nn.LPPool1d", 386, "nn.functional.lp_pool1d"), + ("nn.FractionalMaxPool3d", 252, "nn.functional.fractional_max_pool3d"), + ("nn.Container", 217, None), + ("nn.Unflatten", 206, "nn.functional.unflatten"), + ("nn.FeatureAlphaDropout", 136, "nn.functional.feature_alpha_dropout"), + ( + "nn.TripletMarginWithDistanceLoss", + 107, + "nn.functional.triplet_margin_with_distance_loss", + ), + ("nn.ChannelShuffle", 90, "nn.functional.channel_shuffle"), + ("nn.RNNCellBase", 88, None), + ("nn.LazyLinear", 81, "nn.functional.linear"), + ("nn.UninitializedParameter", 60, None), + ("nn.CrossMapLRN2d", 59, None), + ("nn.GaussianNLLLoss", 55, "nn.functional.gaussian_nll_loss"), + ("nn.PixelUnshuffle", 45, "nn.functional.pixel_unshuffle"), + ("nn.Mish", 31, "nn.functional.mish"), + ("nn.ReflectionPad3d", 22, "nn.functional.pad"), + ("nn.HuberLoss", 18, "nn.functional.huber_loss"), + ("nn.LazyConv2d", 15, None), + ("nn.LazyConv1d", 9, None), + ("nn.LazyConv3d", 8, None), + ("nn.LazyConvTranspose1d", 8, None), + ("nn.LazyConvTranspose2d", 8, None), + ("nn.LazyConvTranspose3d", 8, None), + ("nn.LazyBatchNorm1d", 3, None), + ("nn.LazyBatchNorm2d", 3, None), + ("nn.LazyBatchNorm3d", 3, None), + ("nn.UninitializedBuffer", 3, None), +] + +# No rankings because these are a little hard to get rankings for +method_only_ops: list[str] = [ + "bfloat16", + "bool", + "byte", + "char", + "contiguous", + "cpu", + "cuda", + "detach", + "double", + "expand", + "expand_as", + "float", + "get_device", + "half", + "hardshrink", + "index_add", + "index_copy", + "index_fill", + "index_put", + "int", + "is_contiguous", + "is_pinned", + "is_set_to", + "is_shared", + "is_signed", + "item", + "long", + "masked_scatter", + "masked_fill", + "narrow_copy", + "numpy", + "pin_memory", + "repeat", + "reshape_as", + "select", + "short", + "storage_offset", + "sum_to_size", + "to", + "to_mkldnn", + "tolist", + "type", + "type_as", + "unfold", + "view", + "view_as", +] + + +def get_nn_functional_top_list() -> list[tuple[str, int]]: + top_nn_functional_: dict[str, int] = dict(top_nn_functional) + for _, count, functional_name in top_nn_module: + if functional_name is None: + continue + if functional_name == "torch.flatten": + continue + if functional_name not in top_nn_functional_: + top_nn_functional_[functional_name] = count + else: + top_nn_functional_[functional_name] += count + + top_nn_functional_list = list(top_nn_functional_.items()) + top_nn_functional_list.sort(key=operator.itemgetter(1), reverse=True) + return top_nn_functional_list + + +usage_count: dict[str, int] = dict(get_nn_functional_top_list()) +usage_count.update(top_torch) diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/utils.py b/.venv/lib/python3.12/site-packages/torch/_functorch/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..048271343465f7b450f12bb9c374c5c67d3b54eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/utils.py @@ -0,0 +1,30 @@ +import contextlib +from collections.abc import Generator + +from torch._C._functorch import ( + get_single_level_autograd_function_allowed, + set_single_level_autograd_function_allowed, + unwrap_dead_wrappers, +) +from torch.utils._exposed_in import exposed_in + + +__all__ = [ + "exposed_in", + "argnums_t", + "enable_single_level_autograd_function", + "unwrap_dead_wrappers", +] + + +@contextlib.contextmanager +def enable_single_level_autograd_function() -> Generator[None, None, None]: + try: + prev_state = get_single_level_autograd_function_allowed() + set_single_level_autograd_function_allowed(True) + yield + finally: + set_single_level_autograd_function_allowed(prev_state) + + +argnums_t = int | tuple[int, ...] diff --git a/.venv/lib/python3.12/site-packages/torch/_functorch/vmap.py b/.venv/lib/python3.12/site-packages/torch/_functorch/vmap.py new file mode 100644 index 0000000000000000000000000000000000000000..bc758f172e534b6159b89d79c2f225e3c7a80a89 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_functorch/vmap.py @@ -0,0 +1,567 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +import contextlib +import functools +import itertools +from collections.abc import Callable # noqa: TC003 +from functools import partial +from typing import Any, cast, NoReturn, TYPE_CHECKING +from typing_extensions import ParamSpec, TypeVar + +import torch +from torch import Tensor +from torch._C._functorch import is_batchedtensor +from torch._functorch.predispatch import ( + _add_batch_dim, + _remove_batch_dim, + _vmap_decrement_nesting, + _vmap_increment_nesting, + lazy_load_decompositions, +) +from torch.utils._pytree import ( + _broadcast_to_and_flatten, + tree_flatten, + tree_map_, + tree_unflatten, + TreeSpec, +) + + +if TYPE_CHECKING: + from collections.abc import Generator, Iterable + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +in_dims_t = int | tuple[Any, ...] +out_dims_t = int | tuple[int, ...] | None + + +def doesnt_support_saved_tensors_hooks(f: Callable[_P, _R]) -> Callable[_P, _R]: + message = ( + "torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. " + "Please open an issue with your use case." + ) + + @functools.wraps(f) + def fn(*args: _P.args, **kwargs: _P.kwargs) -> _R: + with torch.autograd.graph.disable_saved_tensors_hooks(message): + return f(*args, **kwargs) + + return fn + + +# 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[Any] +) -> 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 len(batch_sizes) == 0: + raise ValueError("vmap: Expected at least one Tensor to vmap over") + 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: tuple[_R, ...] | _R, + num_elements: int, + error_message_lambda: Callable[[], str], +) -> tuple[_R, ...]: + if not isinstance(value, tuple): + return (value,) * num_elements + if len(value) != num_elements: + raise ValueError(error_message_lambda()) + return value + + +def _process_batched_inputs( + in_dims: in_dims_t, args: tuple[Any, ...], func: Callable[..., Any] +) -> tuple[int, list[int | None], list[Any], TreeSpec]: + 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 i, (arg, in_dim) in enumerate(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 < -arg.dim() 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"-{arg.dim()} <= in_dim < {arg.dim()}." + ) + if in_dim is not None and in_dim < 0: + flat_in_dims[i] = in_dim % arg.dim() + + return ( + _validate_and_get_batch_size(flat_in_dims, flat_args), + flat_in_dims, + flat_args, + args_spec, + ) + + +# Creates BatchedTensors for every Tensor in arg that should be batched. +# Returns the (potentially) batched arguments and the batch_size. + + +# TODO: See if we can explain how flat works to the type checker +def _create_batched_inputs( + flat_in_dims: list[int | None], + flat_args: list[Any], + vmap_level: int, + args_spec: TreeSpec, +) -> tuple[Any, ...]: + # See NOTE [Ignored _remove_batch_dim, _add_batch_dim] + batched_inputs = [ + arg if in_dim is None else _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) + + +def _maybe_remove_batch_dim( + name: str, + batched_output: Any, + vmap_level: int, + batch_size: int, + out_dim: int | None, +) -> torch.Tensor: + if out_dim is None: + if isinstance(batched_output, torch.Tensor) and is_batchedtensor( + batched_output + ): + raise ValueError( + f"vmap({name}, ...): `{name}` can not return a " + f"BatchedTensor when out_dim is None" + ) + return batched_output + + # out_dim is non None + if not isinstance(batched_output, torch.Tensor): + raise ValueError( + f"vmap({name}, ...): `{name}` must only return " + f"Tensors, got type {type(batched_output)}. " + "Did you mean to set out_dims= to None for output?" + ) + + return _remove_batch_dim(batched_output, vmap_level, batch_size, out_dim) + + +# 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[..., Any], +) -> tuple[Any, ...]: + flat_batched_outputs, output_spec = tree_flatten(batched_outputs) + + def incompatible_error() -> NoReturn: + raise ValueError( + f"vmap({_get_name(func)}, ..., out_dims={out_dims})(): " + f"out_dims is not compatible with the structure of `outputs`. " + f"out_dims has structure {tree_flatten(out_dims)[1]} but outputs " + f"has structure {output_spec}." + ) + + flat_out_dims: list[int | None] = [] + if isinstance(batched_outputs, torch.Tensor): + # Some weird edge case requires us to spell out the following + # see test_out_dims_edge_case + if isinstance(out_dims, int): + flat_out_dims = [out_dims] + elif isinstance(out_dims, tuple) and len(out_dims) == 1: + flat_out_dims = list(out_dims) + elif out_dims is None: + flat_out_dims = [out_dims] + else: + incompatible_error() + else: + broadcast_result = _broadcast_to_and_flatten(out_dims, output_spec) + if broadcast_result is None: + incompatible_error() + else: + flat_out_dims = broadcast_result + + flat_outputs = [ + _maybe_remove_batch_dim( + _get_name(func), batched_output, vmap_level, batch_size, out_dim + ) + for batched_output, out_dim in zip(flat_batched_outputs, flat_out_dims) + ] + return tree_unflatten(flat_outputs, output_spec) + + +def _check_int_or_none(x: Any, func: Callable[..., Any], out_dims: out_dims_t) -> None: + if isinstance(x, int): + return + if x is None: + return + raise ValueError( + f"vmap({_get_name(func)}, ..., out_dims={out_dims}): `out_dims` must be " + f"an int, None or a python collection of ints representing where in the outputs the " + f"vmapped dimension should appear." + ) + + +def _check_out_dims_is_int_or_int_pytree( + out_dims: out_dims_t, func: Callable[..., Any] +) -> None: + if isinstance(out_dims, int): + return + tree_map_(partial(_check_int_or_none, func=func, out_dims=out_dims), out_dims) + + +def _get_name(func: Callable[..., Any]) -> str: + if hasattr(func, "__name__"): + return func.__name__ + + if isinstance(func, functools.partial): + return f"functools.partial({_get_name(func.func)}, ...)" + + # Not all callables have __name__, in fact, only static functions/methods + # do. A callable created via nn.Module, to name one example, doesn't have a + # __name__. + return repr(func) + + +def vmap_impl( + func: Callable[_P, Tensor | tuple[Tensor, ...]], + in_dims: in_dims_t, + out_dims: out_dims_t, + randomness: str, + chunk_size: int | None, + *args: _P.args, + **kwargs: _P.kwargs, +) -> Any: + lazy_load_decompositions() + _check_out_dims_is_int_or_int_pytree(out_dims, func) + batch_size, flat_in_dims, flat_args, args_spec = _process_batched_inputs( + in_dims, args, func + ) + + if chunk_size is not None: + chunks_flat_args = _get_chunked_inputs( + flat_args, flat_in_dims, batch_size, chunk_size + ) + return _chunked_vmap( + func, + flat_in_dims, + chunks_flat_args, + args_spec, + out_dims, + randomness, + **kwargs, + ) + + # If chunk_size is not specified. + return _flat_vmap( + func, + batch_size, + flat_in_dims, + flat_args, + args_spec, + out_dims, + randomness, + **kwargs, + ) + + +def get_chunk_sizes(total_elems: int, chunk_size: int) -> list[int]: + n_chunks = total_elems // chunk_size + chunk_sizes = [chunk_size] * n_chunks + # remainder chunk + remainder = total_elems % chunk_size + if remainder != 0: + chunk_sizes.append(remainder) + return chunk_sizes + + +def _get_chunked_inputs( + flat_args: list[Any], + flat_in_dims: list[int | None], + batch_size: int, + chunk_size: int | None, +) -> Iterable[tuple[Any, ...]]: + split_idxs = (batch_size,) + if chunk_size is not None: + chunk_sizes = get_chunk_sizes(batch_size, chunk_size) + split_idxs = tuple(itertools.accumulate(chunk_sizes)) + + flat_args_chunks = tuple( + ( + t.tensor_split(split_idxs, dim=in_dim) + if in_dim is not None + else [ + t, + ] + * len(split_idxs) + ) + for t, in_dim in zip(flat_args, flat_in_dims) + ) + + # transpose chunk dim and flatten structure + # chunks_flat_args is a list of flatten args + chunks_flat_args = zip(*flat_args_chunks) + return chunks_flat_args + + +def _flatten_chunks_output( + chunks_output_: list[Any], +) -> tuple[list[tuple[Any, ...]], TreeSpec]: + # chunks_output is a list of chunked outputs + # flatten chunked outputs: + flat_chunks_output: list[list[Any]] = [] + arg_spec: TreeSpec | None = None + for output in chunks_output_: + flat_output, arg_specs = tree_flatten(output) + flat_chunks_output.append(flat_output) + if arg_spec is None: + arg_spec = arg_specs + + # transpose chunk dim and flatten structure + # flat_output_chunks is flat list of chunks + flat_output_chunks = list(zip(*flat_chunks_output)) + if arg_spec is None: + raise AssertionError("arg_spec must not be None") + return flat_output_chunks, arg_spec + + +def _concat_chunked_outputs( + out_dims: out_dims_t, + arg_spec: TreeSpec, + flat_output_chunks: list[tuple[Any, ...] | None], +) -> list[Tensor]: + # concat chunks on out_dim + flat_out_dims = _broadcast_to_and_flatten(out_dims, arg_spec) + if flat_out_dims is None: + raise AssertionError("flat_out_dims must not be None") + if len(flat_out_dims) != len(flat_output_chunks): + raise AssertionError( + f"len(flat_out_dims)={len(flat_out_dims)} != len(flat_output_chunks)={len(flat_output_chunks)}" + ) + flat_output: list[Tensor] = [] + for idx, out_dim in enumerate(flat_out_dims): + chunk = flat_output_chunks[idx] + if chunk is None: + raise AssertionError(f"chunk at index {idx} must not be None") + flat_output.append(torch.cat(chunk, dim=out_dim)) + # release tensors + flat_output_chunks[idx] = None + + return flat_output + + +# Applies vmap on chunked_input and returns concatenated output over the chunks. +def _chunked_vmap( + func: Callable[_P, Tensor | tuple[Tensor, ...]], + flat_in_dims: list[int | None], + chunks_flat_args: Iterable[tuple[Any, ...]], + args_spec: TreeSpec, + out_dims: out_dims_t, + randomness: str, + **kwargs: Any, +) -> Any: + chunks_output: list[Any] = [] + rs = torch.get_rng_state() if randomness == "same" else None + for flat_args_tuple in chunks_flat_args: + flat_args = list(flat_args_tuple) + batch_size = _validate_and_get_batch_size(flat_in_dims, flat_args) + + # The way we compute split the input in `_get_chunked_inputs`, + # we may get a tensor with `0` batch-size. We skip any computation + # in that case. + # Eg. + # >>> chunk_size = 1 + # >>> batch_size = 6 + # >>> t = torch.zeros(batch_size, 1) + # >>> t.tensor_split([1, 2, 3, 4, 5, 6]) + # (tensor([[0.]]), tensor([[0.]]), tensor([[0.]]), tensor([[0.]]), + # tensor([[0.]]), tensor([[0.]]), tensor([], size=(0, 1))) + if batch_size == 0: + continue + + if rs is not None: + torch.set_rng_state(rs) + chunks_output.append( + _flat_vmap( + func, + batch_size, + flat_in_dims, + flat_args, + args_spec, + out_dims, + randomness, + **kwargs, + ) + ) + + flat_output_chunks, arg_spec = _flatten_chunks_output(chunks_output) + + # chunked output tensors are held by both `flat_output_chunks` and `chunks_output`. + # eagerly remove the reference from `chunks_output`. + del chunks_output + + # concat chunks on out_dim + # Note: We use cast since flat_output_chunks is modified in _concat_chunked_outputs + # to set elements to None after processing + flat_output = _concat_chunked_outputs( + out_dims, arg_spec, cast(list[tuple[Any, ...] | None], flat_output_chunks) + ) + + # finally unflatten the output + return tree_unflatten(flat_output, arg_spec) + + +# Vmap refactored helper functions: +def _check_randomness_arg(randomness: str) -> None: + if randomness not in ["error", "different", "same"]: + raise RuntimeError( + f"Only allowed values for randomness are 'error', 'different', or 'same'. Got {randomness}" + ) + + +@contextlib.contextmanager +def vmap_increment_nesting( + batch_size: int, randomness: str +) -> Generator[int, None, None]: + try: + vmap_level = _vmap_increment_nesting(batch_size, randomness) + yield vmap_level + finally: + _vmap_decrement_nesting() + + +def _flat_vmap( + func: Callable[..., Tensor | tuple[Tensor, ...]], + batch_size: int, + flat_in_dims: list[int | None], + flat_args: list[Any], + args_spec: TreeSpec, + out_dims: out_dims_t, + randomness: str, + **kwargs: Any, +) -> Any: + with vmap_increment_nesting(batch_size, randomness) as vmap_level: + batched_inputs = _create_batched_inputs( + flat_in_dims, flat_args, vmap_level, args_spec + ) + batched_outputs = func(*batched_inputs, **kwargs) + return _unwrap_batched(batched_outputs, out_dims, vmap_level, batch_size, func) + + +# `restore_vmap` is a private helper function. It is vmap but has the following +# differences: +# - instead of returning outputs, it returns an (outputs, out_dims) tuple. +# out_dims is a pytree of same shape as outputs and contains Optional[int] +# specifying where the vmapped dimension, if it exists, is in the corresponding output. +# - does no validation on in_dims or inputs (vmap expects at least one Tensor to be vmapped). +# restore_vmap allows for no inputs to have the vmap dimension +# - does no validation on outputs (vmap expects only Tensor outputs) +# restore_vmap allows for return of arbitrary outputs (not just Tensors) +# +# The TL;DR is that restore_vmap is more general than vmap and has a slightly +# different API. The relaxations are so that we can "pause" vmap in the middle +# of its execution and then "restore" it later (this is what we do in +# the generate_vmap_rule=True implementation of autograd.Function). +# +# restore_vmap can be technically used in the implementation of vmap, but doing +# that refactor is a bit technically challenging because: +# - vmap couples the tensor-wrapping code with error checking +# - vmap's tensor unwrapping code is in C++; we would need to rewrite part of it +# in python because it overlaps with unwrap_batched +def restore_vmap( + func: Callable[..., _R], in_dims: in_dims_t, batch_size: int, randomness: str +) -> Callable[..., tuple[Any, Any]]: + def inner(*args: Any, **kwargs: Any) -> tuple[Any, Any]: + with vmap_increment_nesting(batch_size, randomness) as vmap_level: + batched_inputs = wrap_batched(args, in_dims, vmap_level) + batched_outputs = func(*batched_inputs, **kwargs) + return unwrap_batched(batched_outputs, vmap_level) + + return inner + + +def wrap_batched( + args: tuple[Any, ...], bdims: in_dims_t, level: int +) -> tuple[Any, ...]: + flat_args, spec = tree_flatten(args) + flat_bdims = _broadcast_to_and_flatten(bdims, spec) + if flat_bdims is None: + raise AssertionError("flat_bdims must not be None") + result = _create_batched_inputs(flat_bdims, flat_args, level, spec) + return result + + +def unwrap_batched(args: Any, level: int) -> tuple[Any, Any]: + flat_args, spec = tree_flatten(args) + if len(flat_args) == 0: + return args, () + result = [ + ( + torch._C._functorch._unwrap_batched(arg, level) + if isinstance(arg, torch.Tensor) + else (arg, None) + ) + for arg in flat_args + ] + output, bdims = zip(*result) + return tree_unflatten(output, spec), tree_unflatten(bdims, spec) diff --git a/.venv/lib/python3.12/site-packages/torch/_guards.py b/.venv/lib/python3.12/site-packages/torch/_guards.py new file mode 100644 index 0000000000000000000000000000000000000000..0b1eac5bf3a996d9dabc7a543942832ec4714689 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_guards.py @@ -0,0 +1,1610 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import enum +import functools +import logging +import re +import sys +import threading +import traceback +import unittest.mock +import weakref +from abc import abstractmethod +from collections import defaultdict +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Any, Generic, NamedTuple, overload, TYPE_CHECKING, TypeVar +from typing_extensions import dataclass_transform + +import torch +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet +from torch.utils._python_dispatch import is_traceable_wrapper_subclass +from torch.utils._traceback import CapturedTraceback, format_frame +from torch.utils.weak import WeakTensorKeyDictionary + + +log = logging.getLogger(__name__) + + +if TYPE_CHECKING: + import dis + from collections.abc import Callable, Generator, Iterator + from types import CodeType + + import sympy + + from torch._dynamo.backends.distributed import DDPOptimizerContext + from torch._dynamo.codegen import PyCodegen + from torch._dynamo.guards import GuardCheckSpec + from torch._dynamo.output_graph import CodeOptions + from torch._functorch._aot_autograd.schemas import ViewAndMutationMeta + from torch._higher_order_ops.invoke_subgraph import NestedCompileRegionOptions + from torch._subclasses.fake_tensor import FakeTensorMode + + +""" +torch._guards is the definitional source of truth for general purpose guard structures. + +An important thing to keep in mind here is the preservation of layering. There should be no dynamo notions, +and no guard installation notions here. +""" + +COMPILE_ID_PATTERN = re.compile(r"^(?P\d+)/(?P\d+)$") +CA_COMPILE_ID_PATTERN = re.compile( + r"^!(?P\d+)(?:/(?P\d+)/(?P\d+))?$" +) + +# [Note: Updating CompiledId] +# +# CompiledId represents a unique program-level identifier, and we want to keep that +# property as the codebase evolves. This property is relied on even outside of the pytorch +# repo, e.g. tlparse or other internal tooling. The in-memory format can be freely changed, +# as those dependencies only consume the string serialization. +# +# The string form should be: +# 1. Program-level uid: CompileId can uniquely identify a compiled graph. +# 2. Storage efficient: This object is logged in nearly every entry. We should elide symbols when possible. +# 3. Compact: The string form is directly displayed by some tools. Special symbols are okay. + + +@dataclass(frozen=True, kw_only=True, slots=True) +class CompileId: + frame_id: int | None + # This id is per-frame, and counts how many times we've compiled this + # frame. This could have been a global id but having this be per-frame + # gives you a better intuitive sense for how many recompiles have occurred + # so far. + frame_compile_id: int | None + + # torch.compiling a compiled autograd graph + compiled_autograd_id: int | None = None + + # TODO: consider also tracking the recompilation count + # See Note: Updating CompileId + + def __str__(self) -> str: + # NOTE: Keep this in sync with both from_string and the tlparse repo + if self.compiled_autograd_id is not None: + if (self.frame_id is None) != (self.frame_compile_id is None): + raise AssertionError( + f"frame_id and frame_compile_id must both be None or both be set, " + f"got frame_id={self.frame_id}, frame_compile_id={self.frame_compile_id}" + ) + frame_str = "" + if self.frame_id is not None: + frame_str = f"/{self.frame_id}/{self.frame_compile_id}" + + return f"!{self.compiled_autograd_id}{frame_str}" + else: + if self.frame_id is None or self.frame_compile_id is None: + raise AssertionError( + f"frame_id and frame_compile_id must not be None, " + f"got frame_id={self.frame_id}, frame_compile_id={self.frame_compile_id}" + ) + return f"{self.frame_id}/{self.frame_compile_id}" + + @classmethod + def from_string(cls, compile_id: str | None) -> CompileId | None: + """ + Factory method that creates a CompileId from its string representation. + Keep this in sync with the __str__ method. + """ + if compile_id is None: + return None + try: + for pattern in (COMPILE_ID_PATTERN, CA_COMPILE_ID_PATTERN): + if match := pattern.match(compile_id): + groups = match.groupdict() + for k, v in groups.items(): + if v is not None: + groups[k] = int(v) + return cls(**groups) # type: ignore[arg-type] + else: + raise ValueError + + except Exception as e: + raise ValueError(f"Invalid compile_id '{compile_id}'") from e + + +class TraceId(NamedTuple): + compile_id: CompileId + # This starts off as 0, and every time we restart analysis it goes + # up by one + attempt: int + + def __str__(self) -> str: + # Keep this in sync with tlparse repo + if self.attempt == 0: + return str(self.compile_id) + else: + return f"{self.compile_id}_{self.attempt}" + + +class GuardSource(enum.Enum): + LOCAL = 0 + GLOBAL = 1 + LOCAL_SPECIALIZED_NN_MODULE = 2 + GLOBAL_SPECIALIZED_NN_MODULE = 3 + CONSTANT = 4 + RANDOM_VALUE = 5 + SHAPE_ENV = 6 + LOCAL_FSDP_MODULE = 7 + GLOBAL_FSDP_MODULE = 8 + BACKWARD_STATE = 9 + EPHEMERAL = 10 + SYNTHETIC_LOCAL = 11 + LOCAL_UNSPECIALIZED_NN_MODULE = 12 + GLOBAL_UNSPECIALIZED_NN_MODULE = 13 + LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 14 + GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 15 + TEMP_LOCAL = 16 + + def is_fsdp_module(self) -> bool: + return self in (GuardSource.GLOBAL_FSDP_MODULE, GuardSource.LOCAL_FSDP_MODULE) + + def is_specialized_nn_module(self) -> bool: + import torch._dynamo.config as config + + if config._unsafe_skip_fsdp_module_guards: + return ( + self + in ( + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + ) + or self.is_fsdp_module() + ) + return self in ( + GuardSource.GLOBAL_SPECIALIZED_NN_MODULE, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + ) + + def is_unspecialized_nn_module(self) -> bool: + return self in ( + GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + ) + + def is_unspecialized_builtin_nn_module(self) -> bool: + return self in ( + GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + ) + + def is_local(self) -> bool: + return self in ( + GuardSource.LOCAL, + GuardSource.LOCAL_SPECIALIZED_NN_MODULE, + GuardSource.LOCAL_FSDP_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE, + GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE, + ) + + +""" +Base class for a "GuardBuilder" role. + +The GuardBuilderBase role is to represent a scope within which to build a guard. The name is a little +confusing, as it's not a builder, but for the sake of avoiding a lot of renames and keeping the original reference +to torchdynamo's GuardBuilder. + +Note: create_fn is invoked with a GuardBuilderBase and a Guard. A GuardBuilder is chosen based +on GuardSource's select function. + +There is value in keeping this GuardBuilderBase empty to keep layering clean. +""" + + +class GuardBuilderBase: + pass + + +@dataclasses.dataclass(frozen=True) +class SLoc: + framework_loc: traceback.FrameSummary | str | None + maybe_user_loc: str | None + + def __str__(self) -> str: + floc = ( + self.framework_loc + if isinstance(self.framework_loc, str) + else "" + if self.framework_loc is None + else format_frame(self.framework_loc) + ) + if self.maybe_user_loc is not None: + return f"{self.maybe_user_loc} ({floc})" + else: + return f"({floc})" + + +class ShapeGuard(NamedTuple): + expr: sympy.logic.boolalg.Boolean + sloc: SLoc + size_oblivious: bool + + +@dataclasses.dataclass(slots=True) +class Guard: + # originating_source is the source that called the make_guard method to + # construct this guard object. The property name specifies what exactly it + # is the guard is guarding on. The meaning of the name is dependent on the + # create_fn; you must look at the use-site inside create_fn to know what + # name means. + # + # That being said, although you might think this is just a "name", name is + # usually an arbitrary Python expression that will be evaluated with all + # globals (and locals, if you create a LOCAL guard) to extract the Python + # object that we want to perform guard tests on. This evaluation + # typically happens in GuardBuilder.eval. In these cases, name is + # typically produced by originating_source.name (not to be confused with + # GuardSource - the property source). + # + # Occasionally, name is not a valid Python expression; sometimes + # it is meaningless. Example create_fns that are like this include + # GRAD_MODE and SHAPE_ENV. + originating_source: Source + create_fn: Callable[[GuardBuilderBase, Guard], None] + + # Export only. These values are written to at time of guard check_fn creation. + guard_types: list[str] | None = None + code_list: list[str] | None = None + obj_weakref: object | None = None + guarded_class_weakref: weakref.ReferenceType[Any] | None = None + + stack: CapturedTraceback | None = None + user_stack: traceback.StackSummary | None = None + _hash: int | None = None + _unserializable: bool = False + _force_dict_keys_match: bool = False + + def __hash__(self) -> int: + if self._hash is None: + self._hash = hash((self.name, self.source, id(self.create_fn))) + return self._hash + + def sort_key(self) -> tuple[bool, int, int, str, int]: + # Put the duplicate input guards at the end. The duplicate guards have + # two sources while guard.name only considers one source. + + is_duplicate_input = ( + isinstance(self.create_fn, functools.partial) + and self.create_fn.func is torch._dynamo.guards.GuardBuilder.DUPLICATE_INPUT + ) + return ( + is_duplicate_input, + self.source.value if self.source else -1, + len(self.name), + self.name, + self.inner_create_fn().__code__.co_firstlineno, + ) + + def __lt__(self, other: Guard) -> bool: + return self.sort_key() < other.sort_key() + + def inner_create_fn(self) -> Callable[[GuardBuilderBase, Guard], Any]: + if isinstance(self.create_fn, functools.partial): + return self.create_fn.func + else: + return self.create_fn + + @property + def name(self) -> str: + return self.originating_source.name + + @property + def source(self) -> GuardSource: + return self.originating_source.guard_source + + @staticmethod + def weakref_to_str(obj_weakref: object) -> str: + """ + This is a workaround of a Python weakref bug. + + `obj_weakref` is instance returned by `weakref.ref`, + `str(obj_weakref)` is buggy if the original obj overrides __getattr__, e.g: + + class MyConfig(dict): + def __getattr__(self, x): + return self[x] + + obj = MyConfig(offset=5) + obj_weakref = weakref.ref(obj) + str(obj_weakref) # raise error: KeyError: '__name__' + """ + if isinstance(obj_weakref, weakref.ReferenceType): + obj = obj_weakref() + if obj is not None: + return f"" + else: + return f"" + else: + return str(obj_weakref) + + def __repr__(self) -> str: + s = f""" + {self.source.name.lower() if self.source else ""} {repr(self.name)} {self.inner_create_fn().__name__} + {{ + 'guard_types': {self.guard_types}, + 'code': {self.code_list}, + 'obj_weakref': {self.weakref_to_str(self.obj_weakref)} + 'guarded_class': {self.guarded_class_weakref} + }} + """ + return s + + def __str__(self) -> str: + output = f"Name: {repr(self.name)}\n" + source = self.source.name.lower() if self.source else "" + output += f" Source: {source}\n" + output += f" Create Function: {self.inner_create_fn().__name__}\n" + output += f" Guard Types: {self.guard_types}\n" + output += f" Code List: {self.code_list}\n" + output += f" Object Weakref: {self.weakref_to_str(self.obj_weakref)}\n" + output += f" Guarded Class Weakref: {self.guarded_class_weakref}\n" + return output + + def create(self, builder: GuardBuilderBase) -> Any: + try: + return self.create_fn(builder, self) + except Exception: + log.exception("Error while creating guard:\n%s", str(self).rstrip()) + if self.stack: + log.error("Created at:\n%s", "".join(self.stack.format()[-4:]).rstrip()) + raise + + def is_specialized_nn_module(self) -> bool: + return self.source.is_specialized_nn_module() + + def is_fsdp_module(self) -> bool: + return self.source.is_fsdp_module() + + def is_local(self) -> bool: + return self.source.is_local() + + def create_fn_name(self) -> str: + if isinstance(self.create_fn, functools.partial): + create_fn = self.create_fn.func # type: ignore[attr-defined] + else: + create_fn = self.create_fn + return create_fn.__name__ + + def set_export_info( + self, + guard_type: str, + guarded_class: weakref.ReferenceType[Any] | None, + code_list: list[str], + obj_weakref: object, + ) -> None: + if not self.guard_types: + self.guard_types = [] + + self.guard_types.append(guard_type) + + if self.guarded_class_weakref not in (guarded_class, None): + raise AssertionError( + f"Guarded class id must be identical, or None, " + f"got {self.guarded_class_weakref} vs {guarded_class}" + ) + self.guarded_class_weakref = guarded_class + + if not self.code_list: + self.code_list = code_list + else: + self.code_list.extend(code_list) + + # Some objects are ephemeral, e.g., list[slice(1, 2)]. If we have + # multiple guards on the same object, the weakref can die between the + # invocation of set_export_info calls. So a dead weakref is also + # acceptable. + is_valid = ( + self.obj_weakref in (obj_weakref, None) + or callable(self.obj_weakref) + and self.obj_weakref() is None + ) + if not is_valid: + raise AssertionError( + f"Guarded object must be identical, None or ephemeral (dead weakref), " + f"got {self.obj_weakref} vs {obj_weakref}" + ) + self.obj_weakref = obj_weakref + + +T = TypeVar("T") + +""" +Parent structure for guard env expressions. +A GuardEnvExpr can have any subtype. +Note: All subtypes must be handled exhaustively in +torch._dynamo.guards._parse_guard_env_guards to avoid a RuntimeError. +""" + + +@dataclasses.dataclass(frozen=True) +class GuardEnvExpr: + pass + + +""" +A class representing a pair of duplicate inputs. +input_pos_a and input_pos_b are input positions we have deduped. +""" + + +@dataclasses.dataclass(frozen=True) +class DuplicateInputs(GuardEnvExpr): + input_source_a: Source + input_source_b: Source + + def __post_init__(self) -> None: + if self.input_source_a == self.input_source_b: + raise AssertionError( + f"input_source_a and input_source_b must be different, " + f"got {self.input_source_a}" + ) + + +""" +A class representing storage overlap relations among inputs that aliases the same storage. + +Given that a set of tensors alias the same storage, this guard checks whether they actually +have overlapping storages. + +While non_overlapping_sources represent input tensors that definitely don't have any storage +overlapping with any other input, overlapping_sources represent tensors that either: + +1. Do overlap some other input tensor +2. Might not overlap some other input tensor, but we are not sure +""" + + +@dataclasses.dataclass(frozen=True) +class StorageOverlap(GuardEnvExpr): + overlapping_sources: list[Source] + non_overlapping_sources: list[Source] + + +""" +Checkpointable is an interface for driving state snapshotting, left purposely vague for now. + +copy_graphstate() -> T, a somewhat legacy name, is expected to emit a snapshot of any type that +can also be taken in at restore_graphstate(T) calls. + +When to snapshot, is, at the moment, an implementation detail of upstream callers. Checkpointable +does not provide any guarantees around consistency, idempotency, or safety of calling its APIs, yet. + +In the future, it will have a closer coupling to a generic Checkpoint management system. +""" + + +class Checkpointable(Generic[T]): + @abstractmethod + def copy_graphstate(self) -> T: ... + + @abstractmethod + def restore_graphstate(self, state: T) -> None: ... + + +class GuardsCheckpointState: + """ + The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext + """ + + dynamo_guards: OrderedSet[Guard] + + def __init__(self, dynamo_guards: OrderedSet[Guard]) -> None: + self.dynamo_guards = dynamo_guards + + def diff(self, other: GuardsCheckpointState) -> OrderedSet[Guard] | None: + """ + Produces a delta against another GuardsCheckpointState. + + Returns None if no delta is found, otherwise, return an OrderedSet() of mismatched + Guard type objects. + """ + r = self.dynamo_guards.difference(other.dynamo_guards) + if len(r) == 0: + return None + return r + + def __eq__(self, other: object) -> bool: + if not isinstance(other, GuardsCheckpointState): + return False + return self.diff(other) is None + + +class ModuleContextCheckpointState: + nn_modules: dict[str, torch.nn.Module] = {} + + def __init__(self, nn_modules: dict[str, torch.nn.Module]) -> None: + self.nn_modules = nn_modules + + def diff(self, other: ModuleContextCheckpointState) -> set[str] | None: + """ + Produces a delta against another ModuleContextCheckpointState. + + Returns None if no delta is found, otherwise, return a set() of mismatched + module key names. + """ + r = set(self.nn_modules.keys()).difference(set(other.nn_modules.keys())) + if len(r) == 0: + return None + return r + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ModuleContextCheckpointState): + return False + return self.diff(other) is None + + +class ModuleContext(Checkpointable[ModuleContextCheckpointState]): + def __init__(self) -> None: + self.nn_modules: dict[str, Any] = {} + + def copy_graphstate(self) -> ModuleContextCheckpointState: + return ModuleContextCheckpointState(dict(self.nn_modules)) + + def restore_graphstate(self, state: ModuleContextCheckpointState) -> None: + if not isinstance(state, ModuleContextCheckpointState): + raise AssertionError( + f"expected ModuleContextCheckpointState, got {type(state)}" + ) + self.nn_modules = state.nn_modules + + +class GlobalContextCheckpointState: + global_state: dict[str, tuple[Callable, Any]] = {} + + def __init__(self, global_states: dict[str, tuple[Callable, Any]]) -> None: + self.global_state = global_states + + def diff(self, other: GlobalContextCheckpointState) -> set[str] | None: + """ + Produces a delta against another GlobalContextCheckpointState. + + Returns None if no delta is found, otherwise, return a set() of mismatched + global key names. + """ + r = set(self.global_state.keys()).difference(set(other.global_state.keys())) + if len(r) == 0: + return None + return r + + def __eq__(self, other: object) -> bool: + if not isinstance(other, GlobalContextCheckpointState): + return False + return self.diff(other) is None + + +class GlobalContext(Checkpointable[GlobalContextCheckpointState]): + """ + This keeps track of the global torch state during tracing of a function. + For example, torch.is_grad_enabled. + """ + + _supported_global_states = { + "grad_enabled", + "autocast_enabled", + "autocast_cpu_enabled", + "autocast_gpu_dtype", + "autocast_cpu_dtype", + "autocast_cache_enabled", + } + + def __init__(self) -> None: + self.global_state: dict[str, tuple[Callable, Any]] = {} + + def copy_graphstate(self) -> GlobalContextCheckpointState: + return GlobalContextCheckpointState(self.global_state) + + def restore_graphstate(self, state: GlobalContextCheckpointState) -> None: + if not isinstance(state, GlobalContextCheckpointState): + raise AssertionError( + f"expected GlobalContextCheckpointState, got {type(state)}" + ) + self.global_state = state.global_state + if not ( + len(self.global_state) == len(self._supported_global_states) + and set(self.global_state.keys()) == self._supported_global_states + ): + raise AssertionError( + f"Global state mismatch: got keys {set(self.global_state.keys())}, " + f"expected {self._supported_global_states}" + ) + for func, args in self.global_state.values(): + func(args) + + +# Like a Set[Guard] but will record the user stack on all guards at the +# time they were installed at their destination +class GuardsSet: + def __init__(self, inner: OrderedSet[Guard] | None = None) -> None: + if inner is None: + self.inner: OrderedSet[Guard] = OrderedSet() + else: + self.inner = inner + # Map from source to list of guards with that source. Incrementally + # built in `add` method. + self.source_to_guards: defaultdict[Source, list[Guard]] = defaultdict(list) + for guard in self.inner: + self.track_guard_by_source(guard) + + def track_guard_by_source(self, guard: Guard) -> None: + source = guard.originating_source + self.source_to_guards[source].append(guard) + + def __iter__(self) -> Iterator[Guard]: + return iter(self.inner) + + def __len__(self) -> int: + return len(self.inner) + + # Subtraction along with bool is typically used to determine the delta of + # added guards between checkpoints for higher order ops + def __sub__(self, other: GuardsSet) -> GuardsSet: + return GuardsSet(self.inner - other.inner) + + def __bool__(self) -> bool: + return bool(self.inner) + + def clear(self) -> None: + self.inner = OrderedSet() + self.source_to_guards = defaultdict(list) + + def add( + self, guard: Guard, *, collect_debug_stack: bool = True, skip: int = 0 + ) -> None: + if guard in self.inner: + return + if collect_debug_stack: + if guard.stack is None: + guard.stack = CapturedTraceback.extract(skip=1 + skip) + if guard.user_stack is None: + guard.user_stack = TracingContext.extract_stack() + self.inner.add(guard) + self.track_guard_by_source(guard) + + def update(self, *others: set[Guard]) -> None: + for o in others: + for g in o: + self.add(g, skip=1) + + def get_guards_for_source(self, source: Source) -> list[Guard]: + """Return all guards with the given originating_source.""" + return list(self.source_to_guards[source]) + + def remove_guards_with_source(self, source: Source) -> None: + """Delete all guards that contains a given source""" + from ._dynamo.source import is_from_source + + self.inner = OrderedSet( + g for g in self.inner if not is_from_source(g.originating_source, source) + ) + # Rebuild the index since is_from_source walks the chain, so + # multiple source keys may need removal. + self.source_to_guards = defaultdict(list) + for guard in self.inner: + self.track_guard_by_source(guard) + + +""" +A GuardsContext is a checkpointable representation of all the guards in the current tracing +context. Its lifecycle is bound 1:1 to the tracing context, and it should never be instantiated +directly outside of it. For passing around internal state representations of this object, +prefer to extract them with copy_graphstate to produce a GuardsCheckpointState. +""" + + +class GuardsContext(Checkpointable[GuardsCheckpointState]): + def __init__(self) -> None: + self.dynamo_guards: GuardsSet = GuardsSet() + self.aotautograd_guards: list[GuardEnvExpr] = [] + self.skip_install: bool = False + + @contextlib.contextmanager + def skip_guard_install(self) -> Generator[None, None, None]: + old = self.skip_install + self.skip_install = True + try: + yield + finally: + self.skip_install = old + + def copy_graphstate(self) -> GuardsCheckpointState: + return GuardsCheckpointState(OrderedSet(self.dynamo_guards.inner)) + + def restore_graphstate(self, state: GuardsCheckpointState) -> None: + # NB: "steals" the passed in state + if not isinstance(state, GuardsCheckpointState): + raise AssertionError(f"expected GuardsCheckpointState, got {type(state)}") + self.dynamo_guards = GuardsSet(state.dynamo_guards) + + +class HopSubgraphCache: + @abstractmethod + def add_dynamo_installed_submodule( + self, fn_code: CodeType, identifier: str + ) -> None: ... + + @abstractmethod + def get_dynamo_installed_submodules(self, fn_code: CodeType) -> list[str]: ... + + @abstractmethod + def add_autograd_key_entry(self, identifier: str, key: Callable) -> None: ... + + @abstractmethod + def get_autograd_key_entry(self, identifier: str) -> Callable | None: ... + + @abstractmethod + def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None: ... + + @abstractmethod + def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None: ... + + @abstractmethod + def add_functionalize_schema_entry( + self, key: object, schema: torch._C.FunctionSchema + ) -> None: ... + + @abstractmethod + def get_functionalize_schema_entry( + self, key: object + ) -> torch._C.FunctionSchema | None: ... + + @abstractmethod + def add_lazy_bwd_entry( + self, + identifier: str, + tangent_metadata: tuple[object], + gmod: torch.fx.GraphModule, + ) -> int: ... + + @abstractmethod + def get_lazy_bwd_entry( + self, identifier: str, tangent_metadata: tuple[object] + ) -> tuple[torch.fx.GraphModule | None, int | None]: ... + + +@dataclass +class InvokeSubgraphReuseEntry: + body_name: str + body_gmod: torch.fx.GraphModule + config: NestedCompileRegionOptions | None + subgraph_input_mapping: list[ + Any + ] # list[LiftedArgOrigin] - defined in invoke_subgraph.py + single_tensor_output: bool + # Per-output tensor metadata (shape, stride, dtype, device, requires_grad) + # cached from the first trace so we can construct fresh FakeTensors on + # cache hit without re-running body_gmod. + output_metadata: list[ + tuple[torch.Size, tuple[int, ...], torch.dtype, torch.device, bool] + ] + # 1-1 mapping to flat_vts: source for each flattened arg/kwarg, or None if + # the VT has no source. On cache hit, we build a source replacement mapping + # (old arg sources → new arg sources) to rewrite captured variable sources + # for the current invocation. + arg_sources: list[Source | None] + # Number of user-visible outputs (from the function return value). + # The graph may have additional outputs from side-effect intermediates; + # stamp_out_subgraph uses this to return only the user-visible slice. + num_user_outputs: int = 0 + + +@dataclass +class InvokeSubgraphReuseCondition: + # Per flattened input VT: (InputTag, metadata). + # (InputTag.TENSOR, TensorMetadata) + # (InputTag.SYMNODE, sym_num — same object implies same symbol) + # (InputTag.CONSTANT, value) + # (InputTag.OBJECT, None) + # Tensor metadata is checked here because TENSOR_MATCH guards for + # subgraph inputs may already exist before tracing and thus won't + # appear in the guard delta. + input_checks: list[tuple[Any, object]] # list[tuple[InputTag, object]] + + # Guards captured during the trace (delta + source-mapped). + # Each entry: (source, handler, expected_value, guard) + # handler is a pre-resolved GuardCheckSpec from GUARD_VALUE_DISPATCH. + guards: list[tuple[Source, GuardCheckSpec, object, Guard]] + + # TreeSpec from pytree.tree_flatten of the (args, kwargs) structure. + # On cache hit, we verify the new call has the same treespec. + treespec: pytree.TreeSpec | None = None + + # All sources accessed via VariableBuilder during the subgraph trace. + # On cache hit, we check if any modified VT's source is a base of one + # of these to detect mutations on captured variables. + traced_sources: OrderedSet[Source] = dataclasses.field(default_factory=OrderedSet) + + +class InvokeSubgraphCache(HopSubgraphCache): + def __init__(self) -> None: + self.autograd_cache: dict[str, Callable] = {} + self.proxy_dispatch_cache: dict[str, Callable] = {} + self.functionalize_schema_cache: dict[object, torch._C.FunctionSchema] = {} + self.dynamo_installed_submodules: dict[CodeType, list[str]] = defaultdict(list) + self.lazy_bwd_cache: dict[ + str, dict[tuple[object], tuple[torch.fx.GraphModule, int]] + ] = defaultdict(dict) + self.effects_cache: dict[ + str, set + ] = {} # Maps identifier -> set of effect types + # fn.__code__ → list of (condition, cache_entry) pairs. Walked linearly + # on lookup; first matching condition wins. + self.subgraph_reuse_cache: dict[ + CodeType, + list[tuple[InvokeSubgraphReuseCondition, InvokeSubgraphReuseEntry]], + ] = defaultdict(list) + # fn_code → {hash_key → cache_entry}. Used by user-provided + # reuse_hash_fn for O(1) subgraph reuse lookup. + self.subgraph_reuse_key_cache: dict[ + CodeType, dict[int, InvokeSubgraphReuseEntry] + ] = defaultdict(dict) + + def add_dynamo_installed_submodule( + self, fn_code: CodeType, identifier: str + ) -> None: + self.dynamo_installed_submodules[fn_code].append(identifier) + + def get_dynamo_installed_submodules(self, fn_code: CodeType) -> list[str]: + return self.dynamo_installed_submodules.get(fn_code, []) + + def add_autograd_key_entry(self, identifier: str, key: Callable) -> None: + self.autograd_cache[identifier] = key + + def get_autograd_key_entry(self, identifier: str) -> Callable | None: + return self.autograd_cache.get(identifier, None) + + def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None: + self.proxy_dispatch_cache[identifier] = key + + def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None: + return self.proxy_dispatch_cache.get(identifier, None) + + def add_functionalize_schema_entry( + self, key: object, schema: torch._C.FunctionSchema + ) -> None: + self.functionalize_schema_cache[key] = schema + + def get_functionalize_schema_entry( + self, key: object + ) -> torch._C.FunctionSchema | None: + return self.functionalize_schema_cache.get(key, None) + + def add_lazy_bwd_entry( + self, + identifier: str, + tangent_metadata: tuple[object], + gmod: torch.fx.GraphModule, + ) -> int: + # Save the number of existing graph modules in the dictionary to get the suffix + num_gmods = len(self.lazy_bwd_cache[identifier]) + self.lazy_bwd_cache[identifier][tangent_metadata] = (gmod, num_gmods) + return num_gmods + + def get_lazy_bwd_entry( + self, identifier: str, tangent_metadata: tuple[object] + ) -> tuple[torch.fx.GraphModule | None, int | None]: + if identifier not in self.lazy_bwd_cache: + return (None, None) + + return self.lazy_bwd_cache[identifier].get(tangent_metadata, (None, None)) + + def add_effects(self, identifier: str, effects: set) -> None: + """Store the effect types for a given invoke_subgraph identifier.""" + if prev_effects := self.effects_cache.get(identifier, None): + if effects != prev_effects: + raise AssertionError( + "Different number of effects were found for invoke_subgraph " + f"call with identifier {identifier}. \n" + f"Previously we had the following effects: {prev_effects}.\n" + f"But now we have: {effects}." + ) + self.effects_cache[identifier] = effects + + def get_effects(self, identifier: str) -> set | None: + """Retrieve the effect types for a given invoke_subgraph identifier.""" + return self.effects_cache.get(identifier, None) + + def add_reuse_entry( + self, + fn_code: CodeType, + condition: InvokeSubgraphReuseCondition, + entry: InvokeSubgraphReuseEntry, + max_reuse_entries: int = 8, + ) -> None: + entries = self.subgraph_reuse_cache[fn_code] + if len(entries) >= max_reuse_entries: + raise RuntimeError( + f"invoke_subgraph: exceeded maximum reuse entries " + f"({max_reuse_entries}) for function code {fn_code}. " + f"This most likely means a guard keeps failing on every " + f"invocation, preventing subgraph reuse. " + f"Set TORCH_LOGS='+hierarchical_compile' to identify which " + f"guard is failing. If reuse is genuinely not possible and " + f"you need more cache entries, increase the limit via the " + f"max_reuse_entries argument to nested_compile_region()." + ) + entries.append((condition, entry)) + + def find_reuse_entry( + self, + fn_code: CodeType, + evaluator: Callable[ + [InvokeSubgraphReuseCondition, InvokeSubgraphReuseEntry], bool + ], + ) -> InvokeSubgraphReuseEntry | None: + entries = self.subgraph_reuse_cache.get(fn_code, []) + for i, (condition, entry) in enumerate(entries): + if evaluator(condition, entry): + # MRU: move the hit entry to the front for faster future lookups + if i > 0: + entries.insert(0, entries.pop(i)) + return entry + return None + + def find_reuse_entry_by_key( + self, fn_code: CodeType, hash_key: int + ) -> InvokeSubgraphReuseEntry | None: + return self.subgraph_reuse_key_cache.get(fn_code, {}).get(hash_key) + + def add_reuse_entry_by_key( + self, + fn_code: CodeType, + hash_key: int, + entry: InvokeSubgraphReuseEntry, + max_reuse_entries: int = 8, + ) -> None: + key_cache = self.subgraph_reuse_key_cache[fn_code] + if len(key_cache) >= max_reuse_entries and hash_key not in key_cache: + raise RuntimeError( + f"invoke_subgraph: exceeded maximum reuse entries " + f"({max_reuse_entries}) for function code {fn_code} (hash-key path). " + f"Increase the limit via the max_reuse_entries argument to " + f"nested_compile_region()." + ) + key_cache[hash_key] = entry + + +class HopDispatchSetCache: + def __init__(self) -> None: + # Delayed import to avoid circular dependency + from torch._higher_order_ops.invoke_subgraph import invoke_subgraph + + self.hop_cache_map = {invoke_subgraph: InvokeSubgraphCache()} + + def get_cache(self, op: torch._ops.HigherOrderOperator) -> HopSubgraphCache | None: + if op not in self.hop_cache_map: + return None + return self.hop_cache_map[op] # type: ignore[index] + + +class _TLSStorage(threading.local): + # Default the hot-path attributes to None per thread so that + # TracingContext.try_get() / CompileContext.try_get() -- called on every + # torch.compile'd call -- hit a present attribute instead of paying for an + # AttributeError raise+catch inside getattr(). Without this, a thread that + # never ran compilation itself (e.g. a worker thread executing compiled code + # compiled on another thread) takes the slow getattr-miss path on every call. + def __init__(self) -> None: + self.tracing_context: TracingContext | None = None + self.compile_context: CompileContext | None = None + + +_TLS = _TLSStorage() + +""" +TracingContext is the source of truth for all currently accumulated information +needed to trace. Its lifecycle is kept 1:1 when using TorchDynamo, but other systems +are open to managing their own TracingContext with that in mind. + +The purpose of TracingContext is not to be a dumping ground, or god object, but rather to avoid +having to plumb complex subsystems across multiple verticals. + +Ex: A common example is guard accumulation between dynamo, shape_env, aot_autograd, and inductor. +Accessing the current tracing context via +TracingContext.get() allows users to accumulate their own guards for processing, without needing to know how +to plumb objects back up to where frame interpretation happened. + +Note that you can end up with multiple TracingContext for a single compilation +of a frame, as we reset the TracingContext whenever we restart analysis. +CompileContext is a more overarching context that encompasses multiple restarts. +""" + + +class CompileContext: + @staticmethod + def get() -> CompileContext: + if _TLS.compile_context is None: + raise AssertionError("compile_context is not set") + return _TLS.compile_context + + @staticmethod + def try_get() -> CompileContext | None: + return getattr(_TLS, "compile_context", None) + + def __init__(self, compile_id: CompileId | None) -> None: + if compile_id is not None and not isinstance(compile_id, CompileId): + raise AssertionError( + f"compile_id must be None or CompileId, got {type(compile_id)}" + ) + self.compile_id: CompileId | None = compile_id + self.attempt = 0 + # Verbose ShapeEnv guards produced. + self.shape_env_guards: list[str] = [] + + @staticmethod + def current_compile_id() -> CompileId | None: + self = CompileContext.try_get() + if self is None: + return None + return self.compile_id + + @staticmethod + def current_trace_id() -> TraceId | None: + self = CompileContext.try_get() + if self is None: + return None + if self.compile_id is None: + return None + return TraceId(self.compile_id, self.attempt) + + +@dataclass +class InlinedCodeCache: + """Cache for code-object-derived data used during inlining.""" + + instructions: list[Any] + indexof: dict[Any, int] + code_options: CodeOptions + + +class TracingContext: + """ + Provides the currently installed TracingContext, or None. + + Note that it is a staticmethod, and invocations outside of `with tracing()` (see below), are valid but + will return None. + """ + + @staticmethod + def try_get() -> TracingContext | None: + return getattr(_TLS, "tracing_context", None) + + @staticmethod + def get() -> TracingContext: + if ctx := TracingContext.try_get(): + return ctx + raise RuntimeError( + "TracingContext.get() must be called within an ongoing trace." + ) + + def __init__(self, fake_mode: FakeTensorMode | None) -> None: + self.guards_context = GuardsContext() + self.module_context = ModuleContext() + self.global_context = GlobalContext() + self.previously_inlined_functions: dict[Any, Any] = dict() + self.previously_cleaned_instructions: dict[Any, Any] = dict() + # Combined cache for inlined code data (instructions, indexof, code_options) + self.inlined_code_cache: dict[Any, InlinedCodeCache] = dict() + self.fake_mode: FakeTensorMode | None = fake_mode + self.frame_summary_stack: list[traceback.FrameSummary] = [] + # This is morally part of frame_summary_stack, but it is kept separate + # for clarity. As we process a frame, this variable gets updated + # to keep track of what line we are in the function. We make a + # function call, this gets cleared and the frame location is pushed + # to frame_summary_stack (prepping this variable for the inner frame's + # progress) + self.loc_in_frame: tuple[str, int, str] | None = None + self.loc_in_frame_positions: dis.Positions | None = None + # this is only set after aot_autograd + self.fw_metadata: ViewAndMutationMeta | None = None + # this is only set when the DDPOptimizer is used + self.ddp_optimizer_ctx: DDPOptimizerContext | None = None + # this is only set after aot_autograd + self.aot_graph_name: list[str] | None = None + self.params_flat: list[Any] | None = None + self.params_flat_unwrap_subclasses: list[Any] | None = None + self.params_unwrapped_to_flat_index: list[Any] | None = None + # this is for extended return calling convention from backend + # compiler to aot_autograd + # Per output, what the compiler specified stride of the output is, + # or None if no stride is known. This is always the HINT, it + # is never a SymInt (it would be better if it was a SymInt, but + # I can't conveniently get this from Inductor atm. Also, be + # careful not to accidentally induce guards on the SymInt if + # you ever do change this in aot_autograd.py; you should check + # on permutations preferentially.) + self.output_strides: list[tuple[int, ...] | None] | None = None + # When this is True, whenever we encounter an int in Dynamo tracing, + # we will (1) force unspec it and (2) force it as a size-like unbacked + # integer. This is currently used when processing certain lists of + # ints that are known to be size-like and may have 0/1 entries that we + # must not specialize on. + self.force_unspec_int_unbacked_size_like = False + # See note [Tensor Fakification and Symbol Caching] + self.tensor_to_context = WeakTensorKeyDictionary() + + # If this true, Aot Autograd will return output Fake Tensors with appropriate + # meta on the first invocation + # see note: [Returning Fake Tensors on First AOT Autograd Call] + self.fakify_first_call = False + self.hop_dispatch_set_cache = HopDispatchSetCache() + # list of code objects for inlined functions + self.traced_code: list[CodeType] = [] + self.cudagraph_annotation: Any = None + + def clear(self) -> None: + # Look at the note in output_graph.py in function `save_global_state` + # for the context on clearing global context. + self.global_context.global_state = {} + self.previously_inlined_functions.clear() + self.previously_cleaned_instructions.clear() + self.inlined_code_cache.clear() + + @staticmethod + @contextmanager + def patch(**kwargs: Any) -> Generator[None, None, None]: + prior = {} + ctx = TracingContext.get() + + for key in kwargs: + # KeyError on invalid entry + prior[key] = getattr(ctx, key) + for key, val in kwargs.items(): + setattr(ctx, key, val) + try: + yield + finally: + for key, val in prior.items(): + setattr(ctx, key, val) + + @staticmethod + def extract_stack() -> traceback.StackSummary: + self = TracingContext.try_get() + if self is None: + return traceback.StackSummary() + stack = self.frame_summary_stack + if self.loc_in_frame is not None: + stack = stack + [self._populate_loc_in_frame_summary()] + return traceback.StackSummary.from_list(stack) + + def _populate_loc_in_frame_summary(self) -> traceback.FrameSummary: + if self.loc_in_frame is None: + raise AssertionError("loc_in_frame must not be None") + filename, lineno, frame_name = self.loc_in_frame + # colno/end_colno kwargs were added to FrameSummary in 3.11 + kwargs: dict[str, Any] = {} + if sys.version_info >= (3, 11) and self.loc_in_frame_positions is not None: + kwargs["colno"] = self.loc_in_frame_positions.col_offset + kwargs["end_colno"] = self.loc_in_frame_positions.end_col_offset + return traceback.FrameSummary( + filename, + lineno, + frame_name, + lookup_line=False, + **kwargs, + ) + + # Call this when you want to call into some code that isn't necessarily + # associated with the current frame state + @staticmethod + @contextlib.contextmanager + def clear_frame() -> Generator[None, None, None]: + tc = TracingContext.get() + with ( + unittest.mock.patch.object(tc, "frame_summary_stack", []), + unittest.mock.patch.object(tc, "loc_in_frame", None), + unittest.mock.patch.object(tc, "loc_in_frame_positions", None), + ): + try: + yield + except Exception as e: + # Prevent real_stack from getting attached + # + # The invariant is that if an Exception as real_stack, we've + # appropriately attached a user stack and we no longer need to + # attach anything. Because we cannot conveniently interpose + # when an exception is thrown, we instead interpose everywhere + # we set what the user stack is set (using the context + # manager). However, our compiler stack does "tail calls" + # (when it calls into user compiler), at which point the + # parent exception frames would incorrectly attach an + # incorrect frame. + # + # However, if, somehow, someone raised an exception with this + # scope that had a stack (for example, because they are + # restoring the user stack state appropriately as they process + # node by node), we should respect it. Thus, we cannot + # unconditionally set None. + if not hasattr(e, "real_stack"): + e.real_stack = None # type: ignore[attr-defined] + raise + + @staticmethod + @contextlib.contextmanager + def current_frame( + frame_summary: traceback.FrameSummary | None, + ) -> Generator[None, None, None]: + # frame_summary can be None to solely take advantage of real_stack + # attachment to thrown exceptions + tc = TracingContext.get() + if frame_summary is not None: + tc.frame_summary_stack.append(frame_summary) + old = tc.loc_in_frame + old_positions = tc.loc_in_frame_positions + tc.loc_in_frame = None + tc.loc_in_frame_positions = None + try: + yield + except Exception as e: + if not hasattr(e, "real_stack"): + e.real_stack = tc.extract_stack() # type: ignore[attr-defined] + raise + finally: + if frame_summary is not None: + tc.frame_summary_stack.pop() + tc.loc_in_frame = old + tc.loc_in_frame_positions = old_positions + + @staticmethod + @contextlib.contextmanager + def report_output_strides() -> Generator[ + list[tuple[int, ...] | None] | None, None, None + ]: + tc = TracingContext.try_get() + if tc is None: + yield None + return + old_output_strides = tc.output_strides + tc.output_strides = [] + try: + yield tc.output_strides + finally: + tc.output_strides = old_output_strides + + @staticmethod + def set_current_loc( + filename: str, + lineno: int, + frame_name: str, + positions: dis.Positions | None = None, + ) -> None: + # Save the current location in the frame. Lazily generate the + # framesummary. + tc = TracingContext.get() + tc.loc_in_frame = (filename, lineno, frame_name) + tc.loc_in_frame_positions = positions + + @staticmethod + def get_traced_code() -> list[CodeType] | None: + tc = TracingContext.try_get() + if tc is None: + return None + return tc.traced_code + + +@contextmanager +def compile_context( + context: CompileContext | None, +) -> Generator[CompileContext | None, None, None]: + old_context = getattr(_TLS, "compile_context", None) + _TLS.compile_context = context + try: + yield context + finally: + _TLS.compile_context = old_context + + +@contextmanager +def tracing( + context: TracingContext | None, +) -> Generator[TracingContext | None, None, None]: + """ + This function installs the passed in tracing context as a dynamic scoped + global variable. + + Calls to TracingContext.get() while not under a `with tracing()` context + will return None. + """ + old_context = getattr(_TLS, "tracing_context", None) + _TLS.tracing_context = context + try: + yield context + except Exception as e: + if not hasattr(e, "real_stack") and context is not None: + e.real_stack = context.extract_stack() # type: ignore[attr-defined] + raise + finally: + if ( + context is not None + and context.fake_mode is not None + and context.fake_mode.shape_env is not None + ): + context.fake_mode.shape_env.cleanup() + _TLS.tracing_context = old_context + + +@overload +def dataclass_with_cached_hash(cls: type[T], **kwargs: Any) -> type[T]: ... + + +@overload +def dataclass_with_cached_hash( + cls: None = None, **kwargs: Any +) -> Callable[[type[T]], type[T]]: ... + + +@dataclass_transform() +def dataclass_with_cached_hash( + cls: type[T] | None = None, **kwargs: Any +) -> type[T] | Callable[[type[T]], type[T]]: + def wrap(cls_inner: type[T]) -> type[T]: + new_cls = dataclasses.dataclass(cls_inner, **kwargs) + old_hash = cls_inner.__hash__ + + def __hash__(self) -> int: + if not hasattr(self, "_hash"): + object.__setattr__(self, "_hash", old_hash(self)) + return self._hash + + def __reduce__(self): + # Exclude _hash from pickling to ensure deterministic cache keys. + # The _hash is a cached value that can be nondeterministically computed + # (e.g., based on id() of objects), so it should not affect pickling. + fields = dataclasses.fields(self) + field_values = tuple(getattr(self, f.name) for f in fields if f.init) + return (self.__class__, field_values) + + new_cls.__hash__ = __hash__ + new_cls.__reduce__ = __reduce__ + return new_cls # type: ignore[return-value] + + if cls is None: + return wrap + + return wrap(cls) + + +# Subclasses can be found in torch/_dynamo/source.py +# TODO(voz): Consider a toplevel torch/_source.py +@dataclass_with_cached_hash(frozen=True) +class Source: + def is_dict_key(self) -> bool: + return False + + def is_ephemeral(self) -> bool: + return False + + def reconstruct(self, codegen: PyCodegen) -> None: + raise NotImplementedError + + def reconstruct_pycode(self, codegen: PyCodegen) -> str: + """ + Reconstructs the source into a string of Python code. This method should + be eventually implemented for all subclasses of Source to achieve full + coverage of python wrapper code generation. + """ + raise NotImplementedError + + @functools.cached_property + def guard_source(self) -> GuardSource: + raise NotImplementedError + + @property + def _name_template(self) -> str: + """ + A template for the name of the source. Used to prevent code duplication between + `name` and `get_value`. + + For non-ChainedSources, `name` and `get_value` use the returned string directly. + + For ChainedSources, `name` and `get_value` expect the return to be a format string + with `{0}` present - `name` and `get_value` will apply different values to this function's + returned format string. + """ + raise NotImplementedError + + @functools.cached_property + def name(self) -> str: + return self._name_template + + def get_value( + self, + globals: dict[str, Any], + locals: dict[str, Any], + cache: dict[Source, Any], + ) -> Any: + if self in cache: + return cache[self] + value = eval(self._name_template, globals, locals) + cache[self] = value + return value + + def make_guard(self, fn: Callable[..., Any]) -> Guard: + if self.guard_source is GuardSource.CONSTANT: + raise NotImplementedError + return Guard(self, fn) + + def is_specialized_nn_module(self) -> bool: + return self.guard_source.is_specialized_nn_module() + + def subguards_allowed(self) -> bool: + """True if you can guard on attributes of this""" + return self.guard_source != GuardSource.SYNTHETIC_LOCAL + + def clone(self, transform_fn: Callable[[Source], Source] | None = None) -> Source: + # Frozen dataclass, so returning self is effectively a clone. + # Subclasses with mutable state should override. + if transform_fn is not None: + return transform_fn(self) + return self + + +# Subclasses can be found in torch/_dynamo/source.py +@dataclass_with_cached_hash(frozen=True) +class ChainedSource(Source): + base: Source + + def is_dict_key(self) -> bool: + # Recurse until you either hit a ConstDictKey or a Source + return self.base.is_dict_key() + + def is_ephemeral(self) -> bool: + return self.base.is_ephemeral() + + @functools.cached_property + def guard_source(self) -> GuardSource: + return self.base.guard_source + + def get_base(self) -> Source: + current: Source = self + while isinstance(current, ChainedSource): + current = current.base + return current + + @functools.cached_property + def name(self) -> str: + return self._name_template.format(self.base.name) + + def get_value( + self, + globals: dict[str, Any], + locals: dict[str, Any], + cache: dict[Source, Any], + ) -> Any: + if self in cache: + return cache[self] + tmpvar = "tmp" + counter = 0 + while tmpvar in locals: + tmpvar = f"tmp{counter}" + counter += 1 + locals[tmpvar] = self.base.get_value(globals, locals, cache) + value = eval(self._name_template.format(tmpvar), globals, locals) + del locals[tmpvar] + cache[self] = value + return value + + def clone(self, transform_fn: Callable[[Source], Source] | None = None) -> Source: + cloned_fields: dict[str, Any] = {"base": self.base.clone(transform_fn)} + for f in dataclasses.fields(self): + if f.name == "base": + continue + val = getattr(self, f.name) + if isinstance(val, Source): + cloned_fields[f.name] = val.clone(transform_fn) + result = dataclasses.replace(self, **cloned_fields) + if transform_fn is not None: + result = transform_fn(result) + return result + + +def detect_fake_mode(inputs: Any = None) -> FakeTensorMode | None: + """ + Attempts to "detect" what the current fake mode is. If there is one ambiently + available from TracingContext, we preferentially use that. Otherwise, we + heuristically detect the fake mode via the following sources, in order of + priority: + + - Currently active fake mode on stack + - Fake mode associated with passed in tensors (inputs does not + have to be flattened) + """ + from torch._subclasses.fake_tensor import ( + FakeTensor, + FakeTensorMode, + get_plain_tensors, + is_fake_tensor, + maybe_get_fake_mode, + ) + + # If TracingContext has a fake_mode, use it authoritatively. + # This is the case when Dynamo is driving compilation - any fake tensors + # from other modes in the inputs will be refakified by the caller. + if context := TracingContext.try_get(): + fake_mode = context.fake_mode + if fake_mode is not None: + return fake_mode + + fake_modes = [] + + from torch.utils._python_dispatch import _get_current_dispatch_mode_stack + + for i, m in enumerate(reversed(_get_current_dispatch_mode_stack())): + if isinstance(m, FakeTensorMode): + fake_modes.append((m, "active fake mode", i)) + + flat_inputs = pytree.tree_leaves(inputs) + for i, flat_input in enumerate(flat_inputs): + if is_fake_tensor(flat_input): + fake_modes.append((maybe_get_fake_mode(flat_input), "fake tensor input", i)) + if is_traceable_wrapper_subclass(flat_input): + out: list[torch.Tensor | int | torch.SymInt] = [] + get_plain_tensors(flat_input, out=out) # type: ignore[arg-type] + fake_tensors: list[FakeTensor] = [ + x + for x in out + if isinstance(x, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR + ] + fake_modes.extend( + [ + (maybe_get_fake_mode(tensor), f"subclass input {i}", ix) + for ix, tensor in enumerate(fake_tensors) + ] + ) + + if fake_modes: + fake_mode, desc1, i1 = fake_modes[0] + for m, desc2, i2 in fake_modes[1:]: + if fake_mode is not m: + raise AssertionError( + f"fake mode ({fake_mode}) from {desc1} {i1} doesn't match mode ({m}) from {desc2} {i2}\n\n" + f"fake mode from {desc1} {i1} allocated at:\n{fake_mode.stack}\n" + f"fake mode from {desc2} {i2} allocated at:\n{m.stack}" + ) + + return fake_mode + else: + return None + + +def active_fake_mode() -> FakeTensorMode | None: + """ + Inspects the dispatch mode stack for an active fake mode and returns it. + Returns None if no fake mode is active. + """ + from torch._subclasses.fake_tensor import FakeTensorMode + from torch.utils._python_dispatch import _get_current_dispatch_mode_stack + + for _, m in enumerate(reversed(_get_current_dispatch_mode_stack())): + if isinstance(m, FakeTensorMode): + return m + + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__init__.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea54032864d872aa9ebb815d9abd24b2bd7a1a93 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__init__.py @@ -0,0 +1,91 @@ +from torch._higher_order_ops._invoke_quant import ( + invoke_quant, + invoke_quant_packed, + InvokeQuant, +) +from torch._higher_order_ops.aoti_call_delegate import aoti_call_delegate +from torch._higher_order_ops.associative_scan import associative_scan +from torch._higher_order_ops.auto_functionalize import ( + auto_functionalized, + auto_functionalized_v2, +) +from torch._higher_order_ops.base_hop import BaseHOP +from torch._higher_order_ops.cond import cond +from torch._higher_order_ops.effects import with_effects +from torch._higher_order_ops.executorch_call_delegate import executorch_call_delegate +from torch._higher_order_ops.flat_apply import flat_apply +from torch._higher_order_ops.flex_attention import ( + flex_attention, + flex_attention_backward, +) +from torch._higher_order_ops.flex_gemm import flex_gemm +from torch._higher_order_ops.foreach_map import _foreach_map, foreach_map +from torch._higher_order_ops.hints_wrap import hints_wrapper +from torch._higher_order_ops.inline_asm_elementwise import inline_asm_elementwise +from torch._higher_order_ops.invoke_leaf_function import invoke_leaf_function +from torch._higher_order_ops.invoke_subgraph import invoke_subgraph +from torch._higher_order_ops.local_map import local_map_hop +from torch._higher_order_ops.map import map +from torch._higher_order_ops.out_dtype import out_dtype +from torch._higher_order_ops.print import print +from torch._higher_order_ops.run_const_graph import run_const_graph +from torch._higher_order_ops.scan import scan +from torch._higher_order_ops.strict_mode import strict_mode +from torch._higher_order_ops.switch import switch +from torch._higher_order_ops.torchbind import call_torchbind +from torch._higher_order_ops.while_loop import ( + while_loop, + while_loop_stack_output_op as while_loop_stack_output, +) +from torch._higher_order_ops.wrap import ( + dynamo_bypassing_wrapper, + inductor_compiled_code, + tag_activation_checkpoint, + wrap_activation_checkpoint, + wrap_with_autocast, + wrap_with_set_grad_enabled, +) + + +__all__ = [ + "cond", + "switch", + "while_loop", + "invoke_subgraph", + "scan", + "map", + "flex_attention", + "flex_attention_backward", + "hints_wrapper", + "BaseHOP", + "flat_apply", + "foreach_map", + "_foreach_map", + "flex_gemm", + "with_effects", + "tag_activation_checkpoint", + "auto_functionalized", + "auto_functionalized_v2", + "associative_scan", + "out_dtype", + "executorch_call_delegate", + "call_torchbind", + "run_const_graph", + "InvokeQuant", + "invoke_leaf_function", + "invoke_quant", + "invoke_quant_packed", + "wrap_with_set_grad_enabled", + "wrap_with_autocast", + "wrap_activation_checkpoint", + "dynamo_bypassing_wrapper", + "strict_mode", + "aoti_call_delegate", + "map", + "while_loop_stack_output", + "local_map_hop", + "print", + "inductor_compiled_code", + "inline_asm_elementwise", + "register_hook", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd3623e46bcab59ca58860ca376a3a8fbfbeb8d4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/_invoke_quant.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/_invoke_quant.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8411c8ffa5248d490dd0e33b7eb1f8a365454f42 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/_invoke_quant.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/aoti_call_delegate.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/aoti_call_delegate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad5dcc63d409013601304aeca7abad2c315e2ac2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/aoti_call_delegate.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/associative_scan.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/associative_scan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40257a4db79aae24d059709c24d2f884b58d19fa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/associative_scan.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/auto_functionalize.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/auto_functionalize.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..477e47d85877d7fc2671bc5683b2e2af9f365bf0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/auto_functionalize.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/base_hop.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/base_hop.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3107c2b55996b4bfe6aed1b048eca39d9234e565 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/base_hop.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cond.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cond.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60c73e959101670dcb569272bced26e038db8256 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cond.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cudagraph_conditional_nodes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cudagraph_conditional_nodes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68f49ce4fba92da14bb5e1d052d75faf542e046c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/cudagraph_conditional_nodes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/effects.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/effects.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1c7bba30ebbcdf4943934ea2f4ecf9d8b0da666 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/effects.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/executorch_call_delegate.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/executorch_call_delegate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50386c56f76aac05c80254dcf6e3e627cb7e1b29 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/executorch_call_delegate.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flat_apply.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flat_apply.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baf9c89fc1aca1a79309a4261d7daa14035119e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flat_apply.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_attention.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b2650530e2b350d700ab81c7ac1f6ceb5f8e0d0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_attention.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_gemm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_gemm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8320701a0baae4eeaddbd4393bfe1804c8bbf70 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/flex_gemm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/foreach_map.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/foreach_map.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7a6b47852b3585a7403ddc4463c6c57527622f9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/foreach_map.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/hints_wrap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/hints_wrap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..130ebb82ec2d6ed607b2aae1ceb17182fd363693 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/hints_wrap.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/inline_asm_elementwise.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/inline_asm_elementwise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8abb125e930026a620d216549024a6c3d512476e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/inline_asm_elementwise.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_leaf_function.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_leaf_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08682594cc0e1211576543a6763f9c2e743d6a74 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_leaf_function.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_subgraph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_subgraph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd8fece28d69b4d1c93438572689d802099735ab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/invoke_subgraph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/local_map.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/local_map.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1647ceeb0b5837e98da8f8ac86187080f5fd9fb9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/local_map.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/map.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/map.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1df8b6d5f497a16cbdbe9de01f21d0e432812f55 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/map.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/out_dtype.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/out_dtype.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e6290a74cead3c122717f5cae3b0db92f555249 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/out_dtype.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/partitioner.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/partitioner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07675017cb51abae31c852864d78d5e431f5d8d0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/partitioner.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/print.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/print.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a31bce3e25111adb82140e9d8a9dc50fc34c47b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/print.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/register_hook.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/register_hook.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cc2d86ad4791ebcafddbaf6ccc1dfd914d3bc9b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/register_hook.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/run_const_graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/run_const_graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53a6205dc583dd90f298b34a87d3a97dfe1d08d6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/run_const_graph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/scan.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/scan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4feca4e3856170116670241d9614c55663299320 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/scan.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/schema.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c54cd5cb82a592ab6dc5a3484202c48b88cc7a8f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/schema.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/strict_mode.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/strict_mode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07a5ec8a7eee1efb4296362e47b7b08a0f9c45cd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/strict_mode.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/switch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/switch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60c9d82a7287e3b86567118902bad47c92e2c2b2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/switch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/torchbind.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/torchbind.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..694d87ff178a98987c74e6111bb975b96f53dd44 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/torchbind.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cb28f87f613032691930eb03cf8ed3ca652c373 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:033b54c9fbf4a9cd1d4d8a86af580f0fa486e638cd804d6c95e3e4fa04d4e6f7 +size 100564 diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4179cfbff8358e2d5f33c8a9eec0dc55d70cc3c4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/while_loop.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/while_loop.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5677077a1299a245ab7cb79912d5acbb02b065d9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/while_loop.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/wrap.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/wrap.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b3bd39b83b1f2eb03d36bf5fde40f6a01beb6c0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/__pycache__/wrap.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/_invoke_quant.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/_invoke_quant.py new file mode 100644 index 0000000000000000000000000000000000000000..4e125e68fa4f4e0b19af801301d9d04e7d1d0e41 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/_invoke_quant.py @@ -0,0 +1,61 @@ +# mypy: allow-untyped-defs +# need to fix prim_hop_base type annotations first + +import dataclasses + +import torch +from torch._higher_order_ops.base_hop import BaseHOP, FunctionWithNoFreeVars + + +class InvokeQuantTracer(BaseHOP): + def __init__(self) -> None: + super().__init__("invoke_quant_packed") + + def __call__(self, subgraph, *operands, scheme=None, quant_options=None): + subgraph = FunctionWithNoFreeVars(subgraph) + return super().__call__( + subgraph, *operands, scheme=scheme, quant_options=quant_options + ) + + +invoke_quant_packed = InvokeQuantTracer() + + +class InvokeQuantUnpacked(BaseHOP): + def __init__(self) -> None: + super().__init__("invoke_quant") + + +invoke_quant = InvokeQuantUnpacked() + + +@dataclasses.dataclass(frozen=True, repr=True) +class InvokeQuant: + """ + Invoke a quantization function that will be preserved as a single operator. Preservation + as a single operator aids in pattern matching and custom lowerings. + + The operation appears as: + torch.ops.higher_order.invoke_quant(subgraph, *args, scheme=scheme) + + Args: + codegen_low_precision: Use observed subgraph dtypes for codegen instead of + upcasting to fp32. Can improve performance for prologue fusion but + requires careful testing of numerics. + """ + + codegen_low_precision: bool = True + + def __call__( + self, + *args, + scheme: str | None = None, + **kwargs, + ): + if not torch.compiler.is_compiling(): + return args[0](*args[1:], **kwargs) + + if scheme is not None: + kwargs["scheme"] = scheme + + return invoke_quant_packed(*args, **kwargs, quant_options=self) # type: ignore[call-arg] diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/aoti_call_delegate.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/aoti_call_delegate.py new file mode 100644 index 0000000000000000000000000000000000000000..87f34284047f039f79ea7f3c3df05525790d8fe6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/aoti_call_delegate.py @@ -0,0 +1,164 @@ +# mypy: allow-untyped-defs + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +import torch +import torch.utils._pytree as pytree +from torch._higher_order_ops.utils import register_fake +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import is_fake_tensor +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +AOTI_LOWERED_MODULE = "AOTInductorEPModule/AOTInductorRunnerWrapper" + + +class AOTICallDelegate(HigherOrderOperator): + """aoti_call_delegate is a HOP for calling AOTInductor lowered submodule in ExportedProgram. + + It has the following signature: + aoti_call_delegate( + lowered_module: Union[AOTInductorEPModule, AOTInductorRunnerWrapper] + original_gm:fx.GraphModule, + weight_args: List[Tensor], + input_args: List[Tensor], + ) -> outputs: List[Tensor] + + where, + - lowered_module is the AOTInductor lowered submodule, backed by compiled .so file, supporting real tensor inputs + - original_gm is the stateless version of the original GraphModule before lowering, allowing FakeTensor propagation + - weight_args is the list of weights in original GraphModule, including parameters and buffers + - input_args is the list of flatten inputs + """ + + def __init__(self) -> None: + super().__init__("aoti_call_delegate") + + def __call__( + self, + lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type] + original_gm: torch.fx.GraphModule, + weight_args: list[torch.Tensor], + input_args: list[torch.Tensor], + ) -> list[torch.Tensor]: + # pyrefly: ignore [missing-attribute] + return super().__call__(lowered_module, original_gm, weight_args, input_args) + + +aoti_call_delegate = AOTICallDelegate() +aoti_call_delegate.fallthrough(torch._C.DispatchKey.PythonDispatcher) +aoti_call_delegate.fallthrough(torch._C.DispatchKey.PythonTLSSnapshot) +aoti_call_delegate.fallthrough(torch._C.DispatchKey.ADInplaceOrView) +aoti_call_delegate.fallthrough(torch._C.DispatchKey.AutocastCPU) + + +@aoti_call_delegate.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd) +def call_delegate_cpu( + lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type] + original_gm: torch.fx.GraphModule, + weight_args: list[torch.Tensor], + input_args: list[torch.Tensor], +) -> list[torch.Tensor]: + # FX creates this immutable_dict/list concept. Get rid of this. + map_types: dict[type, type] = { + torch.fx.immutable_collections.immutable_dict: dict, + torch.fx.immutable_collections.immutable_list: list, + } + new_args = pytree.tree_map_only( + tuple(map_types.keys()), + lambda a: map_types[type(a)](a), + weight_args + input_args, + lambda a: isinstance(a, tuple(map_types.keys())), + ) + has_fake_args = any(is_fake_tensor(arg) for arg in new_args) + if has_fake_args: + # use stateless original_gm for tracing with fake tensors + fake_out = original_gm(*new_args) + return fake_out + else: + # use AOTI Runner for real tensors + new_input_args = new_args[len(weight_args) :] + if type(lowered_module).__name__ == "AOTInductorRunnerWrapper": + return lowered_module(*new_input_args) # type: ignore[misc] + elif type(lowered_module).__name__ == "AOTInductorEPModule": + return lowered_module(new_input_args) # type: ignore[misc] + else: + raise RuntimeError( + f"Unexpected lowered_module type: {type(lowered_module)}." + ) + + +def trace_aoti_call_delegate( + proxy_mode, func_overload, lowered_module, original_gm, weight_args, input_args +): + proxy_mode.tracer.root.register_module("lowered_module", lowered_module) + proxy_mode.tracer.root.register_module("original_gm", original_gm) + + node_args = (lowered_module, original_gm, weight_args, input_args) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {}, name="aoti_call_delegate" + ) + with disable_proxy_modes_tracing(): + out = call_delegate_cpu(lowered_module, original_gm, weight_args, input_args) + + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@aoti_call_delegate.py_impl(ProxyTorchDispatchMode) +def call_delegate_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, + lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type] + original_gm: torch.fx.GraphModule, + weight_args: list[torch.Tensor], + input_args: list[torch.Tensor], +): + res = trace_aoti_call_delegate( + mode, aoti_call_delegate, lowered_module, original_gm, weight_args, input_args + ) + return res + + +@register_fake(aoti_call_delegate, skip_cache=True) +def call_delegate_fake_tensor_mode( + lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type] + original_gm: torch.fx.GraphModule, + weight_args: list[torch.Tensor], + input_args: list[torch.Tensor], +) -> list[torch.Tensor]: + return call_delegate_cpu(lowered_module, original_gm, weight_args, input_args) + + +@aoti_call_delegate.py_functionalize_impl +def call_delegate_functionalize( + ctx, + lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type] + original_gm: torch.fx.GraphModule, + weight_args: list[torch.Tensor], + input_args: list[torch.Tensor], +): + unwrapped_weight_args = tuple( + ctx.unwrap_tensors(weight_arg) for weight_arg in weight_args + ) + unwrapped_input_args = tuple( + ctx.unwrap_tensors(input_arg) for input_arg in input_args + ) + with ctx.redispatch_to_next(): + res = aoti_call_delegate( + lowered_module, + original_gm, + unwrapped_weight_args, # type: ignore[arg-type] + unwrapped_input_args, # type: ignore[arg-type] + ) + return ctx.wrap_tensors(res) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/associative_scan.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/associative_scan.py new file mode 100644 index 0000000000000000000000000000000000000000..79576095ef2a3531a6f0e037d1a36832f3b0df94 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/associative_scan.py @@ -0,0 +1,928 @@ +# mypy: allow-untyped-defs +import functools +import itertools +from collections.abc import Callable +from typing import Any + +import torch +import torch._prims_common as utils +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + _maybe_compile_and_run_fn, + _maybe_run_with_interpreter, + check_input_alias_and_mutation_return_outputs, + check_meta_consistency, + create_bw_fn, + first_slice_copy, + first_slice_copy_with_grad, + materialize_as_graph, + reenter_make_fx, + register_fake, + save_values_for_backward, + saved_values, + split_into_chunks, + unique_graph_id, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +aten = torch._ops.ops.aten + + +def wrap_combine_fn_flat(*args, combine_fn, spec, num_leaves): + if len(args) != 2 * num_leaves: + raise AssertionError( + f"Combine_fn received wrong number of arguments, expected {2 * num_leaves}, but got {len(args)}" + ) + lhs = pytree.tree_unflatten(args[:num_leaves], spec) + rhs = pytree.tree_unflatten(args[num_leaves:], spec) + return combine_fn(lhs, rhs) + + +def _interleave(a, b, dim=0): + # https://stackoverflow.com/questions/60869537/how-can-i-interleave-5-pytorch-tensors + if b_trunc := (a.shape[dim] == b.shape[dim] + 1): + pad = ( + [0] * ((b.ndim - dim - 1) * 2 + 1) + + [1] + + [0] * (b.ndim * 2 - ((b.ndim - dim - 1) * 2 + 2)) + ) + b = torch.nn.functional.pad(b, pad) + + stacked = torch.stack([a, b], dim=dim + 1) + interleaved = torch.flatten(stacked, start_dim=dim, end_dim=dim + 1) + # pyrefly: ignore [unbound-name] + if b_trunc: + # TODO: find torch alternative for slice_along dim for torch.jit.script to work + interleaved = aten.slice(interleaved, dim, 0, b.shape[dim] + a.shape[dim] - 1) + return interleaved + + +def safe_map(f, *args): + args = list(map(list, args)) + n = len(args[0]) + for arg in args[1:]: + if len(arg) != n: + raise ValueError("length mismatch: {list(map(len, args))}") + + def nf(a): + return f(*a) + + return list(map(nf, zip(*args))) + + +class AssociativeScanOp(HigherOrderOperator): + def __init__(self): + super().__init__("associative_scan") + + def __call__(self, combine_fn, xs, additional_inputs): + # There is currently an issue that the ScanOp is sometimes called with + # the additional_inputs being a list. See https://github.com/pytorch/pytorch/issues/145785 + # Once this issue is resolved, the assertion should only allow tuples + # and the tuple cast should be removed + if not isinstance(additional_inputs, (tuple, list)): + raise AssertionError( + f"additional_inputs must be a tuple or list, got {type(additional_inputs)}" + ) + additional_inputs = ( + tuple(additional_inputs) + if isinstance(additional_inputs, list) + else additional_inputs + ) + validate_subgraph_args_types(additional_inputs) + # pyrefly: ignore [missing-attribute] + return super().__call__(combine_fn, xs, additional_inputs) + + # pyrefly: ignore [bad-override] + def gen_schema(self, combine_fn, xs, additional_inputs): + from torch._higher_order_ops.schema import HopSchemaGenerator + + # For associative scan, we need two copies of xs for the combine function + # The combine function takes two elements and returns one element + xs_slice1 = [first_slice_copy(x) for x in xs] + xs_slice2 = [first_slice_copy(x) for x in xs] + all_inputs = tuple(xs_slice1 + xs_slice2 + list(additional_inputs)) + + combine_gm: torch.fx.GraphModule = materialize_as_graph(combine_fn, all_inputs) + ( + _, + _, + _, + mutated_inputs, + outputs, + ) = check_input_alias_and_mutation_return_outputs(combine_gm) + if len(mutated_inputs) > 0: + raise RuntimeError( + "For associative_scan, combine_fn cannot have in-place mutations but found " + f"{mutated_inputs}-th inputs are mutated." + ) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("combine_fn", combine_gm) + + for idx, x in enumerate(xs): + schema_gen.add_arg(f"xs{idx}", x) + + for idx, arg in enumerate(additional_inputs): + schema_gen.add_arg( + f"additional_input{idx}", + arg, + ) + + for out in outputs: + schema_gen.add_output(out) + + schema_gen.add_schema_tree_spec(combine_fn, xs, additional_inputs) + return schema_gen.gen_schema() + + +associative_scan_op = AssociativeScanOp() + + +def associative_scan( + combine_fn: Callable[[pytree.PyTree, pytree.PyTree], pytree.PyTree], + xs: pytree.PyTree, + dim: int, + reverse: bool = False, + combine_mode: str = "pointwise", +) -> torch.Tensor: + r""" + Performs an inclusive scan with an associative combine function. + + .. warning:: + + ``torch.associative_scan`` is a prototype feature in PyTorch. It currently + does not support autograd and you may run into miscompiles. + Read more about feature classification at: + https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + With ``combine_mode="pointwise"``, efficient execution requires runtime code + generation via ``torch.compile``, and codegen is only supported on backends + with scan support (currently CUDA and XPU). On other devices the operator + still runs eagerly via the generic fallback. + + Args: + combine_fn (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``, + or if input is a pytree ``(pytree, pytree) -> pytree``. + This function must be pure, i.e., no lifted arguments are supported at the moment, + satisfy the associative property and have no side-effects. + xs (torch.Tensor): The input tensor, or nested pytree of tensors. + dim (int): the dimension to scan over + reverse (bool): A boolean stating if the scan should be reversed with respect to ``dim``, default ``False``. + combine_mode (str): A string indicating whether the ``combine_fn`` is ``pointwise`` or ``generic``, default ``pointwise``. + If ``combine_mode=pointwise``, ``combine_fn`` must be pure and may only contain pointwise + operations; under ``torch.compile`` ``xs`` must be on a backend with scan codegen support + (CUDA or XPU), otherwise the generic fallback is used. + In all other cases ``combine_mode=generic`` should be used. + Note: ``combine_mode=pointwise`` is more efficient than ``combine_mode=generic``. + + Returns: + A pytree of the same structure and shape as ``xs``. If the scan dimension has size 0, + the output mirrors the (empty) input unchanged. The gradient with respect to ``xs`` + is also empty (size 0 along ``dim``), since there are no elements to differentiate through. + + Example:: + + def add(x: torch.Tensor, y: torch.Tensor): + return x + y + + + cumsum = associative_scan(add, x, dim) + + """ + # TODO: Support lifted arguments in inductor for associative_scan + # TODO: Support autograd for cases with lifted arguments for combine_mode=pointwise + + # The reason we flatten xs before calling into dynamo is that + # we want to create a consistent input ordering for combine_fn + # and we also want to the input ordering matches the output ordering. + leaves_xs_orig, spec_xs = pytree.tree_flatten(xs) + + def _validate_input(cfn, lxs, d, r, cm): + # Basic arguments check + if not callable(cfn): + raise ValueError(f"Combine_fn must be a callable, but got {cfn}") + if not isinstance(d, int): + raise ValueError("Dim must be an int, but got " + str(type(d))) + if not isinstance(r, bool): + raise RuntimeError("Reverse must be a bool, but got " + str(type(r))) + if cm not in ["pointwise", "generic"]: + raise ValueError( + f"Combine_mode must either 'pointwise' or 'generic', but got {cm}" + ) + + # Checks for xs + if len(lxs) == 0: + raise ValueError("Expected at least 1 xs leaf") + if any(not isinstance(x, torch.Tensor) for x in lxs): + raise ValueError("xs leaves must be a Tensor") + if any(x.is_sparse for x in lxs): + raise ValueError( + "xs leaves must dense Tensors, consider using `to_dense()`" + ) + if any(x.ndim <= d for x in lxs): + raise ValueError("All xs leaves must have at least 'dim + 1' dimensions") + + ndim = leaves_xs_orig[0].ndim + dim = utils.canonicalize_dim(ndim, dim) + + _validate_input(combine_fn, leaves_xs_orig, dim, reverse, combine_mode) + + # Move scan dim to 0 and always perform scan on dim 0 + leaves_xs = [torch.movedim(elem, dim, 0) for elem in leaves_xs_orig] + + if reverse: + leaves_xs = [torch.flip(elem, [0]) for elem in leaves_xs] + + if combine_mode == "generic": + # The generic_associative_scan implementation calls the combine_fn with a `batch` along the scan dimension + # For example, consider: + # def add(x: torch.Tensor, y: torch.Tensor): + # return x + y + # leaves = torch.tensor([[0.0, 1.0, 2.0, 3.0] + # [0.0, 1.0, 2.0, 3.0]]) + # which has shape 2 x 4; + # dim = 1; + # In the first iteration of `_scan` the combine_fn gets invoked with + # combine_fn([torch.tensor([[0.0, 2.0], + # [0.0, 2.0]])], + # [torch.tensor([[1.0, 3.0], + # [1.0, 3.0]])]) + # The arguments are of shape 2 x 2, but can be evaluated in parallel along the scan dimension. + combine_fn = functools.partial( + wrap_combine_fn_flat, + combine_fn=torch.vmap( + combine_fn, + in_dims=( + pytree.tree_unflatten([0] * len(leaves_xs), spec_xs), + pytree.tree_unflatten([0] * len(leaves_xs), spec_xs), + ), + out_dims=0, + ), + spec=spec_xs, + num_leaves=len(leaves_xs), + ) + out = generic_associative_scan(combine_fn, leaves_xs, additional_inputs=()) + out = pytree.tree_unflatten(out, spec_xs) + else: + combine_fn = functools.partial( + wrap_combine_fn_flat, + combine_fn=combine_fn, + spec=spec_xs, + num_leaves=len(leaves_xs), + ) + + def run_flattened_associative_scan(combine_fn, leaves_xs): + return associative_scan_op(combine_fn, leaves_xs, additional_inputs=()) + + out = _maybe_compile_and_run_fn( + run_flattened_associative_scan, + combine_fn, + leaves_xs, + ) + + if reverse: + out = pytree.tree_map(lambda elem: elem.flip([0]), out) + + out = pytree.tree_map(lambda elem: torch.movedim(elem, 0, dim), out) + + return out + + +def generic_associative_scan(operator, leaves, dim=0, additional_inputs=()): + r""" + This function performs the associative_scan operation. + The algorithm works by recursively collecting neighbours of ``leaves`` and subsequently + applying the ``operator`` on all pairs in parallel along ``dim``. + The results of the recursive calls are later combined. + + Args: + operator (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``, + or if input is a pytree ``(pytree, pytree) -> pytree``. + This function must be pure, pointwise, and satisfy the associative property. + leaves (torch.Tensor): A list of torch.Tensors converted from the pytree of + ``xs`` provided to ``associative_scan``. + All inputs are expected to have the same shape. + dim (int): the dimension to scan over + additional_inputs (Tuple of tensors): A tuple of lifted parameters from the global scope. + This parameter will be populated internally. + + Example:: + + def add(x: torch.Tensor, y: torch.Tensor): + return x + y + + leaves = torch.tensor([0.0, 1.0, 2.0, 3.0]) + + First iteration of _scan -> + # odd_elems -> apply operator on all neighbours + # odd_elems = operator([torch.tensor([0.0, 2.0])], + # [torch.tensor([1.0, 3.0])]) + odd_elems = torch.tensor([1.0, 5.0]) + Second iteration of _scan -> + # odd_elems = operator([torch.tensor([1.0])], + # [torch.tensor([5.0])]) + odd_elems = torch.tensor([6.0]) + # even_elems -> apply operator on all odd_elems and + # every second element of ``elems``, starting from the second element. + # even_elems is expanded with the first element of ``elems`` + even_elems = [1.0] + # Merges odd_elems and even_elems + res = torch.tensor([1.0, 6.0]) + # even_elems -> apply operator on all odd_elems and + # every second element of ``elems``, starting from the second element. + # even_elems is expanded with the first element of ``elems`` + even_elems = [0.0, 3.0] + # Merges odd_elems and even_elems + res = torch.tensor([0.0, 1.0, 3.0, 6.0]) + + """ + + def call_operator(*args): + return pytree.tree_leaves(operator(*args)) + + def _scan(elems): + """Perform the actual recursive scan on ``elems``.""" + num_elems = elems[0].shape[dim] + + if num_elems < 2: + return elems + + reduced_elems = call_operator( + *[aten.slice(elem, dim, 0, -1, 2) for elem in elems], + *[aten.slice(elem, dim, 1, None, 2) for elem in elems], + *additional_inputs, + ) + + # Recursively compute scan for partially reduced tensors. + odd_elems = _scan(reduced_elems) + + if num_elems % 2 == 0: + even_elems = call_operator( + *[aten.slice(e, dim, 0, -1) for e in odd_elems], + *[aten.slice(e, dim, 2, None, 2) for e in elems], + *additional_inputs, + ) + else: + even_elems = call_operator( + *odd_elems, + *[aten.slice(e, dim, 2, None, 2) for e in elems], + *additional_inputs, + ) + + # The first element of a scan is the same as the first element + # of the original `elems`. + even_elems = [ + torch.cat([aten.slice(elem, dim, 0, 1), result], dim=dim) + if result.shape.numel() > 0 and elem.shape[dim] > 0 + else result + if result.shape.numel() > 0 + else aten.slice( + elem, dim, 0, 1 + ) # Jax allows/ignores concat with 0-dim, Pytorch does not + for (elem, result) in zip(elems, even_elems) + ] + + return list( + safe_map(functools.partial(_interleave, dim=dim), even_elems, odd_elems) + ) + + scans = _scan(leaves) + + return scans + + +def trace_associative_scan( + proxy_mode, + func_overload, + combine_fn: Callable, + xs: list[torch.Tensor], + additional_inputs: tuple[torch.Tensor], +): + from torch._dynamo.utils import clone_input + + with disable_proxy_modes_tracing(): + sample_xs = [first_slice_copy(x) for x in itertools.chain(xs, xs)] + sample_additional_inputs = [ + clone_input(x) if isinstance(x, torch.Tensor) else x + for x in additional_inputs + ] + combine_graph = reenter_make_fx(combine_fn)( + *sample_xs, *sample_additional_inputs + ) + + outputs = None + for node in combine_graph.graph.nodes: + if node.op == "output": + if outputs is not None: + raise AssertionError("found multiple output nodes in combine_graph") + if len(node.args) != 1: + raise AssertionError( + f"expected output node to have 1 arg, got {len(node.args)}" + ) + outputs = node.args[0] + + if outputs is None: + raise AssertionError("no output node found in combine_graph") + outputs = pytree.tree_leaves(outputs) + if len(outputs) != len(xs): + raise AssertionError( + f"expected combine_fn to return {len(xs)} results but got {len(outputs)}" + ) + + xs_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [ + first_slice_copy(x) for x in xs + ] + output_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [ + c.meta["val"] for c in outputs + ] + check_meta_consistency( + xs_fake_tensors, output_fake_tensors, "init", "carry", include_contiguity=False + ) + + _, combine_graph_name = unique_graph_id( + proxy_mode, prefix="associative_scan_combine_graph" + ) + + proxy_mode.tracer.root.register_module(combine_graph_name, combine_graph) + + args = (combine_graph, xs, additional_inputs) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {}, name="associative_scan" + ) + + with disable_proxy_modes_tracing(): + out = tuple(aten.clone(x) for x in xs) + + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@associative_scan_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def associative_scan_op_dense(combine_fn, xs, additional_inputs): + return generic_associative_scan(combine_fn, xs, additional_inputs=additional_inputs) + + +class AssociativeScanAutogradOp(torch.autograd.Function): + r""" associative_scan + Example:: + xs = torch.arange(1, 5) = [1, 2, 3, 4] + + def combine_fn(a: torch.Tensor, b: torch.Tensor): + return a * b + + ys = associative_scan(comine_fn, xs), + which can be unpacked as: + ys0 = xs0 = 1 + ys1 = combine_fn(ys0, xs1) = combine_fn(1, 2) = 2 + ... + ysT = combine_fn(ys(T-1), xsT) = combine_fn(6, 4) = 24 + ys = [1, 2, 6, 24] + + This creates a recursive data dependency structure where each output yst + depends on all prior inputs xs0 through xst. The dependency can be visualized as: + + Level 0 (Input): xs0 xs1 xs2 xs3 xs4 + \ / | | | + \ / | | | + Level 1: ys1 ───────┘ | | + \ / | + \ / | + Level 2: ys2 ────────┘ | + \ / + \ / + Level 3: ys3 ────────────┘ + \ + \ + Level 4: ys4 + + + We could get the following backward gradient graph: + + + Level 0 (output): g_xs0 g_xs1 g_xs2 g_xs3 g_xs4 + \ / | | | + \ / | | | + Level 1: gl_ys1 ─> g_ys1 ──────┘ | | + \ / | + \ / | + Level 2: gl_ys2 ─> g_ys2 ────────┘ | + \ / + \ / + Level 3: gl_ys3 ─> g_ys3 ────────────┘ + \ + \ + Level 4: gl_ys4 ─> g_ys4, + + where gl_y1 is the gradient of the loss with respect to ys1 and the input of backward. + + To calculate the gradients of the inputs, the chain rule suggests: + + g_xs0 = g_ys1 + g_xs1 = g_ys1 * bw(ys0, xs1) = g_ys1 * bwxs01 + g_xs2 = g_ys2 * bw(ys1, xs2) = g_ys2 * bwxs12 + g_xs3 = g_ys3 * bw(ys2, xs3) = g_ys3 * bwxs23 + g_xs4 = g_ys4 * bw(ys3, xs4) = g_ys4 * bwxs34 + + Notice the bw(...) is just the single step bw (instantaneous gradients), whose formula can be computed from combine_fn. + For example bw(ys3, xs4) (also abbreviated with bwxs34) computes the gradients ∂/∂xs4 combine_fn(ys3, xs4). + Similarly, bw(ys4, ys3) (also abbreviated with bwys43) computes the gradients ∂/∂ys3 combine_fn(ys3, xs4). + + Let's break down how to calculate g_ys by recursively substituting the unknowns: + + g_ys1 = gl_ys1 + g_ys2 * bw(ys2, ys1) + = gl_ys1 + (gl_ys2 + g_ys3 * bw(ys3, ys2)) * bw(ys2, ys1) + = gl_ys1 + gl_ys2 * bw(ys2, ys1) + g_ys3 * bw(ys3, ys2) * bw(y2, y1) + = gl_ys1 + gl_ys2 * bw(ys2, ys1) + gl_ys3 * bw(ys3, ys2) * bw(y2, y1) \ + + g_ys4 * bw(ys4, ys3) * bw(ys3, ys2) * bw(ys2, ys1) + = gl_ys1 + gl_ys2 * bw(ys2, ys1) + gl_ys3 * bw(ys3, ys2) * bw(y2, y1) \ + + gl_ys4 * bw(ys4, ys3) * bw(ys3, ys2) * bw(ys2, ys1) + + Let's do the same for all the g_ys: + g_ys2 = gl_ys2 + gl_ys3 * bw(ys3, ys2) + gl_y4 * bw(ys4, ys3) * bw(ys3, ys2) + g_ys3 = gl_ys3 + gl_ys4 * bw(ys4, ys3) + g_ys4 = gl_ys4 + + Notice that the above can be re-written as columnwise multiplication of y_mat and gl_ys: + + g_ys1 1, bwys21, bwys321, bwys4321 gl_ys1 + g_ys2 = 0, 1 , bwys321, bwys4321 . gl_ys2 + g_ys3 0, 0 , 1 , bwys4321 gl_ys3 + g_ys4 0, 0 , 0 , 1 gl_ys4, + + where bwys21 is an abbreviation for bw(ys2, ys1), + bwys321 is an abbreviation for bw(ys3, ys2) * bw(ys2, ys1) so on and so forth. + + We could effectively compute the upper triangular matrix y_mat with: + cumprod([1, bwys21, bwys32, bwys43]) then masking out the values as needed. + Thus, only [1, bwys21, bwys32, bwys43] are required to compute the y_mat. + + + References: https://justintchiu.com/blog/pscan_diff/ + + NOTE: [associative_scan autograd implementation] + + The forward of associative_scan can be computed with the following steps: + + 1.) Compute the forward output of the associative_scan + ys = associative_scan(combine_fn, xs, additional_inputs) + + The backward of associative_scan can be computed with the following steps: + + 2.) Prepare the backward graph + We prepare the backward graph to be used in the backward function. + We utilize ``create_bw_fn`` to generate the joint function: + combine_fn_bw = create_bw_fn(combine_fn, operands) + where operands = [ys{t-1}, xst, additional_inputs] + + 3.) Materialize the ``combine_fn_bw`` + This is required because torch.compile and torch.autograd.grad + cannot trace through the joint backward function dynamically. + + 4.) Compute the single step bw (instantaneous gradients) at every step t + bwys{t-1}, bwxst = combine_fn_bw(ys{t-1}, xst, 1.) + Here we pass 1 as the upstream gradient to obtain the local partial derivatives. + + This gives: + bwys = [bw(ys1, ys0), bw(ys2, ys1), ..., bw(ysT, ys{T-1})] + bwxs = [bw(ys1, xs0), bw(ys2, xs1), ..., bw(ys{T-1}, xsT)] + + 5.) Compute the gradient transition matrix y_mat + + As shown in the example above, each input xst affects all later outputs ysi for i ≥ t. + According to the chain rule, each such path contributes a product of local gradients g_ysk. + + For example: + ∂ysT/∂xst = ∂ysT/∂ys{T-1} * ∂ys{T-1}/∂ys{T-2} * ... * ∂ys{t+1}/∂yst * ∂yst/∂xst + = bw(ysT, ys{T-1}) * bw(ys{T-1}, ys{T-2}) * ... * bw(ys{t+1}, yst) * bw(ys{t-1}, xst) + + This motivates the use of a cumulative product over bwys to compute all such paths efficiently. + + We now construct the matrix of gradient transition paths: + + 5.1 Repeat g_y values to form the base matrix + y_mat = [[1, bwys21, bwys32, bwys43], + [1, bwys21, bwys32, bwys43], + [1, bwys21, bwys32, bwys43], + [1, bwys21, bwys32, bwys43]] + + 5.2 Mask the lower triangle (inclusive) with 1s + y_mat = [[1, bwys21, bwys32, bwys43], + [1, 1 , bwys32, bwys43], + [1, 1 , 1 , bwys43], + [1, 1 , 1 , 1 ]] + + 5.3 Apply cumulative product row-wise + y_mat = cumprod(y_mat, dim=1) + Resulting in: + y_mat = [[1, bwys21, bwys32 * bwys21, bwys43 * bwys32 * bwys21], + [1, 1 , bwys32 , bwys43 * bwys32 ], + [1, 1 , 1 , bwys43 ], + [1, 1 , 1 , 1 ]] + + 5.4 Zero out the lower triangle (exclusive) + Final y_mat: + y_mat = [[1, bwys21, bwys32 * bwys21, bwys43 * bwys32 * bwys21], + [0, 1 , bwys32 , bwys43 * bwys32 ], + [0, 0 , 1 , bwys43 ], + [0, 0 , 0 , 1 ]] + + 6.) Scale the y_mat with the upstream gradients gl_ys + scaled_y_mat = y_mat * gl_ys + Each entry now holds the full contribution of ∂L/∂ysj to ∂L/∂xsi via the path through ysj. + + 7.) Reduce the scaled_y_mat with a row-wise sum + summed_y_mat = scaled_y_mat.sum(dim=1) + This accumulates all downstream contributions for each xst. + + 8.) Scale with the instantaneous input gradients bwxs + g_xs = summed_y_mat * bwxs + + This gives the final input gradients: + g_xs = [∂L/∂xs0, ∂L/∂xs1, ..., ∂L/∂xsT] + + NOTE: [scan partial grad handling] + If any element of xs or of the outputs does not require gradients + (i.e., requires_grad=False), then the corresponding gradients will be returned + as tensors of zeros with the same shape as the element. + """ + + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + combine_fn, + num_xs, + num_additional_inputs, + *operands, + ): + ctx._num_xs = num_xs + ctx._num_additional_inputs = num_additional_inputs + ctx._combine_fn = combine_fn + xs, additional_inputs = split_into_chunks( + operands, [num_xs, num_additional_inputs] + ) + + scan_length = xs[0].shape[0] + ctx._scan_length = scan_length + + # We snapshot the dispatch keys in forward for materializing + # the bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + + with torch._C._AutoDispatchBelowAutograd(): + # 1.) Compute the forward output of the associative_scan + ys = associative_scan_op(combine_fn, xs, additional_inputs) + save_values_for_backward(ctx, list(operands) + list(ys)) + + return (*ys,) + + @staticmethod + def backward(ctx, *gl_ys): + r""" + This function computes the gradients of the scan operation. + For a detailed description see the document above. + + Args: + flat_grads (torch.Tensor): The tensor of upstream gradients, or a nested pytree of tensors. + E.g.: Gradient of the loss with respect to the forward output ys + """ + + # The backward of associative_scan is always performed on the first dimension + dim = 0 + scan_length = ctx._scan_length + num_xs = ctx._num_xs + num_additional_inputs = ctx._num_additional_inputs + + # Extract the inputs to the forward path and outputs from the forward path + flat_args = saved_values(ctx) + xs, additional_inputs, outs = split_into_chunks( + flat_args, [num_xs, num_additional_inputs, num_xs] + ) + + if scan_length == 0: + return ( + *[None] * 3, + *[torch.zeros_like(x) for x in xs], + *[None] * num_additional_inputs, + ) + + ndim = outs[0].ndim + + # First_slice_copy does not keep the original requires_grad flag, + # but we need it here in order to compute the correcte gradients + xs_slices = first_slice_copy_with_grad(itertools.chain(xs, xs)) + + # Construct the operands from the forward, fw_operands + # and the operands for a single event t of the forward, fw_operands_slice + fw_operands = (*xs, *additional_inputs) + fw_operands_slice = (*xs_slices, *additional_inputs) + + # 2.) Prepare the backward graph + combine_fn_bw = create_bw_fn(ctx._combine_fn, fw_operands_slice) + + # 3.) Materialize the ``combine_fn_bw`` + # TODO: we need to materialize the bw graphs because dynamo is unable to + # trace through the joint function when torch.compile torch.autograd.grad. + combine_fn_bw_gm = materialize_as_graph( + combine_fn_bw, + ( + *fw_operands_slice, + *[first_slice_copy(o) for o in outs], + ), + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + + # vmap joint graph over scan dimension to compute the individual + # gradients for each time slice ``t`` in parallel. + # This computation can be parallelized, as these are just the instantaneous gradients and not the full chain-rule + # pyrefly: ignore [bad-argument-type] + mapped_combine_fn_bw_gm = torch.vmap(combine_fn_bw_gm, 0, 0) + + # 4.) Compute the single step bw (instantaneous gradients) at every step ``t`` + # Use a ones_like tensor in order not to scale the bwyst and bwxst, + # with the upstream gradients yet. + # Note: All bwyst and bwxst are computed in parallel, thus the tensors bwys and bwxs are the result. + dummy_upstream_grad = (torch.ones_like(x) for x in gl_ys) + grads = mapped_combine_fn_bw_gm( + *(o.roll(1, dim) for o in outs), *fw_operands, *dummy_upstream_grad + ) + bwys, bwxs = split_into_chunks(grads, [num_xs, num_xs]) + + def compute_y_mat(bwys: torch.Tensor) -> torch.Tensor: + # Prepare a ones and a zeros helper mask in order to easily compute the y_mat + def compute_helper_tril_mask(diagonal): + def expand_masks(mask): + for _ in range(ndim - 1): + mask = mask.unsqueeze(-1) + return mask + + tril_mask = torch.tril( + torch.ones( + scan_length, scan_length, device=bwys.device, dtype=torch.bool + ), + diagonal=diagonal, + ) + tril_mask = expand_masks(tril_mask) + tril_mask = tril_mask.expand(-1, -1, *bwys.shape[1:]) + return tril_mask + + # The ones mask is used to fill the main diagonal and all elements below it with 1s + ones_mask = compute_helper_tril_mask(0) + + # The zero mask is used to set all elements below the main diagonal to 0 + zeros_mask = compute_helper_tril_mask(-1) + + # 5.1) Repeat the elements of bwys to form the square matrix + y_mat = bwys.unsqueeze(dim).repeat_interleave(scan_length, dim) + + # 5.2) Fill the lower triangular part, including the diagonal, + # of the h_mat with 1s. I.e., use the ones_mask to fill with 1s. + y_mat.masked_fill_(ones_mask, 1.0) + + # 5.3) Compute the cumulative products across dim + 1 + y_mat = y_mat.cumprod(dim=dim + 1) + + # 5.4) Replace the elements we filled with 1s before with 0s + y_mat.masked_fill_(zeros_mask, 0.0) + + return y_mat + + def compute_grad(bwxs, bwys, gl_ys): + # Set the first gradient component of bwxs to 1.0, per definition. + torch.select(bwxs, dim, 0).fill_(1.0) + + # 5.) Compute the gradient transition matrix + y_mat = compute_y_mat(bwys) + + # 6.) scale the y_mat with the upstream gradients gl_ys + scaled_y_mat = y_mat * gl_ys + + # 7.) Reduce the y_mat with sum along the columns to get the total contributions for xs_t + summed_y_mat = scaled_y_mat.sum(dim + 1) + + # 8.) Scale with the bwxs to obtain the final gradients g_xs + g_xs = summed_y_mat * bwxs + + return g_xs + + # Stack all leaves of the gradients along the first dimension. + # This is useful as later the gradients of those leaves can be computed in parallel. + bwxs_stacked_leaves = torch.stack(bwxs) + bwys_stacked_leaves = torch.stack(bwys) + gl_ys_stacked_leaves = torch.stack(gl_ys) + + # The compute_grad function is parallelized across all individual leaves of xs + # as these gradients can be computed independently from each other + # TODO: torch.vmap may create composability issues + compute_grad_mapped = torch.vmap(compute_grad, 0, 0) + + g_xs = compute_grad_mapped( + bwxs_stacked_leaves, bwys_stacked_leaves, gl_ys_stacked_leaves + ) + + # TODO: Currently the gradients for the additional_inputs are not computed properly + return *[None] * 3, *g_xs, *[None] * num_additional_inputs + + +@associative_scan_op.py_autograd_impl +def associative_scan_autograd(combine_fn, xs, additional_inputs): + num_xs = len(xs) + num_additional_inputs = len(additional_inputs) + + if num_additional_inputs > 0: + raise RuntimeError( + "Associative_scan does currently not support gradients for lifted parameters!" + ) + + flat_out = AssociativeScanAutogradOp.apply( + combine_fn, + num_xs, + num_additional_inputs, + *(tuple(xs) + tuple(additional_inputs)), + ) + return (*flat_out,) + + +@associative_scan_op.py_impl(ProxyTorchDispatchMode) +def associative_scan_proxy_mode(mode, combine_fn, xs, additional_inputs): + return trace_associative_scan( + mode, associative_scan_op, combine_fn, xs, additional_inputs + ) + + +@register_fake(associative_scan_op, skip_cache=True) +def assoiciative_scan_fake_tensor_mode(combine_fn, xs, additional_inputs): + return tuple(x.clone() for x in xs) + + +@associative_scan_op.py_functionalize_impl +def associative_scan_functionalize(ctx, combine_fn, xs, additional_inputs): + from torch._higher_order_ops.utils import _check_alias_and_mutation + + unwrapped_xs = ctx.unwrap_tensors(xs) + unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs) + with ctx.redispatch_to_next(): + functional_combine_fn = ctx.functionalize( + _maybe_run_with_interpreter(combine_fn) + ) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + sample_unwrapped_xs_sliced = [ + first_slice_copy(inp) for inp in itertools.chain(unwrapped_xs, unwrapped_xs) + ] + sample_inputs = list( + itertools.chain( + sample_unwrapped_xs_sliced, + unwrapped_additional_inputs, + ) + ) + _check_alias_and_mutation( + combine_fn, sample_inputs, "associative_scan", pre_dispatch + ) + ret = associative_scan_op( + functional_combine_fn, + unwrapped_xs, + unwrapped_additional_inputs, + ) + return ctx.wrap_tensors(ret) + + +def _fake_associative_scan(combine_fn, xs, dim, reverse=False): + inp_leaves, spec = pytree.tree_flatten(xs) + result_flat: list[Any] = [] + num_leaves = len(inp_leaves) + op = reversed if reverse else lambda x: x + + for ind in op(range(inp_leaves[0].size(dim))): + r = [ + inp_leaves[leave_ind][(slice(None),) * dim + (ind,)] + for leave_ind in range(num_leaves) + ] + if (ind > 0 and not reverse) or ( + ind < (inp_leaves[0].size(dim) - 1) and reverse + ): + r = combine_fn( + pytree.tree_unflatten(result_flat[-1], spec), + pytree.tree_unflatten(r, spec), + ) + r_flat, _ = pytree.tree_flatten(r) + result_flat.append(r_flat) + + if len(result_flat) == 0: + results = list(inp_leaves) + else: + results = [ + torch.stack([e[leave_ind] for e in op(result_flat)], dim) + for leave_ind in range(num_leaves) + ] + return pytree.tree_unflatten(results, spec) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/auto_functionalize.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/auto_functionalize.py new file mode 100644 index 0000000000000000000000000000000000000000..7798dd5e617eeaac8602b20f8bf040167d8f8e54 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/auto_functionalize.py @@ -0,0 +1,1244 @@ +# mypy: allow-untyped-defs +import warnings +from abc import ABC, abstractmethod +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Any, get_args + +import torch +import torch._library.utils as library_utils +import torch.utils._pytree as pytree +from torch import Tensor +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + _has_gen_schema, + call_op, + HopInstance, + HopSchema, + materialize_callable_in_args, + register_fake, + unique_graph_id, +) +from torch._ops import HigherOrderOperator, OperatorBase, OpOverload +from torch._prims_common import clone_preserve_strides +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +class SchemaHolder: + def __init__(self, schema: torch.FunctionSchema): + self.schema = schema + + def __eq__(self, other): + return self.schema == other.schema + + def __hash__(self) -> int: + return hash(self.schema) + + @classmethod + def from_tree_spec(cls, tree_spec: pytree.TreeSpec): + if tree_spec is None: + raise AssertionError("tree_spec cannot be None") + return cls(pytree.tree_unflatten([], tree_spec).schema) + + +# register_constant allows us to get a tree_spec from pytree.tree_flatten(SchemaHolder(FunctionSchema)). +# The tree_spec is proxable in the graph and we can get back the schema via +# schema = pytree.tree_unflatten([], tree_spec).schema +pytree.register_constant(SchemaHolder) + + +def get_base(tensor): + if torch.is_inference_mode_enabled(): + return tensor._inference_mode_base + else: + return tensor._base + + +class ViewInfo(ABC): + base_index: int + + def __init__(self, base_index): + self.base_index = base_index + + @abstractmethod + def regenerate_view(self, bases_list: list[Tensor]): + pass + + +@dataclass +class AsStridedViewInfo(ViewInfo): + size: Sequence[int | torch.SymInt] + stride: Sequence[int | torch.SymInt] + storage_offset: int + + def __init__(self, base_index, size, stride, storage_offset): + super().__init__(base_index) + self.size = size + self.stride = stride + self.storage_offset = storage_offset + + def regenerate_view(self, bases_list: list[Tensor]): + return torch.as_strided( + bases_list[self.base_index], + self.size, + self.stride, + self.storage_offset, + ) + + +@dataclass +class SliceViewInfo(ViewInfo): + dim: int | torch.SymInt + start: int | torch.SymInt + end: int | torch.SymInt + + def __init__(self, base_index, dim, start, end): + super().__init__(base_index) + self.dim = dim + self.start = start + self.end = end + + def regenerate_view(self, bases_list: list[Tensor]): + return torch.ops.aten.slice.Tensor( + bases_list[self.base_index], self.dim, self.start, self.end + ) + + +@dataclass +class AliasViewInfo(ViewInfo): + def __init__(self, base_index): + super().__init__(base_index) + + def regenerate_view(self, bases_list: list[Tensor]): + return torch.ops.aten.alias.default(bases_list[self.base_index]) + + +@dataclass +class NotView(ViewInfo): + def __init__(self, base_index): + super().__init__(base_index) + + def regenerate_view(self, bases_list: list[Tensor]): + return bases_list[self.base_index] + + +def is_alias(base, tensor): + from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq + + return all( + statically_known_true(a) + for a in [ + sym_eq(base.storage_offset(), tensor.storage_offset()), + sym_eq(base.stride(), tensor.stride()), + sym_eq(base.size(), tensor.size()), + ] + ) + + +# return None or (dim, start, end) +def try_use_slice(base, tensor): + from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq + + # This condition should never be triggered. + if is_alias(base, tensor): + return (0, 0, base.size()[0]) + + # TODO is there cases can we use slice even if stride or len(sizes) are not equal? + if not statically_known_true(sym_eq(tensor.stride(), base.stride())): + return None + if not statically_known_true(sym_eq(len(tensor.size()), len(base.size()))): + return None + + dim = None + count = 0 + for i in range(len(tensor.size())): + if base.size()[i] != tensor.size()[i]: + dim = i + count = count + 1 + if count != 1: + return None + + if tensor.storage_offset() % tensor.stride()[dim] != 0: + return None + start = tensor.storage_offset() // tensor.stride()[dim] + end = start + tensor.size()[dim] + return (dim, start, end) + + +def write_view_information_to_args( + mutable_arg_names: list[str], + mutable_arg_types: list[torch.Type], + kwargs: dict[str, Any], + arg_to_base_index: dict[str, Any], +): + """ + This function writes the view information into kwargs. It reads mutable_args from kwargs. + and uses arg_to_base_index and tensor information to write ViewInfo into kwargs. + mutable_arg_names: mutable custom operator arg names. + mutable_arg_types: mutable custom operator arg types. + kwargs: the original custom operator args. + arg_to_base_index: maps mutable_arg_name to int | [int] that refers to the base tensor that + corresponds to the input tensor + """ + + def write_single_view(prefix: str, tensor: Tensor, base_index: int): + if f"{prefix}_base_index" in kwargs: + raise AssertionError(f"{prefix}_base_index already in kwargs") + if f"{prefix}_size" in kwargs: + raise AssertionError(f"{prefix}_size already in kwargs") + if f"{prefix}_stride" in kwargs: + raise AssertionError(f"{prefix}_stride already in kwargs") + if f"{prefix}_storage_offset" in kwargs: + raise AssertionError(f"{prefix}_storage_offset already in kwargs") + + if f"{prefix}_slice_dim" in kwargs: + raise AssertionError(f"{prefix}_slice_dim already in kwargs") + if f"{prefix}_slice_start" in kwargs: + raise AssertionError(f"{prefix}_slice_start already in kwargs") + if f"{prefix}_slice_end" in kwargs: + raise AssertionError(f"{prefix}_slice_end already in kwargs") + + def use_as_strided(tensor): + kwargs[f"{prefix}_size"] = tensor.size() + kwargs[f"{prefix}_stride"] = tensor.stride() + kwargs[f"{prefix}_storage_offset"] = tensor.storage_offset() + + def use_slice(dim, start, end): + kwargs[f"{prefix}_slice_dim"] = dim + kwargs[f"{prefix}_slice_start"] = start + kwargs[f"{prefix}_slice_end"] = end + + def use_alias(): + kwargs[f"{prefix}_alias"] = True + + # The start if the function + if tensor is None: + kwargs[f"{prefix}_base_index"] = None + else: + base = get_base(tensor) + kwargs[f"{prefix}_base_index"] = base_index + if base is None: + # no need to add anything else other than _base_index + return + elif is_alias(base, tensor): + use_alias() + elif (slice_info := try_use_slice(base, tensor)) is not None: + use_slice(*slice_info) + else: + use_as_strided(tensor) + + for arg_name, arg_type in zip(mutable_arg_names, mutable_arg_types): + arg = kwargs[arg_name] + if library_utils.is_tensorlist_like_type(arg_type): + if arg is None: + kwargs[f"_{arg_name}_length"] = None + else: + kwargs[f"_{arg_name}_length"] = len(arg) + for i, elem in enumerate(arg): + write_single_view( + f"_{arg_name}_{i}", elem, arg_to_base_index[arg_name][i] + ) + + elif library_utils.is_tensor_like_type(arg_type): + write_single_view( + f"_{arg_name}", + kwargs[arg_name], + arg_to_base_index.get(arg_name), # type: ignore[arg-type] + ) + else: + raise RuntimeError(f"Unsupported type {arg_type}") + + +# Returns a dict of arg_name -> ViewInfo | [ViewInfo] +def read_view_information_from_args( + mutable_arg_names: list[str], + mutable_arg_types: list[torch.Type], + kwargs: dict[str, Any], + all_bases: list[Tensor], +): + """ + This reads the view information added by `write_view_information_to_args` from kwargs, pop them, + and returns a dict arg_name -> ViewInfo | [ViewInfo](if the input is list). that maps each mutable arg + to its view information. + mutable_arg_names: mutable custom operator arg names. + mutable_arg_types: mutable custom operator arg types. + kwargs : args of auto_functionalize(custom_op, kwargs) + """ + + def get_arg(name): + return kwargs.pop(name) + + def read_single_view(prefix): + base_index = get_arg(f"{prefix}_base_index") + if base_index is None: + return None + elif f"{prefix}_alias" in kwargs: + get_arg(f"{prefix}_alias") + return AliasViewInfo(base_index) + elif f"{prefix}_storage_offset" in kwargs: + # The view is regenerated using as_strided. + size = get_arg(f"{prefix}_size") + stride = get_arg(f"{prefix}_stride") + storage_offset = get_arg(f"{prefix}_storage_offset") + return AsStridedViewInfo(base_index, size, stride, storage_offset) + elif f"{prefix}_slice_dim" in kwargs: + dim = get_arg(f"{prefix}_slice_dim") + start = get_arg(f"{prefix}_slice_start") + end = get_arg(f"{prefix}_slice_end") + return SliceViewInfo(base_index, dim, start, end) + else: + # This means that the argument is the base tensor + return NotView(base_index) + + args_view_info: dict[str, Any] = {} + for arg_name, arg_type in zip(mutable_arg_names, mutable_arg_types): + if library_utils.is_tensorlist_like_type(arg_type): + length = get_arg(f"_{arg_name}_length") + if length is None: + # The whole list is None. + args_view_info[arg_name] = None + else: + args_view_info[arg_name] = [ + read_single_view(f"_{arg_name}_{i}") for i in range(length) + ] + + elif library_utils.is_tensor_like_type(arg_type): + args_view_info[arg_name] = read_single_view(f"_{arg_name}") + else: + raise RuntimeError(f"Unsupported type {arg_type}") + return args_view_info + + +# NOTE: [auto-functionalizing custom ops] +# Users may wish to torch.compile custom ops that mutate their inputs. +# torch.compile will automatically support this op without anyone needing +# to provide a functionalization kernel for it. Here's how. +# +# Let's say we have a hypothetical mylib::sin_(Tensor(a!) x) -> () +# op. First, when FakeTensor sees this op: +# - If the schema says it returns nothing, we can generate a trivial +# FakeTensor rule for it (that returns nothing). +# - Otherwise, the user needs to provide a FakeTensor impl (fake impl) +# +# Next, when Python FunctionalTensor sees the op, it will functionalize +# it by emitting a call to an auto_functionalize(op, ["x"], {"x": ...}) +# HOP and replacing the mutated inputs with corresponding outputs of this HOP. +# This HOP effectively runs the functional version of the op when +# called: it clones inputs that will be mutated, runs the op, and +# then returns (output, Tensors with the new values) +# +# auto_functionalize_v2 is an improved version of auto_functionalize that better handle +# re-inplacing views. + + +class AutoFunctionalized(HigherOrderOperator): + """auto_functionalized(_mutable_op, **kwargs) + + This HOP runs a "functional" version of _mutable_op. + + Concretely, it looks at all the arguments that are mutable through + _mutable_op's operator schema, clones those kwargs, runs + `out = _mutable_op(**kwargs)` with the cloned values, and then returns the + operator output concatenated with the cloned values that were mutated. + + We have some restrictions on `_mutable_op`. + See `can_auto_functionalize` for the restrictions. We can likely lift + many of these if users request it. + + The reason why _mutable_op is prefixed with an + underscore is to prevent collisions with kwarg names in **kwargs. + """ + + def __init__(self) -> None: + super().__init__("auto_functionalized", cacheable=True) + + def __call__( + self, + /, + _mutable_op: OpOverload, + **kwargs: Any, + ) -> tuple[Any, tuple[Tensor, ...]]: + if not can_auto_functionalize(_mutable_op): + raise AssertionError(f"Cannot auto-functionalize op {_mutable_op}") + if not isinstance(kwargs, dict): + raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}") + # pyrefly: ignore [missing-attribute] + return super().__call__(_mutable_op, **kwargs) + + +auto_functionalized = AutoFunctionalized() +auto_functionalized.__module__ = "torch.ops.higher_order" + +auto_functionalized.fallthrough(DispatchKey.AutogradCPU) +auto_functionalized.fallthrough(DispatchKey.AutogradCUDA) + + +_MutableOpType = OpOverload | HigherOrderOperator + + +class AutoFunctionalizedV2(HigherOrderOperator): + """auto_functionalized_v2(_mutable_op, **kwargs) + + This HOP runs a "functional" version of _mutable_op. + Unlike AutoFunctionalized, this version is improved to better handle + view tensors. This version is only used in non export mode. + """ + + def __init__(self) -> None: + super().__init__("auto_functionalized_v2", cacheable=True) + + def __call__( + self, + /, + _mutable_op: _MutableOpType, + **kwargs: Any, + ) -> tuple[Any, tuple[Tensor, ...]]: + _op_to_check: OpOverload | HopInstance | None = None + if isinstance(_mutable_op, HigherOrderOperator): + _op_to_check = HopInstance( + _mutable_op, + SchemaHolder.from_tree_spec(kwargs.get("_op_schema")).schema, # type: ignore[arg-type] + ) + else: + _op_to_check = _mutable_op + + if _op_to_check is None: + raise AssertionError("_op_to_check cannot be None") + if not can_auto_functionalize(_op_to_check): + raise AssertionError(f"Cannot auto-functionalize op {_op_to_check}") + if not isinstance(kwargs, dict): + raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}") + # pyrefly: ignore [missing-attribute] + return super().__call__(_mutable_op, **kwargs) + + +auto_functionalized_v2 = AutoFunctionalizedV2() +auto_functionalized_v2.__module__ = "torch.ops.higher_order" + +auto_functionalized_v2.fallthrough(DispatchKey.AutogradCPU) +auto_functionalized_v2.fallthrough(DispatchKey.AutogradCUDA) + + +def can_auto_functionalize( + op: OperatorBase | HopInstance, +) -> bool: + if isinstance(op, HopInstance): + # HOPs that implement gen_schema and schema is not functional are auto_functionalizable. + if not _has_gen_schema(op._op): + return False + + else: + if not isinstance(op, OpOverload): + return False + + if torch._library.utils.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 not schema.is_mutable: + return False + schema = op._schema + + for arg in schema.arguments: + if arg.alias_info is None: + continue + if not arg.alias_info.is_write: + continue + if torch._library.utils.is_tensor_like_type(arg.type): + continue + if torch._library.utils.is_tensorlist_like_type(arg.type): + continue + return False + + if len(schema.returns) == 1 and isinstance(schema.returns[0].type, torch.NoneType): + # Skip schema returns -> None + return True + if isinstance(op, OpOverload): + if torch._library.utils.is_out(op): + # Out ops have aliased returns (returns alias the mutable args). + # This is fine because the mutable args are write-only output buffers. + pass + elif torch._library.utils.is_inplace(op): + # Inplace ops have aliased returns (return aliases the first mutable arg). + pass + else: + # The returns of OpOverload must not alias anything + for ret in schema.returns: + if ret.alias_info is None and type(ret.type) is torch.TensorType: + continue + # Not yet supported: List[Tensor] return. + return False + if torch._C._dispatch_has_kernel_for_dispatch_key(op.name(), "Functionalize"): + return False + return True + + +def get_mutable_args_from_schema( + schema: torch.FunctionSchema, +) -> tuple[list[str], list[torch.Type]]: + """ + Returns the list of argument names that get mutated according to the + schema and their types. + """ + mutable_args_names = [ + arg.name + for arg in schema.arguments + if arg.alias_info is not None and arg.alias_info.is_write + ] + + mutable_args_types = [ + arg.type + for arg in schema.arguments + if arg.alias_info is not None and arg.alias_info.is_write + ] + return mutable_args_names, mutable_args_types # type: ignore[return-value] + + +def get_mutable_args(op: OpOverload) -> tuple[list[str], list[torch.Type]]: + return get_mutable_args_from_schema(op._schema) + + +def do_auto_functionalize( + mode: "torch._subclasses.functional_tensor.FunctionalTensorMode", + op: OpOverload, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> Any: + """Functionalizes a call to op(*args, **kwargs) by emitting a call to + `outs = auto_functionalized(op, normalized_kwargs)` + and replacing the mutated (args, kwargs) with the corresponding outputs. + + The normalized_kwargs are just the (args, kwargs), but all in kwarg form. + This makes handling easier for the auto_functionalized HOP. + """ + from torch._subclasses.functional_tensor import PythonFunctionalizeAPI + + ctx = PythonFunctionalizeAPI(mode=mode) + + # All of the (args, kwargs), but all as kwargs. The names for the + # args come from the schema. This makes it easier for us to work with them. + normalized_kwargs = {} + schema = op._schema + for idx, arg in enumerate(schema.arguments): + # NB: torch_dispatch kwargs are the args defined as kwarg-only in the schema + if arg.name in kwargs: + normalized_kwargs[arg.name] = kwargs[arg.name] + elif idx < len(args): + # if its out of bounds we don't need to do anything + # as it means the optional arg was passed with its default + # value + normalized_kwargs[arg.name] = args[idx] + else: + normalized_kwargs[arg.name] = arg.default_value + + unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type] + if "self" in unwrapped_kwargs or "self_" in unwrapped_kwargs: + warnings.warn( + "Using `self` or `self_` as an argument in the definition of custom ops may lead to ambiguous parsing. " + "Please consider using a different name for this argument to avoid potential issues.", + stacklevel=2, + ) + with ctx.redispatch_to_next(): + unwrapped_outs = auto_functionalized( + op, + **unwrapped_kwargs, # type: ignore[arg-type] + ) + + # List of the name of args that get mutated (according to the schema) + mutable_args_names, _ = get_mutable_args(op) + + unwrapped_actual_out: Any | tuple[Any] = unwrapped_outs[: -len(mutable_args_names)] + unwrapped_mutable_out = unwrapped_outs[-len(mutable_args_names) :] + + if len(op._schema.returns) == 0: + if unwrapped_actual_out[0] is not None: + raise AssertionError( + f"Expected None for op with no returns, got {unwrapped_actual_out[0]}" + ) + unwrapped_actual_out = None + elif len(op._schema.returns) == 1: + if len(unwrapped_actual_out) != 1: + raise AssertionError(f"Expected 1 output, got {len(unwrapped_actual_out)}") + unwrapped_actual_out = unwrapped_actual_out[0] + else: + if len(unwrapped_actual_out) != len(op._schema.returns): + raise AssertionError( + f"Expected {len(op._schema.returns)} outputs, got {len(unwrapped_actual_out)}" + ) + + for name, unwrapped_out in zip(mutable_args_names, unwrapped_mutable_out): + # Can be None if input was `Tensor(a!)?` + if unwrapped_out is None: + continue + + # We only handle Tensor or List[Tensor] here for now. + def sync_update(o, orig_arg): + ctx.replace(orig_arg, o) + ctx.commit_update(orig_arg) + ctx.sync(orig_arg) + + orig_arg = normalized_kwargs[name] + + if isinstance(unwrapped_out, torch.Tensor): + sync_update(unwrapped_out, orig_arg) + elif isinstance(unwrapped_out, list) and all( + isinstance(o, torch.Tensor) for o in unwrapped_out + ): + if len(orig_arg) != len(unwrapped_out): + raise AssertionError( + f"orig_arg length ({len(orig_arg)}) != unwrapped_out length ({len(unwrapped_out)})" + ) + for orig_a, o in zip(orig_arg, unwrapped_out): + sync_update(o, orig_a) + else: + raise RuntimeError( + f"unsupported type for auto-functionalization: {unwrapped_out}" + ) + + return ctx.wrap_tensors(unwrapped_actual_out) # type: ignore[arg-type] + + +# Wrapper for GraphModule that applies functionalization during execution to enable +# epilogue graph inlining and better fusion opportunities in subgraphs +# When tracing this wrapper, we'll get a graph module with epilogue. +# +# We want to hash it according to the original graph module, so that when we go +# from Functional mode -> fake mode for multiple invoke_subgraph calls that share, +# the same inner graph module, we can hit the cache. +class FunctionalCallableWithEpilogue: + def __init__(self, orig_callable: Callable): + self.orig_callable = orig_callable + # Propagate so callers pass inputs as a list, enabling input deallocation. + self._boxed_call = getattr(orig_callable, "_boxed_call", False) + + def __call__(self, *args, **kwargs): + # Functionalize to inline the epilogue graph (copy_ ops) for better fusion. + # Python functionalization so mutable custom ops reach auto_functionalized_v2. + from torch._subclasses.functional_tensor import ( + dispatch_functionalize, + FunctionalTensorMode, + ) + + functionalized = dispatch_functionalize( + self.orig_callable, + FunctionalTensorMode(), + propagate_input_mutations=True, + ) + if self._boxed_call: + # Not all callers respect _boxed_call (e.g. reenter_make_fx + # always calls f(*args)). Detect which convention was used. + if len(args) == 1 and isinstance(args[0], list): + return tuple(functionalized(args[0])) + return tuple(functionalized(list(args))) + return functionalized(*args, **kwargs) + + def __hash__(self): + return id(self.orig_callable) + + +def do_auto_functionalize_v2( + mode: "torch._subclasses.functional_tensor.FunctionalTensorMode", + op: OpOverload | HopInstance, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> Any: + from torch._subclasses.functional_tensor import PythonFunctionalizeAPI + + ctx = PythonFunctionalizeAPI(mode=mode) + + # All of the (args, kwargs), but all as kwargs. The names for the + # args come from the schema. This makes it easier for us to work with them. + normalized_kwargs = {} + + schema = op._schema + # pyrefly: ignore [bad-assignment] + op = op._op if isinstance(op, HopInstance) else op + if not isinstance(op, get_args(_MutableOpType)): + raise AssertionError(f"Expected _MutableOpType, got {type(op)}") + + subgraph_arg_names = { + arg_info.name + for arg_info in schema.arguments + if isinstance(arg_info.type, torch._C.AnyType) + } + + def _maybe_functionalize(name: str, arg: Any) -> Any: + if name in subgraph_arg_names and callable(arg): + return FunctionalCallableWithEpilogue(arg) + return arg + + args = tuple( + _maybe_functionalize(schema.arguments[i].name, a) + if i < len(schema.arguments) + else a + for i, a in enumerate(args) + ) + kwargs = {k: _maybe_functionalize(k, v) for k, v in kwargs.items()} + + for idx, arg in enumerate(schema.arguments): + # NB: torch_dispatch kwargs are the args defined as kwarg-only in the schema + if arg.name in kwargs: + normalized_kwargs[arg.name] = kwargs[arg.name] + elif idx < len(args): + # if its out of bounds we don't need to do anything + # as it means the optional arg was passed with its default + # value + normalized_kwargs[arg.name] = args[idx] + else: + normalized_kwargs[arg.name] = arg.default_value + + if isinstance(op, OpOverload) and torch._library.utils.is_out(op): + return _do_auto_functionalize_v2_for_out_operator( + ctx, op, schema, normalized_kwargs + ) + if isinstance(op, OpOverload) and torch._library.utils.is_inplace(op): + return _do_auto_functionalize_v2_for_inplace_operator( + ctx, op, schema, normalized_kwargs + ) + return _do_auto_functionalize_v2_for_generic_mutable_operator( + ctx, op, schema, normalized_kwargs + ) + + +def _do_auto_functionalize_v2_for_out_operator( + ctx: Any, + op: OpOverload, + schema: Any, + normalized_kwargs: dict[str, Any], +) -> Any: + """Handle functionalization for out= operators. + + Out= operators have write-only mutable args. These are not inputs to + auto_functionalized_v2; we encode their tensor properties so the dense + impl can create empty tensors. + """ + mutable_args_names, _ = get_mutable_args_from_schema(schema) + + # Save references to the original FunctionalTensors for post-call sync + out_arg_originals = [normalized_kwargs[name] for name in mutable_args_names] + + # Encode tensor properties and remove the actual out tensors from kwargs + for arg_name in mutable_args_names: + arg = normalized_kwargs[arg_name] + normalized_kwargs[f"_{arg_name}_size"] = arg.size() + normalized_kwargs[f"_{arg_name}_stride"] = arg.stride() + normalized_kwargs[f"_{arg_name}_dtype"] = arg.dtype + normalized_kwargs[f"_{arg_name}_device"] = arg.device + del normalized_kwargs[arg_name] + + unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type] + auto_func_kwargs = dict(unwrapped_kwargs, _all_bases=[]) + + with ctx.redispatch_to_next(): + unwrapped_outs = auto_functionalized_v2( + op, + **auto_func_kwargs, # type: ignore[arg-type] + ) + + # For out= ops, the functional HOP returns exactly the out tensors. + # auto_functionalized_v2 returns a bare tensor for single return, + # tuple for multiple. + results = unwrapped_outs if isinstance(unwrapped_outs, tuple) else (unwrapped_outs,) + for orig_arg, result in zip(out_arg_originals, results, strict=True): + ctx.replace(orig_arg, result) + ctx.commit_update(orig_arg) + ctx.sync(orig_arg) + + return ctx.wrap_tensors(unwrapped_outs) # type: ignore[arg-type] + + +def _do_auto_functionalize_v2_for_inplace_operator( + ctx: Any, + op: OpOverload, + schema: Any, + normalized_kwargs: dict[str, Any], +) -> Any: + """Handle functionalization for inplace operators. + + Inplace operators mutate their first positional argument (self) and return + it. Unlike out= operators (write-only), self is read by the operator, so + it must be passed as a base for clone analysis during reinplacing. + """ + mutable_args_names, mutable_args_types = get_mutable_args_from_schema(schema) + + self_arg_name = mutable_args_names[0] + self_arg = normalized_kwargs[self_arg_name] + + # self is both read and written; pass its base for clone analysis + base = self_arg if get_base(self_arg) is None else get_base(self_arg) + + arg_to_base_index: dict[str, Any] = {self_arg_name: 0} + write_view_information_to_args( + mutable_args_names, mutable_args_types, normalized_kwargs, arg_to_base_index + ) + del normalized_kwargs[self_arg_name] + + unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type] + all_bases_unwrapped = ctx.unwrap_tensors([base]) + auto_func_kwargs = dict(unwrapped_kwargs, _all_bases=all_bases_unwrapped) + + with ctx.redispatch_to_next(): + unwrapped_outs = auto_functionalized_v2( + op, + **auto_func_kwargs, # type: ignore[arg-type] + ) + + # HOP returns (op_result, mutated_self_base). + # op_result aliases mutated_self_base (inplace semantics). + unwrapped_result = unwrapped_outs[0] + unwrapped_mutated_base = unwrapped_outs[1] + + ctx.replace(base, unwrapped_mutated_base) + ctx.commit_update(base) + ctx.sync(base) + + return ctx.wrap_tensors(unwrapped_result) # type: ignore[arg-type] + + +def _do_auto_functionalize_v2_for_generic_mutable_operator( + ctx: Any, + op: Any, + schema: Any, + normalized_kwargs: dict[str, Any], +) -> Any: + """Handle functionalization for generic mutable operators via the + auto_functionalized_v2 HOP.""" + mutable_args_names, mutable_args_types = get_mutable_args_from_schema(schema) + + # A list of all bases of mutable args without duplication + all_bases: list[Any] = [] + all_bases_addresses: list[int] = [] + + # Map arg_name to the index of its base in all_bases. + arg_to_base_index: dict[str, Any] = {} + + def update_dict(tensor, arg_name, index=None): + base = tensor if get_base(tensor) is None else get_base(tensor) + + def set_result(base_index): + if index is None: + arg_to_base_index[arg_name] = base_index + else: + arg_to_base_index[arg_name][index] = base_index + + if not all_bases_addresses.__contains__(base._cdata): + all_bases_addresses.append(base._cdata) + all_bases.append(base) + set_result(len(all_bases) - 1) + else: + set_result(all_bases_addresses.index(base._cdata)) + + for arg_name in mutable_args_names: + arg = normalized_kwargs[arg_name] + if arg is None: + continue + + if isinstance(arg, list): + arg_to_base_index[arg_name] = {} + for i, tensor in enumerate(arg): + if tensor is None: + arg_to_base_index[arg_name].append(None) + continue + + update_dict(tensor, arg_name, i) + + else: + update_dict(arg, arg_name) + + # add view_meta for each args into unwrapped_kwargs. + write_view_information_to_args( + mutable_args_names, + mutable_args_types, + normalized_kwargs, + arg_to_base_index, + ) + + # remove mutated args from the kwargs (its a function of _all_bases now) + for arg_name in mutable_args_names: + del normalized_kwargs[arg_name] # type: ignore[arg-type] + + unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type] + if "self" in unwrapped_kwargs or "self_" in unwrapped_kwargs: + warnings.warn( + "Using `self` or `self_` as an argument in the definition of custom ops may lead to ambiguous parsing. " + "Please consider using a different name for this argument to avoid potential issues.", + stacklevel=2, + ) + all_basis_unwrapped = ctx.unwrap_tensors(all_bases) + + if "_all_bases" in unwrapped_kwargs: + raise AssertionError(f"_all_bases already in unwrapped_kwargs for {op}") + auto_func_kwargs = dict(unwrapped_kwargs, _all_bases=all_basis_unwrapped) + if isinstance(op, HigherOrderOperator): + if "_ops_schema" in unwrapped_kwargs: + raise AssertionError(f"_ops_schema already in unwrapped_kwargs for {op}") + # We pass in the tree_spec of tree_flatten(SchemaHolder) to make it proxable + auto_func_kwargs.update( + {"_op_schema": pytree.tree_flatten(SchemaHolder(schema))[1]} + ) + + with ctx.redispatch_to_next(): + unwrapped_outs = auto_functionalized_v2( + op, + **auto_func_kwargs, # type: ignore[arg-type] + ) + + unwrapped_actual_out: Any | tuple[Any] = ( + unwrapped_outs if len(all_bases) == 0 else unwrapped_outs[: -len(all_bases)] + ) + + unwrapped_mutable_out = ( + [] if len(all_bases) == 0 else unwrapped_outs[-len(all_bases) :] + ) + + if isinstance(op, HigherOrderOperator): + if len(schema.returns) <= 0: + raise AssertionError( + f"hop is expected to return at least one output {schema}." + ) + if len(unwrapped_actual_out) != len(schema.returns): + raise AssertionError( + f"Expected {len(schema.returns)} outputs, got {len(unwrapped_actual_out)}" + ) + else: + if len(schema.returns) == 0: + if unwrapped_actual_out[0] is not None: + raise AssertionError( + f"Expected None for op with no returns, got {unwrapped_actual_out[0]}" + ) + unwrapped_actual_out = None + elif len(schema.returns) == 1: + if len(unwrapped_actual_out) != 1: + raise AssertionError( + f"Expected 1 output, got {len(unwrapped_actual_out)}" + ) + unwrapped_actual_out = unwrapped_actual_out[0] + else: + if len(unwrapped_actual_out) != len(schema.returns): + raise AssertionError( + f"Expected {len(schema.returns)} outputs, got {len(unwrapped_actual_out)}" + ) + + for orig_arg, unwrapped_out in zip(all_bases, unwrapped_mutable_out): + # Can be None if input was `Tensor(a!)?` + if unwrapped_out is None: + continue + + # We only handle Tensor or List[Tensor] here for now. + def sync_update(o, orig_arg): + ctx.replace(orig_arg, o) + ctx.commit_update(orig_arg) + ctx.sync(orig_arg) + + if isinstance(unwrapped_out, torch.Tensor): + sync_update(unwrapped_out, orig_arg) + elif isinstance(unwrapped_out, list) and all( + isinstance(o, torch.Tensor) for o in unwrapped_out + ): + if len(orig_arg) != len(unwrapped_out): + raise AssertionError( + f"orig_arg length ({len(orig_arg)}) != unwrapped_out length ({len(unwrapped_out)})" + ) + for orig_a, o in zip(orig_arg, unwrapped_out): + sync_update(o, orig_a) + else: + raise RuntimeError( + f"unsupported type for auto-functionalization: {unwrapped_out}" + ) + + return ctx.wrap_tensors(unwrapped_actual_out) # type: ignore[arg-type] + + +# auto_functionalize functions +@auto_functionalized.py_impl(DispatchKey.CompositeExplicitAutograd) +def auto_functionalized_dense( + _mutable_op: OpOverload, + _only_clone_these_tensors: tuple[str, ...] | None = None, + **kwargs: Any, +) -> tuple[Any, tuple[Tensor, ...]]: + new_kwargs = dict(**kwargs) + result = [] + + _mutable_args_names, _ = get_mutable_args(_mutable_op) + for name in _mutable_args_names: + if ( + _only_clone_these_tensors is not None + and name not in _only_clone_these_tensors + ): + new_kwargs[name] = kwargs[name] + else: + new_kwargs[name] = ( + [clone_preserve_strides(x) for x in kwargs[name]] + if kwargs[name] is not None and isinstance(kwargs[name], list) + else ( + clone_preserve_strides(kwargs[name]) + if kwargs[name] is not None + else None + ) + ) + result.append(new_kwargs[name]) + out = _mutable_op(**new_kwargs) + + if isinstance(out, tuple): + return (*out, *result) # type: ignore[return-value] + else: + return (out, *result) # type: ignore[return-value] + + +@register_fake(auto_functionalized, skip_cache=True) +def auto_functionalized_fake( + _mutable_op: OpOverload, + **kwargs: Any, +) -> tuple[Any, tuple[Tensor, ...]]: + result = auto_functionalized_dense( + _mutable_op, _only_clone_these_tensors=None, **kwargs + ) + return result + + +@auto_functionalized.py_impl(ProxyTorchDispatchMode) +def auto_functionalized_proxy( + mode, + _mutable_op: OpOverload, + **kwargs: Any, +) -> tuple[Any, tuple[Tensor, ...]]: + with disable_proxy_modes_tracing(): + out = auto_functionalized(_mutable_op, **kwargs) + + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) + out_proxy = mode.tracer.create_proxy( + "call_function", + auto_functionalized, + (_mutable_op,), + proxy_kwargs, + ) + result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + return result + + +@auto_functionalized.py_functionalize_impl +def auto_functionalized_func(ctx, _mutable_op, **kwargs): + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) + with ctx.redispatch_to_next(): + result = auto_functionalized(_mutable_op, **unwrapped_kwargs) + return ctx.wrap_tensors(result) + + +# auto_functionalized_v2 functions +@auto_functionalized_v2.py_impl(DispatchKey.CompositeExplicitAutograd) +def auto_functionalized_v2_dense( + _mutable_op: _MutableOpType, + _only_clone_these_bases: tuple[int, ...] | None = None, + **kwargs: Any, +) -> tuple[Any, tuple[Tensor, ...]]: + _all_bases: list[Tensor] = kwargs.pop("_all_bases", []) + if _only_clone_these_bases is None: + _only_clone_these_bases = tuple(range(len(_all_bases))) + + if isinstance(_mutable_op, OpOverload): + schema: torch._C.FunctionSchema = _mutable_op._schema + else: + schema = pytree.tree_unflatten([], kwargs.pop("_op_schema")).schema + + if isinstance(_mutable_op, OpOverload): + _callable_op: HopInstance | OpOverload = _mutable_op + else: + if not isinstance(schema, HopSchema): + raise AssertionError(f"Expected HopSchema, got {type(schema)}") + _callable_op = HopInstance(_mutable_op, schema) + + _is_out = isinstance(_mutable_op, OpOverload) and torch._library.utils.is_out( + _mutable_op + ) + + op_kwargs_new, all_bases_new = _generate_new_op_kwargs_from_bases( + schema, + kwargs, + _all_bases, + _only_clone_these_bases, + _is_out, + ) + + out = call_op( + _callable_op, + tuple(), + op_kwargs_new, + ) + + if _is_out: + return out # type: ignore[return-value] + + if isinstance(out, tuple): + return (*out, *all_bases_new) # type: ignore[return-value] + else: + return (out, *all_bases_new) # type: ignore[return-value] + + +def _generate_new_op_kwargs_from_bases( + schema, kwargs, all_bases, _only_clone_these_bases, _is_out +): + mutable_args_names, mutable_args_types = get_mutable_args_from_schema(schema) + + if _is_out: + # For out= ops, _all_bases is empty. Create empty tensors from the + # metadata that was encoded by _do_auto_functionalize_v2_for_out_operator. + new_kwargs = dict(**kwargs) + created_out_tensors = [] + for arg_name in mutable_args_names: + size = new_kwargs.pop(f"_{arg_name}_size") + stride = new_kwargs.pop(f"_{arg_name}_stride") + dtype = new_kwargs.pop(f"_{arg_name}_dtype") + device = new_kwargs.pop(f"_{arg_name}_device") + t = torch.empty_strided(size, stride, dtype=dtype, device=device) + new_kwargs[arg_name] = t + created_out_tensors.append(t) + return new_kwargs, created_out_tensors + + args_view_info = read_view_information_from_args( + mutable_args_names, mutable_args_types, kwargs, all_bases + ) + + def maybe_copy(i, t): + if t is None: + return None + if i in _only_clone_these_bases: + return clone_preserve_strides(t) + else: + return t + + all_bases_new = [maybe_copy(i, t) for i, t in enumerate(all_bases)] + + # create new args + new_kwargs = dict(**kwargs) + + # re-generate all inputs from all_bases_new using args_view_info and add them to new_kwargs. + for arg_name in mutable_args_names: + if args_view_info[arg_name] is None: + new_kwargs[arg_name] = None + elif isinstance(args_view_info[arg_name], list): + new_kwargs[arg_name] = [] + for i, elem in enumerate(args_view_info[arg_name]): + if elem is None: + new_kwargs[arg_name].append(None) + else: + view_info = args_view_info[arg_name][i] + new_kwargs[arg_name].append( + view_info.regenerate_view(all_bases_new) + ) + else: + new_kwargs[arg_name] = args_view_info[arg_name].regenerate_view( + all_bases_new + ) + + return new_kwargs, all_bases_new + + +@register_fake(auto_functionalized_v2, skip_cache=True) +def auto_functionalized_v2_fake( + _mutable_op: _MutableOpType, + **kwargs: dict[str, Any], +) -> tuple[Any, tuple[Tensor, ...]]: + result = auto_functionalized_v2_dense( + _mutable_op, _only_clone_these_bases=None, **kwargs + ) + return result + + +@auto_functionalized_v2.py_impl(ProxyTorchDispatchMode) +def auto_functionalized_v2_proxy( + mode, + _mutable_op: _MutableOpType, + **kwargs: Any, +) -> tuple[Any, tuple[Tensor, ...]]: + if isinstance(_mutable_op, HigherOrderOperator): + # Note [materialize callable inputs as graph] + # Below code materializes the callable inputs to the hop as graph modules. + # kwargs may contain general callables, that are not proxable e.g. FunctionWithNoFreeVars + # this could happen when we auto_functionalize the backward of the hop, + # where backward fn is a callable that wraps forward graph module. + # This function materialize the callable args according to the schema of the hop. + + # We cannot materialize the callables in kwargs directly because the inputs to callable + # vary from hops to hop. To make the materialiation process generic to all hops, + # we trace a function that wraps the hop and let each hop itself figure out how to trace + # its callable inputs. Then we look at the schema of the traced hop node and replace the + # callable in original kwarg with the traced subgraphs. + # + # Specifically, we first trace a wrapped_fn that calls into the hop. Then we look for the + # hop node in the traced graph and graph module inputs to the hop. Finally, we replace the + # original kwarg's callable with the graph module. + all_bases = kwargs.get("_all_bases", []) + _only_clone_these_bases = kwargs.get("_only_clone_these_bases") + if _only_clone_these_bases is None: + _only_clone_these_bases = tuple(range(len(all_bases))) + + schema = pytree.tree_unflatten([], kwargs.get("_op_schema")).schema # type: ignore[arg-type] + new_kwargs, _ = _generate_new_op_kwargs_from_bases( + schema, + {k: v for k, v in kwargs.items() if k not in ("_all_bases", "_op_schema")}, + all_bases, + _only_clone_these_bases, + _is_out=False, + ) + + _, materialized_kwargs = materialize_callable_in_args( + HopInstance(_mutable_op, schema), tuple(), new_kwargs + ) + + # Only replace the callables in kwargs with the materialized subgraphs. + # The rest of the kwargs are kept unchanged. + subgraph_arg_names = { + arg_info.name + for arg_info in schema.arguments + if isinstance(arg_info.type, torch._C.AnyType) + } + for k, v in kwargs.items(): + if k in subgraph_arg_names and callable(v): + if k not in materialized_kwargs or not isinstance( + materialized_kwargs[k], torch.fx.GraphModule + ): + raise AssertionError( + f"Expected {k} to be in materialized_kwargs as a GraphModule" + ) + kwargs[k] = materialized_kwargs[k] + + with disable_proxy_modes_tracing(): + out = auto_functionalized_v2(_mutable_op, **kwargs) + + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) + + if isinstance(_mutable_op, HigherOrderOperator): + + def _maybe_register_subgraph(val: Any): + if isinstance(val, torch.fx.GraphModule): + _, graph_name = unique_graph_id( + mode, prefix="auto_functionalized_subgraph" + ) + mode.tracer.root.register_module(graph_name, val) + return val + return val + + proxy_kwargs = pytree.tree_map(_maybe_register_subgraph, proxy_kwargs) + + out_proxy = mode.tracer.create_proxy( + "call_function", + auto_functionalized_v2, + (_mutable_op,), + proxy_kwargs, + ) + result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + return result + + +@auto_functionalized_v2.py_functionalize_impl +def auto_functionalized_v2_func(ctx, _mutable_op, **kwargs): + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) + with ctx.redispatch_to_next(): + result = auto_functionalized_v2(_mutable_op, **unwrapped_kwargs) + return ctx.wrap_tensors(result) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/base_hop.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/base_hop.py new file mode 100644 index 0000000000000000000000000000000000000000..89095b60a2e2aa8cb2a88ff76ca7c1e2cfefb048 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/base_hop.py @@ -0,0 +1,279 @@ +# mypy: allow-untyped-defs + +import abc + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._dispatch.python import suspend_functionalization +from torch._higher_order_ops.auto_functionalize import FunctionalCallableWithEpilogue +from torch._higher_order_ops.utils import ( + check_input_alias_and_mutation_return_outputs, + HopInstance, + materialize_as_graph, + reenter_make_fx, + register_fake, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.functional_tensor import disable_functional_mode +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +class BaseHOP(HigherOrderOperator, abc.ABC): + """ + This is the "Base" HOP implementation for a HOP that looks like: + + call_subgraph_hop(subgraph, *operands, **kwargs) + + That is: + 1) the HOP stays alive until Inductor + 2) the HOP's semantics are subgraph(*operands) + 3) kwargs may be some config options but aren't passed directly to the subgraph. + + To use this, please subclass this class and override methods as necessary: + ``` + class InvokeQuant(BaseHOP): + def __init__(self): + return super().__init__("invoke_quant") + + + invoke_quant = InvokeQuant() + + + def g(x): + return x.sin().cos() + + + @torch.compile(backend="aot_eager") + def f(x): + return invoke_quant(g, x, scheme="nf4") + ``` + + NOTE: don't subclass BaseHOP out of tree! That is not allowed. All + usages must be in tree. + """ + + def __init__(self, hop_name) -> None: + super().__init__(hop_name) + + # Set up the registrations + # If you want to override any of these, override them in your subclass. + self.py_autograd_impl(self._call_Autograd) + self.py_functionalize_impl(self._call_Functionalize) + self.py_impl(ProxyTorchDispatchMode)(self._call_ProxyTorchDispatchMode) + register_fake(self, self._fake_impl, skip_cache=True) + self.py_impl(DispatchKey.CompositeExplicitAutograd)( + self._call_CompositeExplicitAutograd + ) + + def __call__(self, subgraph, *operands, **kwargs): + if not isinstance( + subgraph, + ( + torch.fx.GraphModule, + FunctionWithNoFreeVars, + FunctionalCallableWithEpilogue, + ), + ): + raise RuntimeError( + f"{self._name}: when calling this API without torch.compile, " + f"we require that the subgraph be a torch.fx.GraphModule (or " + f"a function we know doesn't have free variables)." + ) + # pyrefly: ignore [missing-attribute] + return super().__call__(subgraph, *operands, **kwargs) + + def _call_Autograd(self, subgraph, *operands, **kwargs): + if isinstance(subgraph, torch.fx.GraphModule): + pass + + # We assume the subgraph doesn't mutate inputs and there is no aliasing. + # In the PT2 stack, this is Dynamo's responsibility to figure out. + return BaseHOPFunction.apply(self, subgraph, kwargs, *operands) + + def _call_CompositeExplicitAutograd(self, subgraph, *operands, **kwargs): + from torch.utils._python_dispatch import _get_current_dispatch_mode + + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + return subgraph(*operands) + + def _call_ProxyTorchDispatchMode(self, proxy_mode, subgraph, *operands, **kwargs): + traced_graph = reenter_make_fx(subgraph)(*operands) + if not isinstance(proxy_mode.tracer, torch.fx.Tracer): + raise AssertionError( + f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}" + ) + qualname = proxy_mode.tracer.get_fresh_qualname("subgraph") + proxy_mode.tracer.root.register_module(qualname, traced_graph) + + node_args = (traced_graph, *operands) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) # type: ignore[attr-defined] + proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, kwargs) # type: ignore[attr-defined] + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", self, proxy_args, proxy_kwargs + ) + + out = self(subgraph, *operands, **kwargs) + return track_tensor_tree( + out, + out_proxy, + constant=None, + tracer=proxy_mode.tracer, # type: ignore[arg-type] + ) + + def _fake_impl(self, subgraph, *operands, **kwargs): + return subgraph(*operands) + + # NOTE [Support input mutation of hops] + # To support input mutation, hop's subgraph must be functionalized because many inductor passes are + # applied to subgraph recursively and only work on functional graph. However, we could inline an + # epilogue graph (i.e. the copy_) into the subgraph because this is how input mutation + # is implemented in the top-level graph when no hop is presented. All passes must have been and will be + # aware of the epilogue graph. + # + # Since we've supported input mutation for custom op with auto_functionalized, we share the infra for hops + # The plan is: + # 1. In hop's Functionalization key, it calls do_auto_functionalize_v2 if subgraph mutates input + # 2. In do_auto_functionalize_v2: + # a. we functionalize the callables in hop's argument. This is to make the subgraphs functional so we + # could recursively run passes on them. Also the epilogue graph is inlined at the end. + # b. we call auto_functionalized_v2 and pass in an additional schema in order to properly invoke + # the hop with normalized kwargs. + # 3. In inductor, we decompose the auto_functionalized hop by calling into the dense implementation, which + # copies the mutated inputs to the hop if necessary and call the hop. + # After these steps, the rest of the inductor stack knows how to fuse the copy_ in subgraph with other ops. + def _call_Functionalize(self, ctx, subgraph, *operands, **kwargs): + from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, + ) + + # invoke_quant has non-proxable argument of type InvokeQuant that + # we cannot generate schema for. + if self is not torch.ops.higher_order.invoke_quant_packed: + hop_instance = HopInstance.create(self, subgraph, *operands, **kwargs) + if can_auto_functionalize(hop_instance): + return do_auto_functionalize_v2( + ctx.mode, hop_instance, (subgraph, *operands), kwargs + ) + + unwrapped_operands = ctx.unwrap_tensors(operands) + with ctx.redispatch_to_next(): + # We assume the subgraph doesn't mutate inputs and there is no aliasing. + # In the PT2 stack, this is Dynamo's responsibility to figure out. + functionalized_subgraph = FunctionWithNoFreeVars( + ctx.functionalize(subgraph) + ) + out = self(functionalized_subgraph, *unwrapped_operands, **kwargs) + return ctx.wrap_tensors(out) + + # pyrefly: ignore [bad-override] + def gen_schema(self, subgraph, *operands, **kwargs): + from .schema import HopSchemaGenerator + + subgraph = materialize_as_graph(subgraph, operands) + ( + inp_inp_alias, + inp_out_alias, + out_out_alias, + mutated_inp_idx, + output, + ) = check_input_alias_and_mutation_return_outputs(subgraph) + + if not ( + len(inp_inp_alias) == 0 + and len(inp_out_alias) == 0 + and len(out_out_alias) == 0 + ): + # TODO: turn this into an error. + # test_foreach_map_backward_binary_foreach_map_addrecip_op fails the alias test. + import warnings + + warnings.warn( + "Aliasing is not supported for HOP subgraph.\n" + f"{subgraph.print_readable(print_output=False)}\n" + f"Alias info: inp-inp alias: {inp_inp_alias}, inp-out alias: {inp_out_alias}, out-out alias{out_out_alias}" + f"This may lead to silent incorrectness.", + stacklevel=2, + ) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("subgraph", subgraph) + for idx, arg in enumerate(operands): + schema_gen.add_arg(f"arg{idx}", arg, is_mutated=idx in mutated_inp_idx) + + for name, arg in kwargs.items(): + schema_gen.add_arg(name, arg, default_value=arg, kw_only=True) + + for out in output: + schema_gen.add_output(out) + + return schema_gen.gen_schema() + + +class BaseHOPFunction(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx, hop, subgraph, kwargs, *operands): + ctx.hop = hop + ctx.operands = operands + ctx.subgraph = subgraph + ctx.kwargs = kwargs + + with torch._C._AutoDispatchBelowAutograd(): + return hop(subgraph, *operands, **kwargs) + + @staticmethod + def backward(ctx, *grad_outputs): + subgraph = ctx.subgraph + operands = ctx.operands + kwargs = ctx.kwargs + + # TODO: Something special needs to happen with min cut partitioner + with ( + suspend_functionalization(), + disable_functional_mode(), + torch.enable_grad(), + ): + with disable_proxy_modes_tracing(): + from .invoke_subgraph import create_fw_bw_graph + from .utils import _from_fun + + fw_inputs = pytree.tree_map(_from_fun, operands) + ( + _, + joint_graph, + _, + ) = create_fw_bw_graph(subgraph, fw_inputs, grad_outputs) + + # The joint graph returns (*grad_inputs, *fwd_outputs). + # We only need the grad_inputs. + def bwd_fn(*args): + operands = args[: -len(grad_outputs)] + grad_outs = args[-len(grad_outputs) :] + result = joint_graph(*operands, *grad_outs) + grad_inputs = result[: -len(grad_outputs)] + return grad_inputs + + return ( + None, + None, + None, + *ctx.hop( + FunctionWithNoFreeVars(bwd_fn), *operands, *grad_outputs, **kwargs + ), + ) + + +class FunctionWithNoFreeVars: + def __init__(self, fn): + self.fn = fn + + def __call__(self, *args, **kwargs): + return self.fn(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cond.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cond.py new file mode 100644 index 0000000000000000000000000000000000000000..a55255b7f248b102643bba8f06025beccd080baf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cond.py @@ -0,0 +1,793 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import contextlib +import logging +import warnings +from collections.abc import Callable +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._C._functorch import ( + _add_batch_dim, + get_unwrapped, + is_batchedtensor, + maybe_get_bdim, +) +from torch._functorch.utils import exposed_in +from torch._higher_order_ops.utils import ( + _maybe_run_with_interpreter, + check_input_alias_and_mutation_return_outputs, + create_bw_fn, + create_fn_remove_none, + fill_none_with_masks, + materialize_as_graph, + reenter_make_fx, + save_values_for_backward, + saved_values, + unique_graph_id, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.utils._python_dispatch import _get_current_dispatch_mode + + +log = logging.getLogger(__name__) + +""" +We're going to define a `cond_op` operation. +In order to do this, we need implementations for each of the dispatch keys. +""" + + +class CondOp(HigherOrderOperator): + def __init__(self): + super().__init__("cond") + + def __call__(self, pred, true_fn, false_fn, operands): + validate_subgraph_args_types(operands) + # pyrefly: ignore [missing-attribute] + return super().__call__(pred, true_fn, false_fn, operands) + + # pyrefly: ignore [bad-override] + def gen_schema(self, pred, true_fn, false_fn, operands): + from torch._higher_order_ops.schema import HopSchemaGenerator + from torch._higher_order_ops.utils import materialize_as_graph + + then_gm: torch.fx.GraphModule = materialize_as_graph(true_fn, operands) + else_gm: torch.fx.GraphModule = materialize_as_graph(false_fn, operands) + ( + _, + _, + _, + then_mutated_inputs, + then_outputs, + ) = check_input_alias_and_mutation_return_outputs(then_gm) + ( + _, + _, + _, + else_mutated_inputs, + else_outputs, + ) = check_input_alias_and_mutation_return_outputs(else_gm) + mutated_inputs = set(then_mutated_inputs) | set(else_mutated_inputs) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("pred", pred) + schema_gen.add_arg("true_fn", then_gm) + schema_gen.add_arg("false_fn", else_gm) + for idx, arg in enumerate(operands): + schema_gen.add_arg(f"operand{idx}", arg, is_mutated=idx in mutated_inputs) + + for out in then_outputs: + schema_gen.add_output(out) + schema_gen.add_schema_tree_spec(pred, true_fn, false_fn, operands) + return schema_gen.gen_schema() + + +cond_op = CondOp() + + +@exposed_in("torch") +def cond( + pred: bool | int | float | torch.Tensor, + true_fn: Callable, + false_fn: Callable, + operands: tuple | list = (), +) -> Any: + r""" + Conditionally applies `true_fn` or `false_fn`. + + .. warning:: + + `torch.cond` is a prototype feature in PyTorch. It has limited support for input and output types. + Please look forward to a more stable implementation in a future version of PyTorch. + Read more about feature classification at: https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + `cond` is structured control flow operator. That is, it is like a Python if-statement, + but has restrictions on `true_fn`, `false_fn`, and `operands` that enable it to be + capturable using torch.compile and torch.export. + + Assuming the constraints on `cond`'s arguments are met, `cond` is equivalent to the following:: + + def cond(pred, true_branch, false_branch, operands): + if pred: + return true_branch(*operands) + else: + return false_branch(*operands) + + Args: + pred (Union[bool, torch.Tensor]): A boolean expression or a tensor with one element, + indicating which branch function to apply. + + true_fn (Callable): A callable function (a -> b) that is within the + scope that is being traced. + + false_fn (Callable): A callable function (a -> b) that is within the + scope that is being traced. The true branch and false branch must + have consistent input and outputs, meaning the inputs have to be + the same, and the outputs have to be the same type and shape. Int + output is also allowed. We'll make the output dynamic by turning it + into a symint. + + operands (Tuple of possibly nested dict/list/tuple of torch.Tensor): A tuple of inputs to the + true/false functions. It can be empty if true_fn/false_fn doesn't require input. Defaults to (). + + Example:: + + def true_fn(x: torch.Tensor): + return x.cos() + + + def false_fn(x: torch.Tensor): + return x.sin() + + + return cond(x.shape[0] > 4, true_fn, false_fn, (x,)) + + Restrictions: + - The conditional statement (aka `pred`) must meet one of the following constraints: + + - It's a `torch.Tensor` with only one element, and torch.bool dtype + + - It's a boolean expression, e.g. `x.shape[0] > 10` or `x.dim() > 1 and x.shape[1] > 10` + + - The branch function (aka `true_fn`/`false_fn`) must meet all of the following constraints: + + - The function signature must match with operands. + + - The function must return a tensor with the same metadata, e.g. shape, + dtype, etc. + + - The function cannot have in-place mutations on global variables. + (Note: in-place tensor operations such as `add_` for intermediate results + are allowed in a branch) + + - The function can perform in-place mutations on its input tensors during inference (i.e., + when `torch.is_grad_enabled()` is False). + Note: When using `torch.compile()` with a non-constant predicate, the outputs will always + be new tensors that do not share object identity with the original inputs. + + Example:: + + def true_fn(x): + return x.sin_() + + + def false_fn(x): + return x + 1 + + + def f(x): + return cond(x.sum() > 0, true_fn, false_fn, (x,)) + + + x = torch.ones(4) + with torch.no_grad(): + result = torch.compile(f)(x) + assert result is not x # result is a new tensor, not the original x + + """ + if torch.compiler.is_dynamo_compiling(): + return cond_op(pred, true_fn, false_fn, operands) + + if isinstance(pred, (bool, int, float)): + # This is the non-strict export case. Strict export and torch.compile are + # handled above in dynamo. + if torch.compiler.is_exporting(): + warnings.warn( + "Pred is a Python constant. When used with torch.cond, it specializes on one of the branches." + " If you want torch.cond to preserve two branches, please make the predicate a boolean tensor or a SymBool.", + UserWarning, + stacklevel=2, + ) + # This is the eager case. We can just run the true or false branch. + if pred: + return true_fn(*operands) + else: + return false_fn(*operands) + + def _validate_input(pred, true_fn, false_fn, operands): + if not isinstance(pred, (bool, torch.Tensor, torch.SymBool)): + raise RuntimeError(f"Expected pred to be bool or tensor, but got {pred}.") + + if isinstance(pred, torch.Tensor) and pred.numel() != 1: + raise RuntimeError( + f"Expected pred to be bool or single-element tensor, but got {pred}." + ) + + if not callable(true_fn) or not callable(false_fn): + raise RuntimeError("Expect both branches to be callable.") + + if not isinstance(operands, (tuple, list)) or pytree.tree_any( + lambda t: not isinstance(t, torch.Tensor), operands + ): + raise RuntimeError( + "Expect operands to be a tuple of possibly nested dict/list/tuple that only " + f"consists of tensor leaves, but got {operands}." + ) + + _validate_input(pred, true_fn, false_fn, operands) + + if not torch._dynamo.is_dynamo_supported(): + raise RuntimeError("torch.cond requires dynamo support.") + + # Dynamo is expecting a callable with "__code__" attribute. + # We cannot directly pass cond_op to it. So we wrap it in a dummy function. + def _cond_op_wrapper(*args, **kwargs): + return cond_op(*args, **kwargs) + + from torch._higher_order_ops.utils import _hop_compile_and_call + + return _hop_compile_and_call(_cond_op_wrapper, (pred, true_fn, false_fn, operands)) + + +def trace_cond(proxy_mode, func_overload, pred, true_fn, false_fn, operands): + if not isinstance(operands, (list, tuple)): + raise AssertionError( + f"Cond operands must be a list or tuple of tensors and SymInts {operands}" + ) + + true_graph = reenter_make_fx(true_fn)(*operands) + false_graph = reenter_make_fx(false_fn)(*operands) + + true_outs = [] + false_outs = [] + for node in true_graph.graph.nodes: + if node.op == "output": + true_outs.extend(node.args) + + for node in false_graph.graph.nodes: + if node.op == "output": + false_outs.extend(node.args) + + flat_true_outs = pytree.arg_tree_leaves(*true_outs) + flat_false_outs = pytree.arg_tree_leaves(*false_outs) + if len(flat_true_outs) != len(flat_false_outs): + raise torch._dynamo.exc.CondOpArgsMismatchError( + f"Expected to return same number of outputs but got:" + f"\n true branch returns {len(flat_true_outs)} item(s)" + f"\n false branch returns {len(flat_false_outs)} item(s)" + ) + + i, true_name = unique_graph_id(proxy_mode, prefix="true_graph") + + false_name = f"false_graph_{i}" + if hasattr(proxy_mode.tracer.root, false_name): + raise AssertionError( + f"proxy_mode.tracer.root already has attribute {false_name}" + ) + + proxy_mode.tracer.root.register_module(true_name, true_graph) + proxy_mode.tracer.root.register_module(false_name, false_graph) + + args = (pred, true_graph, false_graph, operands) + + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {} + ) + + out = func_overload(pred, true_graph, false_graph, operands) + + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@cond_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def cond_op_dense(pred, true_fn, false_fn, operands): + if not all(isinstance(o, (torch.Tensor, int)) for o in operands): + raise AssertionError( + f"Dense implementation operands must be a list of tensors and ints {operands}" + ) + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + if pred: + return true_fn(*operands) + else: + return false_fn(*operands) + + +class CondAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + pred, + true_fn, + false_fn, + *operands, + ): + ctx._pred = pred + ctx._true_bw_fn = create_bw_fn( + true_fn, + operands, + ) + ctx._false_bw_fn = create_bw_fn( + false_fn, + operands, + ) + # We snapshot the dispatch keys in forward for materializing + # the bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + save_values_for_backward(ctx, operands) + + with torch._C._AutoDispatchBelowAutograd(): + return cond_op(pred, true_fn, false_fn, operands) + + @staticmethod + def backward(ctx, *flat_grads): + operands = saved_values(ctx) + args = operands + flat_grads + # TODO: we need to materialize the bw graphs because dynamo is unable to + # trace through the joint function when torch.compile torch.autograd.grad. + true_wrapped, grads_tensor_masks = create_fn_remove_none(ctx._true_bw_fn) + true_bw_gm = materialize_as_graph( + true_wrapped, + args, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + false_wrapped, _ = create_fn_remove_none(ctx._false_bw_fn) + false_bw_gm = materialize_as_graph( + false_wrapped, + args, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + grads = cond_op( + ctx._pred, + true_bw_gm, + false_bw_gm, + args, + ) + return None, None, None, *fill_none_with_masks(grads, grads_tensor_masks) + + +# Note: +# As long as one of the tensors in pred or operands requires grad, +# all the output would require grad with backward fn set to be the CondAutogradOp. +# This is consistent with autograd.Function's semantic. +@cond_op.py_autograd_impl +def cond_autograd(pred, true_fn, false_fn, operands): + return CondAutogradOp.apply( + pred, + true_fn, + false_fn, + *operands, + ) + + +@cond_op.py_impl(ProxyTorchDispatchMode) +def inner(mode, pred, true_fn, false_fn, operands): + return trace_cond(mode, cond_op, pred, true_fn, false_fn, operands) + + +@cond_op.py_impl(FakeTensorMode) +def cond_fake_tensor_mode(mode, pred, true_fn, false_fn, operands): + # Ignore here, because if you've gotten here but you're not manually + # tracing the inner graphs, that means that you intend to reuse the graph + # directly. Which means the old unbacked symbol bindings are appropriate. + # This strategy will not work if unbacked symbols can escape. + ignore_fresh_unbacked = contextlib.nullcontext() + if mode.shape_env: + ignore_fresh_unbacked = mode.shape_env.ignore_fresh_unbacked_symbols() + + with mode, ignore_fresh_unbacked: + flat_true_outs, true_out_spec = pytree.tree_flatten(true_fn(*operands)) + flat_false_outs, false_out_spec = pytree.tree_flatten(false_fn(*operands)) + if true_out_spec != false_out_spec: + raise RuntimeError( + "Unmatched output spec from torch.cond branches: " + f"true branch tree_spec {true_out_spec} vs false branch tree_spec {false_out_spec}." + ) + + merged_outs = [] + for true_out, false_out in zip(flat_true_outs, flat_false_outs): + merged_outs.append(_merge_output(true_out, false_out, mode)) + return pytree.tree_unflatten(merged_outs, true_out_spec) + + +def check_tensor_meta_match( + t1: torch.Tensor, t2: torch.Tensor, attr_names: tuple[str, ...], msg_prefix: str +) -> None: + def _get_attr_maybe_call(t: torch.Tensor, attr_name: str) -> Any: + attr = getattr(t, attr_name) + if callable(attr): + return attr() + return attr + + for attr_name in attr_names: + lattr = _get_attr_maybe_call(t1, attr_name) + rattr = _get_attr_maybe_call(t2, attr_name) + torch._check( + lattr == rattr, + lambda: f"{msg_prefix} expected same {attr_name} but got {lattr} and {rattr}.", + ) + + +def _merge_ints_to_symint( + values: list[int], mode: FakeTensorMode +) -> int | torch.SymInt: + """Merge N concrete ints into a single unbacked SymInt bounded [min, max]. + + Returns the value unchanged when all values are equal. + """ + if all(v == values[0] for v in values): + return values[0] + if mode.shape_env is None: + raise AssertionError("mode.shape_env is None") + merged = mode.shape_env.create_unbacked_symint() + mode.shape_env.constrain_symbol_range(merged.node.expr, min(values), max(values)) + return merged + + +def _merge_output( + a: torch.Tensor | int | None, + b: torch.Tensor | int | None, + mode: FakeTensorMode, +): + from torch.fx.experimental.symbolic_shapes import ( + has_free_unbacked_symbols, + SymIntEqByExpr, + ) + + if a is None or b is None: + if not (a is None and b is None): + raise AssertionError(f"expected both a and b to be None, got a={a}, b={b}") + return None + + def min_max(s0, s1): + def _bound(s0, lower_bound: bool): + if isinstance(s0, int): + return s0 + r = mode.shape_env.var_to_range.get( # type: ignore[union-attr] + s0.node.expr, + torch.utils._sympy.value_ranges.ValueRanges.unknown(), + ) + return r.lower if lower_bound else r.upper + + return min(_bound(s0, True), _bound(s1, True)), max( + _bound(s0, False), _bound(s1, False) + ) + + if type(a) is int and type(b) is int: + return _merge_ints_to_symint([a, b], mode) + + if not (type(a) is FakeTensor and type(b) is FakeTensor): + raise AssertionError( + f"expected both a and b to be FakeTensor, got a={type(a)}, b={type(b)}" + ) + + # Note: we don't check size, stride because + # they'll be merged with unbacked symints if they differ. + _meta_to_check = { + "dtype", + "device", + "layout", + "dim", + "is_quantized", + "is_conj", + "is_sparse", + "storage_offset", + } + check_tensor_meta_match( + a, + b, + tuple(_meta_to_check), + msg_prefix="When merging two branches' output in torch.cond, ", + ) + # NYI + if a.is_quantized or b.is_quantized: + raise AssertionError("quantized tensors not yet implemented") + if a.is_sparse or b.is_sparse: + raise AssertionError("sparse tensors not yet implemented") + if a.is_conj() or b.is_conj(): + raise AssertionError("conjugate tensors not yet implemented") + + """ + Step 1: create unbacked symints for sizes that are different + along the same axis. For example: + a.size is [s0, 4, s0, 5, 4, 5] + b.size is [s1, 4, s2, 8, 4, 7] + merged_size will be [u0, 4, u1, u2, 4, u3], where + u0 has range [min(s0, s1), max(s0, s1)] + u1 has range [min(s0, s2), max(s0, s2)] + u2 has range [5, 8] + u3 has range [5, 7] + """ + merged_size: list[int | torch.SymInt] = [] + + def _has_unbacked_symbols(s: int | torch.SymInt) -> bool: + if isinstance(s, int): + return False + else: + return has_free_unbacked_symbols(s.node.expr) + + for s0, s1 in zip(a.size(), b.size()): + # If there are unbacked symbols leaked out of true_branch or false_branch + # we need to merge them with a new unbacked symbol and track in parent graph. + if ( + not _has_unbacked_symbols(s0) + and not _has_unbacked_symbols(s1) + and SymIntEqByExpr(s0) == SymIntEqByExpr(s1) + ): + merged_size.append(s0) + else: + if mode.shape_env is None: + raise AssertionError("mode.shape_env is None") + new_size = mode.shape_env.create_unbacked_symint() + mode.shape_env.constrain_symbol_range(new_size.node.expr, *min_max(s0, s1)) + merged_size.append(new_size) + + """ + This follows the logic in symbolic_shapes._compute_symbolic_stride + Step 2: Since tensor stride is an accumulative multiplication of the sizes, which is a permutated + (due to view ops) non-descending sequence. + + Case 1: No size is 1. In this case, strides have unique values. + For example, suppose we have a tensor with: + size [3, 4, 3, 5, 4, 5], + stride (1200, 300, 1, 12, 3, 60), + merged_size [u0, u1, u2, u3, u4, u5]. + + We visit the strides in ascending order: 1, 3, 12, 60, 300, 1200. In each step, we check whether + the current stride is bounded or not and bound next stride by setting. + stride_expr[next_stride] = current_stride_expr * current_size_expr + 1st round: + current_stride is 1, current_size is 3, so next_stride is 1 * 3 = 3, + current_stride_expr is set to 1, current_size_expr is u2, so stride_expr[3] is therefore 1 * u2 = u2 + 2nd round: + current_stride is 3, current_size is 4, so next_stride is 3 * 4 = 12, + current_stride_expr is stride_expr[3] i.e. u2, current_size_expr is u4, so stride_expr[12] = u2 * u4 + ... + + Case 2: At least one dimension has size 1, which can produce duplicates in strides. + In this case, theoretically, we cannot uniquely determine the expr of strides because + the accessing stride_expr with same key in different order causes the final stride expression + to be different. + + Suppose we have: + size: (3, 1) + stride: (1, 1) + merged_size: (u0, u1) + + The stride expr could either be (u1, 1) or (1, u0) depending on whether we start with u1 or u0. + For this reason, we try to break tie by sorting via descending index so we always get (u1, 1). + + Note that backend might optimize the strides anyway so this is usually not a problem as long + as two branches matches. See relevant discussions in https://github.com/pytorch/pytorch/issues/142024. + + Case 3: Dim has 0 stride. 0 stride doesn't participate in the accumulative multiplication of + sizes. So they're always treated as constant even if their corresponding size is turned into unbacked symint. + + Suppose we have: + size: (3, 3) + stride: (0, 1) + merged_size: (u0, u1) + + The merged stride would be (0, 1) + """ + + def _bound_stride( + a_ex_size: torch.Size, + b_ex_size: torch.Size, + a_ex_stride: tuple[int, ...], + b_ex_stride: tuple[int, ...], + merged_size: list[int | torch.SymInt], + ) -> list[int | torch.SymInt]: + from torch._inductor.ir import get_stride_order + + a_sorted_stride_idx = get_stride_order(a_ex_stride, mode.shape_env) + b_sorted_stride_idx = get_stride_order(b_ex_stride, mode.shape_env) + + a_stride_li: list[tuple[int | torch.SymInt, int] | None] = [None] * len( + a_ex_stride + ) + b_stride_li: list[tuple[int | torch.SymInt, int] | None] = [None] * len( + b_ex_stride + ) + for i, idx in enumerate(a_sorted_stride_idx): + a_stride_li[idx] = (a_ex_stride[i], -i) + for i, idx in enumerate(b_sorted_stride_idx): + b_stride_li[idx] = (b_ex_stride[i], -i) + + for a_pair, b_pair in zip(a_stride_li, b_stride_li): + if a_pair is None or b_pair is None: + raise AssertionError( + f"expected a_pair and b_pair to be non-None, got a_pair={a_pair}, b_pair={b_pair}" + ) + _, a_idx = a_pair + _, b_idx = b_pair + + if a_idx != b_idx: + raise RuntimeError( + f"The sorted order of strides of the two branches' output doesn't match." + f"this indicates the contiguousness of the two branches are different. " + f"True branch has stride {a_ex_stride} but false branch has stride {b_ex_stride}." + f"Consider using contiguous() to make the two branches have the same contiguousness." + ) + + def _maybe_expr(s: int | torch.SymInt): + if isinstance(s, int): + return s + return s.node.expr + + a_stride_expr: dict[Any, int | torch.SymInt] = {} + b_stride_expr: dict[Any, int | torch.SymInt] = {} + merged_strides: list[int | torch.SymInt] = [None] * len(a_ex_stride) # type: ignore[list-item] + for a_pair, b_pair in zip(a_stride_li, b_stride_li): + if a_pair is None or b_pair is None: + raise AssertionError( + f"expected a_pair and b_pair to be non-None, got a_pair={a_pair}, b_pair={b_pair}" + ) + a_val, neg_i = a_pair + b_val, _ = b_pair + + i = -neg_i + if a_val == 0: + if b_val != 0: + raise AssertionError( + f"expected b_val == 0 when a_val == 0, got a_val={a_val}, b_val={b_val}" + ) + merged_strides[i] = 0 + continue + + if _maybe_expr(a_val) in a_stride_expr: + a_expr = a_stride_expr[_maybe_expr(a_val)] + if b_stride_expr[_maybe_expr(b_val)] != a_expr: + raise AssertionError( + f"a_stride_expr:{a_stride_expr}, b_stride_expr:{b_stride_expr}" + ) + merged_strides[i] = a_expr + else: + if a_val == 1: + if b_val != 1: + raise AssertionError( + f"expected b_val == 1 when a_val == 1, got b_val={b_val}" + ) + a_stride_expr[_maybe_expr(a_val)] = 1 + b_stride_expr[_maybe_expr(b_val)] = 1 + merged_strides[i] = 1 + else: + # If we cannot find the expr of a_val in a_stride_expr, it means + # the strides is not a simple accumulative multiplication of sizes. + # In this case, we cannot determine the expr of strides from the new + # shapes so we error out and hint users to call contiguous(). + raise RuntimeError( + f"It seems one of cond's output stride is not a simple accumulative multiplication of sizes. " + f"This could be because cond returns a slice of a tensor, which is not dense in memory. " + f"True branch has size {a_ex_size}, stride {a_ex_stride} and false branch has size {b_ex_size} " + f"stride {b_ex_stride}. Hint: can call t.contiguous(). " + ) + nxt_merged_stride_expr = merged_strides[i] * merged_size[i] + a_stride_expr[_maybe_expr(a_val * a_ex_size[i])] = nxt_merged_stride_expr + b_stride_expr[_maybe_expr(b_val * b_ex_size[i])] = nxt_merged_stride_expr + # fake tensors accumulate contiguous strides as stride * max(size, 1) + a_max_key = _maybe_expr(a_val * torch.sym_max(a_ex_size[i], 1)) + b_max_key = _maybe_expr(b_val * torch.sym_max(b_ex_size[i], 1)) + a_stride_expr.setdefault(a_max_key, nxt_merged_stride_expr) + b_stride_expr.setdefault(b_max_key, nxt_merged_stride_expr) + return merged_strides + + merged_stride: list[int | torch.SymInt] = _bound_stride( + a.size(), b.size(), a.stride(), b.stride(), merged_size + ) + + with mode: + return torch.empty_strided( + merged_size, merged_stride, dtype=a.dtype, device=a.device + ) + + +@cond_op.py_functionalize_impl +def cond_func(ctx, pred, true_fn, false_fn, inputs): + from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, + ) + from torch._higher_order_ops.utils import _check_alias_and_mutation, HopInstance + + hop_instance = HopInstance.create(cond_op, pred, true_fn, false_fn, inputs) + # For now, we only support auto-functionalization for cond when using python + # functionalization mode + if can_auto_functionalize(hop_instance) and hasattr(ctx, "mode"): + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + tuple(pytree.tree_flatten((pred, true_fn, false_fn, inputs))[0]), + {}, + ) + + unwrapped_inputs = ctx.unwrap_tensors(inputs) + unwrapped_pred = ctx.unwrap_tensors(pred) + with ctx.redispatch_to_next(): + functional_true = ctx.functionalize(_maybe_run_with_interpreter(true_fn)) + functional_false = ctx.functionalize(_maybe_run_with_interpreter(false_fn)) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + for branch, branch_name in [(true_fn, "cond_true"), (false_fn, "cond_false")]: + _check_alias_and_mutation( + branch, unwrapped_inputs, branch_name, pre_dispatch + ) + + cond_return = cond_op( + unwrapped_pred, functional_true, functional_false, unwrapped_inputs + ) + return ctx.wrap_tensors(cond_return) + + +@cond_op.py_impl(torch._C._functorch.TransformType.Vmap) +def cond_batch_rule(interpreter, pred, true_fn, false_fn, inputs): + if not isinstance(inputs, (list, tuple)): + raise AssertionError( + f"Cond inputs must be a list or tuple of tensors, got {type(inputs)}" + ) + if not all(isinstance(i, torch.Tensor) for i in inputs): + raise AssertionError( + f"Cond inputs must be a list of tensors, got {[type(i) for i in inputs]}" + ) + + pred_is_batched = isinstance(pred, torch.Tensor) and is_batchedtensor(pred) + pred_ = get_unwrapped(pred) if pred_is_batched else pred + + # unbatched tensors are not vmapped + tensors, in_dims = zip( + *[ + (get_unwrapped(t), maybe_get_bdim(t)) if is_batchedtensor(t) else (t, None) + for t in inputs + ] + ) + + if pred_is_batched: + # prepend "pred" and vmap everything + tensors = (pred_,) + tensors + in_dims = (0,) + in_dims + + def fn(p, *args): + t = true_fn(*args) + f = false_fn(*args) + return torch.where(p, t[0], f[0]) + + with interpreter.lower(): + result = torch.vmap(fn, in_dims=in_dims)(*tensors) + + else: + # predicate is known at this stage and it is a boolean expression or a + # tensor with one element. + true_fn = torch.vmap(true_fn, in_dims=in_dims) + false_fn = torch.vmap(false_fn, in_dims=in_dims) + + with interpreter.lower(): + result = cond_op(pred, true_fn, false_fn, tensors) + + if not isinstance(result, tuple): + result = (result,) + lvl = interpreter.level() + return tuple(_add_batch_dim(r, 0, lvl) for r in result) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cudagraph_conditional_nodes.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cudagraph_conditional_nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..d8bc93d1a58f5c20c4de9f997bce7e151569f1de --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/cudagraph_conditional_nodes.py @@ -0,0 +1,238 @@ +# mypy: allow-untyped-defs +from collections.abc import Generator +from contextlib import contextmanager + +import torch +import torch.utils._pytree as pytree +from torch.utils._python_dispatch import TorchDispatchMode + + +class CUDAGraphCaptureControlFlowOpDispatchMode(TorchDispatchMode): + @classmethod + def ignore_compile_internals(cls) -> bool: + return True + + def __init__( + self, + ) -> None: + self.supports_higher_order_operators = True + super().__init__() + + def __torch_dispatch__( + self, + func, + types, + args=(), + kwargs=None, + ): + kwargs = {} if kwargs is None else kwargs + if func is torch.ops.higher_order.cond: + # Re-enter the mode to support nested conditionals + _check_no_cond_kwargs(kwargs) + with self: + return if_else_node(*args) + if func is torch.ops.higher_order.while_loop: + # Re-enter the mode to support nested control flow + _check_no_while_loop_kwargs(kwargs) + with self: + return while_loop_node(*args) + return func(*args, **kwargs) + + +class ControlFlowOpWarmupDispatchMode(TorchDispatchMode): + """Warm up control-flow subgraphs before CUDA graph capture. + + Data-dependent control flow does not necessarily execute every subgraph, so + operations in an untaken torch.cond branch or a torch.while_loop body may + not have been warmed up. This mode uses a relaxed stream capture, whose + final CUDA graph is discarded, to warm up both cond branches and execute a + while_loop body once. This works because stream capture does not execute GPU + code and the branch and body functions are FX graphs without CPU side + effects. + """ + + @classmethod + def ignore_compile_internals(cls) -> bool: + return True + + def __init__( + self, + ) -> None: + super().__init__() + self.supports_higher_order_operators = True + self.capture_stream = torch.cuda.Stream() + + def __torch_dispatch__( + self, + func, + types, + args=(), + kwargs=None, + ): + kwargs = {} if kwargs is None else kwargs + + # Warm up both sides of this torch.cond() + if func is torch.ops.higher_order.cond: + if torch.cuda.is_current_stream_capturing(): + # This is a call to torch.cond() nested within another + # control-flow function. + _check_no_cond_kwargs(kwargs) + with self: + # We re-enter the mode in case of nested calls to torch.cond() + return if_else_node(*args) + else: + _check_no_cond_kwargs(kwargs) + with ( + torch.cuda.graph( + torch.cuda.CUDAGraph(), + pool=None, + stream=self.capture_stream, + capture_error_mode="relaxed", + ), + self, + ): + if_else_node(*args) + + return func(*args, **kwargs) + elif func is torch.ops.higher_order.while_loop: + _check_no_while_loop_kwargs(kwargs) + if torch.cuda.is_current_stream_capturing(): + # This is a call to torch.while_loop() nested within another + # control-flow function. + with self: + return while_loop_node(*args) + else: + with ( + torch.cuda.graph( + torch.cuda.CUDAGraph(), + pool=None, + stream=self.capture_stream, + capture_error_mode="relaxed", + ), + self, + ): + while_loop_node(*args) + + return func(*args, **kwargs) + else: + return func(*args, **kwargs) + + +def _check_no_cond_kwargs(kwargs) -> None: + if kwargs: + raise RuntimeError("CUDA graph conditional torch.cond does not support kwargs") + + +def _check_no_while_loop_kwargs(kwargs) -> None: + if kwargs: + raise RuntimeError( + "CUDA graph conditional torch.while_loop does not support kwargs" + ) + + +def _is_boolean_scalar_cuda_tensor(pred: object) -> bool: + return ( + isinstance(pred, torch.Tensor) + and pred.size() == torch.Size([]) + and pred.dtype == torch.bool + and pred.is_cuda + ) + + +@contextmanager +def _if_body(pred: torch.Tensor) -> Generator[None, None, None]: + current_cuda_graph = torch.cuda.CUDAGraph.get_currently_capturing_graph() + current_cuda_graph.begin_capture_to_if_node(pred) + try: + yield + finally: + current_cuda_graph.end_capture_to_conditional_node() + + +def if_else_node(pred: torch.Tensor, true_fn, false_fn, operands): + if not pred.is_cuda: + raise ValueError( + "Conditions must be on a cuda device to use conditional node in cuda graphs" + ) + # if-else is not supported until CUDA 12.8. Therefore, we use two + # if conditions, where one evaluates !pred + outs = [] + + for lazy_pred, fn in [ + (lambda: pred, true_fn), + (lambda: torch.logical_not(pred), false_fn), + ]: + with _if_body(lazy_pred()): + outs.append(fn(*operands)) + + # The output of the else branch gets copied into the + # output of the if branch. This is done because the rest + # of the cudagraph after the conditional node has fixed + # inputs, so we need to merge the two outputs into a + # single output. + if len(outs) == 2: + for if_out, else_out in zip( + pytree.tree_iter(outs[0]), pytree.tree_iter(outs[1]) + ): + if_out.copy_(else_out) + return outs[0] + + +@contextmanager +def _while_body(pred: torch.Tensor): + current_cuda_graph = torch.cuda.CUDAGraph.get_currently_capturing_graph() + current_cuda_graph.begin_capture_to_while_node(pred) + try: + yield current_cuda_graph + finally: + current_cuda_graph.end_capture_to_conditional_node() + + +def while_loop_node( + cond_fn, + body_fn, + carried_inputs, + additional_inputs, +): + flat_carried_inputs, carried_spec = pytree.tree_flatten(carried_inputs) + if not all(isinstance(inp, torch.Tensor) for inp in flat_carried_inputs): + raise RuntimeError( + "CUDA graph while_loop conditional nodes only support tensor carried_inputs" + ) + + loop_carried = pytree.tree_map_only( + torch.Tensor, lambda inp: inp.clone(), carried_inputs + ) + flat_loop_carried = pytree.tree_leaves(loop_carried) + + pred = cond_fn(*loop_carried, *additional_inputs) + if not _is_boolean_scalar_cuda_tensor(pred): + raise RuntimeError( + f"cond_fn must return a boolean scalar CUDA tensor but got {pred}" + ) + + with _while_body(pred) as current_cuda_graph: + body_out = body_fn(*loop_carried, *additional_inputs) + flat_body_out, body_out_spec = pytree.tree_flatten(body_out) + if body_out_spec != carried_spec: + raise RuntimeError( + "body_fn should return the same pytree structure as carried_inputs" + ) + if not all(isinstance(out, torch.Tensor) for out in flat_body_out): + raise RuntimeError( + "CUDA graph while_loop conditional nodes only support tensor " + "body_fn outputs" + ) + + for carried, out in zip(flat_loop_carried, flat_body_out): + if carried.data_ptr() != out.data_ptr(): + carried.copy_(out) + + pred = cond_fn(*loop_carried, *additional_inputs) + if not _is_boolean_scalar_cuda_tensor(pred): + raise RuntimeError( + f"cond_fn must return a boolean scalar CUDA tensor but got {pred}" + ) + current_cuda_graph.set_conditional_handle_for_current_node(pred) + + return loop_carried diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/effects.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/effects.py new file mode 100644 index 0000000000000000000000000000000000000000..9806e14d4edbf1a45b7d438f24da681e32926daa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/effects.py @@ -0,0 +1,342 @@ +# mypy: allow-untyped-defs +from typing import Any, cast, Union + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.invoke_leaf_function import invoke_leaf_function +from torch._higher_order_ops.print import print as hop_print +from torch._higher_order_ops.schema import HopSchema +from torch._higher_order_ops.torchbind import call_torchbind +from torch._higher_order_ops.utils import register_fake +from torch._library.custom_ops import CustomOpDef +from torch._library.effects import EffectType +from torch._library.utils import RegistrationHandle +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +_op_identifier = Union[ + str, + "torch._ops.OpOverload", + "torch._library.custom_ops.CustomOpDef", + "torch._ops.HigherOrderOperator", +] +OpType = Union["torch._ops.HigherOrderOperator", "torch._ops.OpOverload"] + +_EffectType = EffectType + + +def _get_op_qualname(op: _op_identifier) -> str: + """Convert an op identifier to a qualified string key.""" + if isinstance(op, torch._ops.OpOverload): + return op._name + elif isinstance(op, torch._ops.HigherOrderOperator): + return f"{op.namespace}::{op.name()}" + elif isinstance(op, CustomOpDef): + return op._qualname + elif isinstance(op, str): + return op + + raise ValueError(f"Invalid operator input {op}") + + +def _register_effectful_op( + op: _op_identifier, effect: EffectType | None +) -> RegistrationHandle: + qualname = _get_op_qualname(op) + entry = torch._library.simple_registry.singleton.find(qualname) + handle = entry.effect.register(effect) + return handle + + +def _get_effect(op: _op_identifier) -> _EffectType | None: + qualname = _get_op_qualname(op) + entry = torch._library.simple_registry.singleton.find(qualname) + return entry.effect.effect + + +_register_effectful_op("aten::_print", _EffectType.ORDERED) +# _linalg_check_errors has no tensor output, but it raises on invalid linalg +# results and must be preserved by functionalization/DCE. +_register_effectful_op("aten::_linalg_check_errors", _EffectType.ORDERED) +_register_effectful_op("profiler::_record_function_exit._RecordFunction", None) +_register_effectful_op(call_torchbind, _EffectType.ORDERED) +_register_effectful_op(hop_print, _EffectType.ORDERED) +_register_effectful_op(invoke_leaf_function, _EffectType.ORDERED) + + +class WithEffects(HigherOrderOperator): + """ + with_effects(token, op, args, kwargs) -> (new_token, op_results) + + This HOP helps ensure ordering between side effectful ops like prints or ops + using torchbind objects. This is needed to ensure a traced graph from + AOTAutograd is functional so that future optimization passes do not reorder + these operators. This is done through threading "effect tokens" through the + graph to enforce data dependence between side effectful ops. + + The tokens are basically dummy values (torch.tensor([])). We create a token + per "effect type", which are enumerated in the _EffectType enum. + """ + + def __init__(self) -> None: + super().__init__("with_effects") + + def __call__( + self, + token, + op: OpType, + *args: tuple[Any, ...], + **kwargs: dict[str, Any], + ) -> tuple[Any, ...]: + if not isinstance(op, (torch._ops.HigherOrderOperator, torch._ops.OpOverload)): + raise AssertionError( + f"op must be HigherOrderOperator or OpOverload, got {type(op)}" + ) + if has_aliasing(op): + raise AssertionError("Ops with aliasing is not supported") + if not isinstance(kwargs, dict): + raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}") + # pyrefly: ignore [missing-attribute] + return super().__call__(token, op, *args, **kwargs) + + +with_effects = WithEffects() + + +def has_aliasing(op: OpType): + # NOT FOR PUBLIC USE + if isinstance(op, torch._ops.HigherOrderOperator): + return False + + for arg in op._schema.arguments: + if arg.alias_info is not None: + return True + for arg in op._schema.returns: + if arg.alias_info is not None: + return True + return False + + +def has_effects(op) -> bool: + return ( + isinstance(op, (torch._ops.HigherOrderOperator, torch._ops.OpOverload)) + and not has_aliasing(op) + and _get_effect(op) is not None + ) + + +def new_token_tensor() -> torch.Tensor: + return torch.tensor([]) + + +@with_effects.py_impl(DispatchKey.CompositeExplicitAutograd) +def with_effects_dense( + token: torch.Tensor, + op: torch._ops.OpOverload, + *args: tuple[Any, ...], + **kwargs: dict[str, Any], +) -> tuple[torch.Tensor, ...]: + out = op(*args, **kwargs) + new_token = new_token_tensor() + # [NOTE: with_effects return type] + # Note that we should only do *out for tuple type, but not list type. + # This is to match the schema of the op. + # For tuple output, the length of schema output is the same as the length of out. + # For list output, the length of schema output is 1 (e.g. Tensor[]) regardless of the + # length of the list. + if isinstance(out, tuple): + return (new_token, *out) + return (new_token, out) + + +@register_fake(with_effects, skip_cache=True) +def with_effects_fake( + token: torch.Tensor, + op: torch._ops.OpOverload, + *args: tuple[Any, ...], + **kwargs: dict[str, Any], +) -> tuple[torch.Tensor, ...]: + result = with_effects_dense(token, op, *args, **kwargs) + return result + + +@with_effects.py_impl(ProxyTorchDispatchMode) +def with_effects_proxy( + mode, + token: torch.Tensor, + op: torch._ops.OpOverload, + *args: tuple[Any, ...], + **kwargs: dict[str, Any], +) -> tuple[torch.Tensor, ...]: + with disable_proxy_modes_tracing(): + out = with_effects(token, op, *args, **kwargs) + + proxy_token = mode.tracer.unwrap_proxy(token) + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args) + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) + + from torch.fx.node import has_side_effect + + # To avoid the being DCEed by graph.eliminate_dead_code if they. + # don't have output or their outputs are not used. + has_side_effect(op) + + out_proxy = mode.tracer.create_proxy( + "call_function", + with_effects, + (proxy_token, op, *proxy_args), + proxy_kwargs, + ) + result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + return result + + +with_effects.fallthrough(DispatchKey.AutogradCPU) +with_effects.fallthrough(DispatchKey.AutogradCUDA) + + +@with_effects.py_functionalize_impl +def with_effects_functional( + ctx, + token: torch.Tensor, + op: torch._ops.OpOverload, + *args: tuple[Any, ...], + **kwargs: dict[str, Any], +) -> tuple[torch.Tensor, ...]: + # with_effects is already functional, so just re-emit it. + unwrapped_token, unwrapped_args, unwrapped_kwargs = ctx.unwrap_tensors( + [token, args, kwargs] + ) + with ctx.redispatch_to_next(): + result = with_effects(unwrapped_token, op, *unwrapped_args, **unwrapped_kwargs) + return ctx.wrap_tensors(result) + + +_EFFECTFUL_HOPS_WITH_SCHEMA = {hop_print, invoke_leaf_function} + + +def _get_schema(op, args, kwargs: dict | None = None) -> torch.FunctionSchema: + if isinstance(op, torch._ops.OpOverload): + return op._schema + elif op == call_torchbind: + return getattr(args[0], args[1]).schema + elif op in _EFFECTFUL_HOPS_WITH_SCHEMA: + extra_kwargs = kwargs or {} + return op.gen_schema(*args, **extra_kwargs) + else: + raise RuntimeError(f"Unable to get schema for op {op}") + + +def handle_effects( + allow_token_discovery: bool, + tokens: dict[_EffectType, torch.Tensor], + op: OpType, + args: tuple[Any, ...], + kwargs: dict[str, Any], +) -> Any: + """ + Args: + allow_token_discovery: Whether or not we are discovering tokens. If this + is true, we will create a token for every side effect type seen that + does not have a token assigned yet. If this is false, the tokens + should've all been created ahead of time, so we will error if there is + no token mapping to every effect type. + + tokens: Map of effect type to tokens. This is to chain operators of the + same effects together so that they do not get reordered in later + optimization passes. + """ + + # Get a token. We can't do `tokens.get(op, torch.tensor([]))` because + # this will create an empty tensor during proxy mode tracing if the token + # doesn't exist. But the tokens should always exist during proxy mode tracing. + key = _get_effect(op) + if key is None: + raise AssertionError(f"effect key must not be None for op {op}") + if key not in tokens: + if not allow_token_discovery: + raise AssertionError( + f"Could not find a token for effect {key} which came from the function {op}" + ) + proxy_tensor_mode = cast( + "ProxyTorchDispatchMode | None", + torch._C._get_dispatch_mode(torch._C._TorchDispatchModeKey.PROXY), + ) + if proxy_tensor_mode is not None: + # If we discovered a new token during tracing, we are in backward. + # Then we patch the graph, adding additional tangents_token as input to the joint graph. + tracer = proxy_tensor_mode.tracer + + from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + track_tensor_tree, + ) + + with disable_proxy_modes_tracing(): + token_tensor = new_token_tensor() + + token_proxy = proxy_tensor_mode.tracer.create_proxy( + "placeholder", "tangents_token", (), {}, name="tangents_token" + ) + track_tensor_tree(token_tensor, token_proxy, constant=None, tracer=tracer) + + tokens[key] = token_tensor + else: + tokens[key] = new_token_tensor() + + token = tokens[key] + + from torch._subclasses.functional_tensor import PythonFunctionalizeAPI + + ctx = PythonFunctionalizeAPI() + + unwrapped_token = ctx.unwrap_tensors([token])[0] + unwrapped_args = ctx.unwrap_tensors(args) + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) # type: ignore[arg-type] + with ctx.redispatch_to_next(): + (new_token, *unwrapped_outs) = with_effects( + unwrapped_token, op, *unwrapped_args, **unwrapped_kwargs + ) + + schema = _get_schema(op, unwrapped_args, unwrapped_kwargs) + + if isinstance(schema, HopSchema): + if len(schema.returns) == 0: + unwrapped_outs = () + else: + if len(unwrapped_outs) != len(schema.returns): + raise AssertionError( + f"expected {len(schema.returns)} outputs but got {len(unwrapped_outs)}" + ) + unwrapped_outs = tuple(unwrapped_outs) + elif len(schema.returns) == 0: + if unwrapped_outs[0] is not None: + raise AssertionError(f"expected no outputs but got {unwrapped_outs[0]}") + unwrapped_outs = None # type: ignore[assignment] + elif len(schema.returns) == 1: + if len(unwrapped_outs) != 1: + raise AssertionError(f"expected 1 output but got {len(unwrapped_outs)}") + unwrapped_outs = unwrapped_outs[0] + else: + if len(unwrapped_outs) != len(schema.returns): + raise AssertionError( + f"expected {len(schema.returns)} outputs but got {len(unwrapped_outs)}" + ) + + # Add the newly created token into the tokens map for a following call to + # use this token. + wrapped_token = ctx.wrap_tensors(new_token) + if not isinstance(wrapped_token, torch.Tensor): + raise AssertionError( + f"expected wrapped_token to be torch.Tensor, got {type(wrapped_token)}" + ) + tokens[key] = wrapped_token + + # pyrefly: ignore [bad-argument-type] + return ctx.wrap_tensors(unwrapped_outs) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/executorch_call_delegate.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/executorch_call_delegate.py new file mode 100644 index 0000000000000000000000000000000000000000..a3770350dd8fb7a8ed8a7a5d989d3f0b97d76bf5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/executorch_call_delegate.py @@ -0,0 +1,181 @@ +# mypy: allow-untyped-defs + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +# pyre-strict + +from __future__ import annotations + +from typing import Any, cast + +import torch +import torch.utils._pytree as pytree +from torch._higher_order_ops.utils import register_fake +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + get_proxy_slot, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.utils._pytree import tree_flatten + + +class ExecutorchCallDelegate(HigherOrderOperator): + def __init__(self): + super().__init__("executorch_call_delegate") + + def __call__(self, lowered_module, *args): + # pyrefly: ignore [missing-attribute] + return super().__call__(lowered_module, *args) + + +executorch_call_delegate = ExecutorchCallDelegate() +executorch_call_delegate.fallthrough(torch._C.DispatchKey.PythonDispatcher) +executorch_call_delegate.fallthrough(torch._C.DispatchKey.PythonTLSSnapshot) +executorch_call_delegate.fallthrough(torch._C.DispatchKey.ADInplaceOrView) +executorch_call_delegate.fallthrough(torch._C.DispatchKey.AutocastCPU) + +LOWERED_BACKEND_MODULE_TYPE = "LoweredBackendModule" + + +# pyre-ignore +def trace_call_delegate(proxy_mode, func_overload, lowered_module, *args): + # pyre-ignore + def _unwrap_proxy(e): + if not isinstance(e, (torch.Tensor, torch.SymInt, torch.SymFloat)): + return e + return get_proxy_slot( + cast(torch.Tensor, e), + proxy_mode.tracer, + e, + lambda e: e.proxy, # type: ignore[attr-defined] + ) + + if not is_lowered_module(lowered_module): + raise ValueError( + "executorch_call_delegate()'s first argument must be a LoweredBackendModule" + ) + + with disable_proxy_modes_tracing(): + out = call_delegate_cpu(lowered_module, *args) + + get_lowered_module_name(proxy_mode.tracer.root, lowered_module) + + node_args = (lowered_module, *args) + proxy_args = pytree.tree_map(_unwrap_proxy, node_args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {}, name="executorch_call_delegate" + ) + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@executorch_call_delegate.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd) +# pyre-ignore +def call_delegate_cpu(lowered_module, *args): + # FX creates this immutable_dict/list concept. Get rid of this. + map_types: dict[type, type] = { + torch.fx.immutable_collections.immutable_dict: dict, + torch.fx.immutable_collections.immutable_list: list, + } + new_args = pytree.tree_map_only( + tuple(map_types.keys()), + lambda a: map_types[type(a)](a), + args, + lambda a: isinstance(a, tuple(map_types.keys())), + ) + return lowered_module.original_module.module()(*new_args) + + +@executorch_call_delegate.py_autograd_impl +# pyre-ignore +def call_delegate_autograd(lowered_module, *args): + # TODO: support autograd + flat_operands, _ = tree_flatten([lowered_module, *args]) + requires_grad = any( + f.requires_grad for f in flat_operands if isinstance(f, torch.Tensor) + ) + + with torch._C._ExcludeDispatchKeyGuard( + torch._C.DispatchKeySet(torch._C.DispatchKey.AutogradCPU) + ): + res = executorch_call_delegate(lowered_module, *args) + + if requires_grad: + # Create aliases of the output that has requires_grad=True. We need + # at least one of the inputs to err_fn to require grad so that the + # output will have a grad_fn. + + # pyre-ignore + def fake_requires_grad(var): + if var is not None: + var = var.detach() + if torch.is_floating_point(var) or torch.is_complex(var): + var.requires_grad = True + return var + + return pytree.tree_map_only(torch.Tensor, fake_requires_grad, res) + + return res + + +@executorch_call_delegate.py_impl(ProxyTorchDispatchMode) +# pyre-ignore +def call_delegate_proxy_torch_dispatch_mode(mode, lowered_module, *args): + res = trace_call_delegate(mode, executorch_call_delegate, lowered_module, *args) + return res + + +@register_fake(executorch_call_delegate, skip_cache=True) +# pyre-ignore +def call_delegate_fake_tensor_mode(lowered_module, *args): + return call_delegate_cpu(lowered_module, *args) + + +@executorch_call_delegate.py_functionalize_impl +# pyre-ignore +def call_delegate_functionalize(ctx, lowered_module, *args): + unwrapped_args = tuple(ctx.unwrap_tensors(arg) for arg in args) + with ctx.redispatch_to_next(): + res = executorch_call_delegate(lowered_module, *unwrapped_args) + return ctx.wrap_tensors(res) + + +# pyre-ignore: Missing parameter annotation [2]: Parameter `obj` must have a type other than `Any`.Pyre +def is_lowered_module(obj: Any) -> bool: + """ + This function is added to avoid using isinstance(obj, + LoweredBackendModule) as it will import LoweredBackendModule, which may + cause a circular import. + """ + return type(obj).__name__ == LOWERED_BACKEND_MODULE_TYPE + + +def get_lowered_module_name( + root: torch.nn.Module, + # pyre-ignore: Undefined or invalid type [11]: Annotation `LoweredBackendModule` is not defined as a type. + lowered_module: LOWERED_BACKEND_MODULE_TYPE, # type: ignore[valid-type] +) -> str: + """ + Adds the given lowered_module into the given root module and returns the + name of the module added. + """ + # Find a qualifying name for the lowered submodule + qualname = None + i = 0 + while True: + qualname = f"lowered_module_{i}" + if not hasattr(root, qualname): + break + i += 1 + if qualname is None: + raise AssertionError( + "qualname must not be None after finding unused module slot" + ) + + root.add_module(qualname, lowered_module) + return qualname diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flat_apply.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flat_apply.py new file mode 100644 index 0000000000000000000000000000000000000000..413757a9fdb938616526fbcf02800bb6173dbdec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flat_apply.py @@ -0,0 +1,183 @@ +import typing +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Generic, overload, TypeAlias, TypeVar +from typing_extensions import ParamSpec, TypeIs, TypeVarTuple, Unpack + +import torch +import torch.fx.node +import torch.utils._pytree as pytree +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class +from torch._ops import HigherOrderOperator + + +_R = TypeVar("_R") +_P = ParamSpec("_P") +_Ts = TypeVarTuple("_Ts") + + +def is_graphable(val: object) -> TypeIs[torch.fx.node.BaseArgumentTypes]: + """Definition: a graphable type is a type that is an acceptable input/output type to a FX node.""" + return isinstance( + val, (*torch.fx.node.base_types, FakeScriptObject) + ) or is_custom_class(type(val)) + + +def is_graphable_type(typ: type[object]) -> bool: + """Return whether the given type is graphable.""" + return ( + issubclass(typ, torch.fx.node.base_types) + or is_custom_class(typ) + or issubclass(typ, FakeScriptObject) + ) + + +def to_graphable(stuff: pytree.PyTree) -> tuple[list[object], pytree.TreeSpec]: + """Flattens stuff into a flat list of graphable types.""" + # We can consider preserving things like List[int] to improve + # perf and readability (right now that is all flattened out) + flat_args, spec = pytree.tree_flatten(stuff) + for arg in flat_args: + if not is_graphable(arg): + raise RuntimeError( + f"Expected all pytree.tree_leaves of (args, kwargs) to be graphable types, but found " + f"non-fx-graphable type {type(arg)}. If this type is meant to be constant, mark it as " + f"via pytree.register_constant; otherwise, register it as a pytree." + ) + return flat_args, spec + + +def from_graphable( + flat_args: tuple[Unpack[_Ts]], spec: pytree.TreeSpec +) -> pytree.PyTree: + """The inverse of to_graphable.""" + stuff = pytree.tree_unflatten(flat_args, spec) + return stuff + + +def func_to_graphable( + func: Callable[..., object], +) -> tuple[list[object], pytree.TreeSpec]: + """ + Pack and flatten a function type into graphable types. + This is useful for legalizing the function argument of `flat_apply`. + """ + return pytree.tree_flatten(_ConstantFunction(func)) + + +@dataclass(frozen=True, slots=True) +class _ConstantFunction(Generic[_P, _R]): + func: Callable[_P, _R] + + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: + return self.func(*args, **kwargs) + + +pytree.register_constant(_ConstantFunction) + + +_OpTypes = ( + torch._ops.OpOverload | torch._ops.OpOverloadPacket | torch._ops.HigherOrderOperator +) +_op_types = typing.get_args(_OpTypes) + + +_Base: TypeAlias = torch.fx.node.BaseArgumentTypes +# pyrefly bug: pyrefly is complaining: Expected a type form, got instance of `Literal['_FXOutput'] +# pyrefly: ignore[not-a-type] +_FXOutput = _Base | Sequence["_FXOutput"] + + +class FlatApply(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("flat_apply") + + def __call__( + self, + func: _OpTypes | pytree.TreeSpec, + in_spec: pytree.TreeSpec, + *flat_args: Unpack[_Ts], + # If True then the output is checked to be valid. If False then it is up + # to the caller to ensure the output is appropriate. + checked_output: bool = True, + **_unused: object, + ) -> object: + """ + Functions that take in non-graphable types cannot directly be put into FX graph. + + Given func(*args, **kwargs), if all of the non-graphable types are pytrees, + then we're able to store a call to flat_apply(func, in_spec, *flat_args) in the FX graph. + + The semantics of flat_apply(func, in_spec, *flat_args) are roughly equivalent to: + + >>> def flat_apply_impl(func, in_spec, *flat_args): + >>> args, kwargs = pytree.tree_unflatten(flat_args, in_spec) + >>> output = func(*args, **kwargs) + >>> return output + + flat_apply supports the following two cases: + - an input type is a container type (e.g. of tensors) registered as a pytree. + We'll tree_flatten the input type and store the spec. + - an input type is a constant type (i.e. torch.compile will specialize on it) + registered with pytree.register_constant. The constant type goes directly + into the spec. + """ + if not ( + isinstance(func, _op_types) + or is_custom_class(type(func)) + or pytree._is_constant_holder(func) + ): + raise AssertionError( + f"func must be an op type, constant holder, or opaque callable, got {type(func)}" + ) + if len(_unused) != 0: + raise AssertionError(f"unexpected keyword arguments: {_unused}") + # pyrefly: ignore[bad-argument-type] # pyrefly bug? + return impl(func, in_spec, flat_args, checked_output) + + +@overload +def is_valid_output(x: tuple[object, ...]) -> TypeIs[tuple[_FXOutput, ...]]: ... + + +@overload +def is_valid_output(x: Sequence[object]) -> TypeIs[Sequence[_FXOutput]]: ... + + +def is_valid_output(x: object) -> bool: + if isinstance(x, (tuple, list)): + return all(map(is_valid_output, x)) + return is_graphable(x) + + +def impl( + func: _OpTypes | pytree.TreeSpec, + in_spec: pytree.TreeSpec, + flat_args: tuple[Unpack[_Ts]], + checked_output: bool, +) -> _FXOutput: + if isinstance(func, pytree.TreeSpec): + # assume _ConstantFunction + func = pytree._retrieve_constant(func) + if not isinstance(func, _ConstantFunction): + raise AssertionError( + f"expected retrieved constant to be _ConstantFunction, got {type(func)}" + ) + + from torch._higher_order_ops.invoke_leaf_function import unflatten_args_with_modules + + with unflatten_args_with_modules(flat_args, in_spec) as (args, kwargs): + out = func(*args, **kwargs) + + if checked_output: + # For "normal" usage all outputs must either be graphable or + # lists/tuples of graphables. + if not is_valid_output(out): + raise AssertionError( + f"output must be graphable or nested list/tuple of graphables, got {type(out)}" + ) + return out + + +flat_apply = FlatApply() diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_attention.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..3d03c43b3ec69fa115a9d026f198803d97b59c85 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_attention.py @@ -0,0 +1,1543 @@ +import contextlib +import math +from collections.abc import Callable, Sequence +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch import Tensor +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + _has_potential_branch_input_mutation, + _maybe_reenter_make_fx, + autograd_not_implemented, + has_user_subclass, + redirect_to_mode, + reenter_make_fx, + register_fake, + save_values_for_backward, + saved_values, + UnsupportedAliasMutationException, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch._subclasses import FakeTensor +from torch.amp.autocast_mode import _cast as _autocast_cast +from torch.fx.experimental.proxy_tensor import ( + make_fx, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.fx.graph_module import GraphModule +from torch.fx.traceback import annotate, current_meta +from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode + + +# Duplicate of _inductor/kernel/flex_attention.py to avoid circular import +def _construct_strides( + sizes: Sequence[int], + fill_order: Sequence[int], +) -> Sequence[int]: + """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( + f"Length of sizes must match the length of the fill order, got {len(sizes)} vs {len(fill_order)}" + ) + strides = [0] * len(sizes) + + # Start with stride 1 for the innermost dimension + current_stride = 1 + + # Iterate through the fill order populating strides + for dim in fill_order: + strides[dim] = current_stride + current_stride *= sizes[dim] + + return strides + + +def _permute_strides(out: torch.Tensor, query_strides: tuple[int, ...]) -> torch.Tensor: + """ + Create a new tensor with the same data and shape as the input, + but with strides permuted based on the input tensor's stride order. + + Args: + out (torch.Tensor): The output tensor of attention. + query_strides (List[int]): The stride order of the input query tensor + + Returns: + torch.Tensor: A new tensor with same shape and data as the input, + but with strides permuted based on the query tensor's stride order. + """ + from torch._inductor.ir import get_fill_order + + fill_order = get_fill_order(query_strides) + if out.storage_offset() != 0: + raise AssertionError( + f"Only support storage_offset == 0, got {out.storage_offset()}" + ) + out_strides = _construct_strides(out.shape, 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 out_strides[-1] != 1: + last_dim = len(out.shape) - 1 + fill_order = list(fill_order) + fill_order.remove(last_dim) + fill_order = [last_dim] + fill_order + out_strides = _construct_strides(out.shape, fill_order) + + new_out = out.new_empty_strided(out.shape, out_strides) + new_out.copy_(out) + return new_out + + +class FlexAttentionHOP(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("flex_attention", cacheable=True) + + def __call__( + self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + validate_subgraph_args_types(score_mod_other_buffers + mask_mod_other_buffers) + # pyrefly: ignore [missing-attribute] + return super().__call__( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +flex_attention = FlexAttentionHOP() + + +class FlexAttentionBackwardHOP(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("flex_attention_backward", cacheable=True) + + def __call__( + self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor | None, + grad_logsumexp: torch.Tensor | None, + fw_graph: Callable | GraphModule, + joint_graph: GraphModule, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), + ) -> tuple[ + torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...] + ]: + validate_subgraph_args_types(score_mod_other_buffers + mask_mod_other_buffers) + + # pyrefly: ignore [missing-attribute] + return super().__call__( + 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, + ) + + +flex_attention_backward = FlexAttentionBackwardHOP() + + +def _math_attention_inner( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor]: + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + working_precision = torch.float64 if query.dtype == torch.float64 else torch.float32 + + scores = query.to(working_precision) @ key.to(working_precision).transpose(-2, -1) + + b = torch.arange(0, scores.size(0), device=scores.device) + h = torch.arange(0, scores.size(1), device=scores.device) + m = torch.arange(0, scores.size(2), device=scores.device) + n = torch.arange(0, scores.size(3), device=scores.device) + + captured_buffers_in_dim = (None,) * len(score_mod_other_buffers) + from torch.nn.attention.flex_attention import _vmap_for_bhqkv + + # first input is score + score_mod = _vmap_for_bhqkv(score_mod, prefix=(0,), suffix=captured_buffers_in_dim) + + mask_mod = block_mask[-1] + mask_mod_in_dim_buffers = (None,) * len(mask_mod_other_buffers) + mask_mod = _vmap_for_bhqkv(mask_mod, prefix=(), suffix=mask_mod_in_dim_buffers) + + with TransformGetItemToIndex(): + scores = (scores * scale).to(working_precision) + post_mod_scores = torch.where( + mask_mod(b, h, m, n, *mask_mod_other_buffers), + score_mod(scores, b, h, m, n, *score_mod_other_buffers), + torch.tensor(-float("inf"), dtype=working_precision, device=scores.device), + ) + + return scores, post_mod_scores + + +def math_attention( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Eager implementation + + This implementation uses vmap to vectorize the score_mod function over the batch, head, m, and n dimensions. + We then apply the vectorized score_mod function to the scores matrix. Each wrap of vmap applies one of the + batch, head, m, or n dimensions. We need to apply vmap 4 times to vectorized over all 4 dimensions. + + Args: + query: The query tensor + key: The key tensor + value: The value tensor + score_mod: The score_mod function + other_buffers: Other buffers that are passed to the score_mod function + + Notes: + Query and Keys are dtype cast up to float64 (if query.dtype is float64) and float32 otherwise. + Scores and Values are dtype cast to input query.dtype at the end. + """ + # broadcast query & key along head dim for GQA + G = query.size(1) // key.size(1) + value = torch.repeat_interleave(value, G, dim=1) + key = torch.repeat_interleave(key, G, dim=1) + + Bq, Bkv = query.size(0), key.size(0) + if not ((Bq == Bkv) or (Bq > 1 and Bkv == 1)): + raise RuntimeError(f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}") + + key = key.expand((Bq, *key.size()[1:])) + value = value.expand((Bq, *value.size()[1:])) + + _, post_mod_scores = _math_attention_inner( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + # Set fully masked rows' sumexp to 0.0 + logsumexp = post_mod_scores.logsumexp(dim=-1) + masked_rows = torch.all(post_mod_scores == -float("inf"), dim=-1) + logsumexp = torch.where(masked_rows, -float("inf"), logsumexp) + + # working precision will be used so no need to cast to fp32 + max_scores = torch.max(post_mod_scores, dim=-1)[0] + + post_mod_scores = torch._safe_softmax(post_mod_scores, dim=-1) + + # NB: kernel computes in ln2 space, we always convert back at the top level op, so + # for math impl we divide by log(2) because we will multiply by log(2) + + return ( + post_mod_scores.to(query.dtype) @ value.to(query.dtype), + logsumexp / math.log(2), + max_scores / math.log(2), + ) + + +def _flex_attention_autocast_impl( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple, + mask_mod_other_buffers: tuple, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Forward-only autocast shim: cast Q/K/V to the active autocast dtype, then + redispatch with Autocast keys excluded so we hit the normal implementation. + """ + device_type = query.device.type + autocast_dtype = torch.get_autocast_dtype(device_type) + + query = _autocast_cast(query, device_type, autocast_dtype) + key = _autocast_cast(key, device_type, autocast_dtype) + value = _autocast_cast(value, device_type, autocast_dtype) + + autocast_keyset = torch._C.DispatchKeySet( + DispatchKey.AutocastCPU + ) | torch._C.DispatchKeySet(DispatchKey.AutocastCUDA) + with torch._C._ExcludeDispatchKeyGuard(autocast_keyset): + return flex_attention( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +@flex_attention.py_impl(DispatchKey.AutocastCUDA) +def flex_attention_autocast_cuda( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + return _flex_attention_autocast_impl( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +@flex_attention.py_impl(DispatchKey.AutocastCPU) +def flex_attention_autocast_cpu( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + return _flex_attention_autocast_impl( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +@flex_attention.py_impl(DispatchKey.CompositeExplicitAutograd) +def sdpa_dense( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + out, lse, max_scores = math_attention( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + out = _permute_strides(out, query.stride()) + return out, lse, max_scores + + +def trace_flex_attention( + proxy_mode: ProxyTorchDispatchMode, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Traces the flex_attention operator with the given score_mod function and other_buffers. + + Trace SDPA will call make_fx with "fake" example vals and then trace the score_mod function + This will produce a GraphModule that will be stored on the root tracer as "sdpa_score". We + access this graph module in inductor to inline the score_mod function to the triton template. + """ + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + example_out = flex_attention( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + example_vals = [query.new_zeros((), requires_grad=query.requires_grad)] + [ + query.new_zeros((), dtype=torch.int) for _ in range(4) + ] + mask_example_vals = [query.new_zeros((), dtype=torch.int) for _ in range(4)] + mask_mod = block_mask[-1] + with TransformGetItemToIndex(): + score_graph = reenter_make_fx(score_mod)( + *example_vals, *score_mod_other_buffers + ) + mask_graph = reenter_make_fx(mask_mod)( + *mask_example_vals, *mask_mod_other_buffers + ) + if not isinstance(proxy_mode.tracer, torch.fx.Tracer): + raise AssertionError( + f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}" + ) + block_mask = block_mask[:-1] + (mask_graph,) + qualname = proxy_mode.tracer.get_fresh_qualname("sdpa_score") + proxy_mode.tracer.root.register_module(qualname, score_graph) + mask_qualname = proxy_mode.tracer.get_fresh_qualname("sdpa_mask") + proxy_mode.tracer.root.register_module(mask_qualname, mask_graph) + node_args = ( + query, + key, + value, + score_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + # pyrefly: ignore [missing-attribute] + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) + with torch.fx.experimental.proxy_tensor.set_original_aten_op(flex_attention): + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", flex_attention, proxy_args, {} + ) + return track_tensor_tree( + example_out, + out_proxy, + constant=None, + tracer=proxy_mode.tracer, + ) + + +@flex_attention.py_impl(ProxyTorchDispatchMode) +def flex_attention_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if mode is None: + raise AssertionError("Mode should always be enabled for python fallback key") + return trace_flex_attention( + mode, + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + + +@flex_attention.py_functionalize_impl +def flex_attention_functionalize( + ctx: torch._subclasses.functional_tensor.BaseFunctionalizeAPI, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Defines the functionalization rules for the flex_attention operator. + + Right now we are unwrapping each tensor and then redispatching to the next, however we want to + guard against any mutations in the score_mod function, to the other_buffers since those + are free variables. + """ + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + query_unwrapped = ctx.unwrap_tensors(query) + key_unwrapped = ctx.unwrap_tensors(key) + value_unwrapped = ctx.unwrap_tensors(value) + block_mask_unwrapped = ctx.unwrap_tensors(block_mask) + score_mod_other_buffers_unwrapped = ctx.unwrap_tensors(score_mod_other_buffers) + mask_mod_other_buffers_unwrapped = ctx.unwrap_tensors(mask_mod_other_buffers) + + # Appease the mypy overlords + if not isinstance(query_unwrapped, torch.Tensor): + raise AssertionError( + f"expected query_unwrapped to be torch.Tensor, got {type(query_unwrapped)}" + ) + if not isinstance(key_unwrapped, torch.Tensor): + raise AssertionError( + f"expected key_unwrapped to be torch.Tensor, got {type(key_unwrapped)}" + ) + if not isinstance(value_unwrapped, torch.Tensor): + raise AssertionError( + f"expected value_unwrapped to be torch.Tensor, got {type(value_unwrapped)}" + ) + if not isinstance(block_mask_unwrapped, tuple): + raise AssertionError( + f"expected block_mask_unwrapped to be tuple, got {type(block_mask_unwrapped)}" + ) + if not isinstance(score_mod_other_buffers_unwrapped, tuple): + raise AssertionError( + f"expected score_mod_other_buffers_unwrapped to be tuple, got {type(score_mod_other_buffers_unwrapped)}" + ) + if not isinstance(mask_mod_other_buffers_unwrapped, tuple): + raise AssertionError( + f"expected mask_mod_other_buffers_unwrapped to be tuple, got {type(mask_mod_other_buffers_unwrapped)}" + ) + + example_vals = ( + [query_unwrapped.new_zeros(())] + + [query_unwrapped.new_zeros((), dtype=torch.int) for _ in range(4)] + + list(score_mod_other_buffers_unwrapped) + ) + with ctx.redispatch_to_next(): + functional_score_mod = ctx.functionalize(score_mod) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + with TransformGetItemToIndex(): + # TODO: So far only the input mutations are checked + # In the other HOPs, also aliases are checked which is + # omitted here + mutates = _has_potential_branch_input_mutation( + score_mod, example_vals, pre_dispatch + ) + # We only care about mutations of existing buffers since we can't replay these. + # However, we can just error if anything is detected + if mutates: + raise UnsupportedAliasMutationException("Mutations detected in score_mod") + + out = flex_attention( + query_unwrapped, + key_unwrapped, + value_unwrapped, + functional_score_mod, + block_mask_unwrapped, + scale, + kernel_options, + score_mod_other_buffers_unwrapped, + mask_mod_other_buffers_unwrapped, + ) + return ctx.wrap_tensors(out) # type: ignore[return-value, arg-type] + + +@register_fake(flex_attention) +def flex_attention_fake_impl( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if has_user_subclass( + ( + query, + key, + value, + score_mod, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ), + allowed_subclasses=(FakeTensor,), + ): + return NotImplemented + + v_head_dim = value.size(-1) + batch_size, num_heads, seq_len_q, _q_head_dim = query.shape + logsumexp = query.new_empty(batch_size, num_heads, seq_len_q, dtype=torch.float32) + max_scores = query.new_empty(batch_size, num_heads, seq_len_q, dtype=torch.float32) + out_shape = (batch_size, num_heads, seq_len_q, v_head_dim) + out = query.new_empty(out_shape) + out = _permute_strides(out, query.stride()) + return out, logsumexp, max_scores + + +# Registers dispatches for SAC +redirect_to_mode(flex_attention, _CachingTorchDispatchMode) +redirect_to_mode(flex_attention, _CachedTorchDispatchMode) + + +# ---------------------------- Autograd Implementation ---------------------------- +def create_fw_bw_graph( + score_mod: Callable, + index_values: tuple[Tensor, Tensor, Tensor, Tensor, Tensor], + other_buffers: tuple[Tensor, ...], +) -> tuple[Callable, Callable]: + # See Note:[HOP create fw_bw graph] + + # All of these imports need to be here in order to avoid circular dependencies + from torch._dispatch.python import suspend_functionalization + from torch._dynamo._trace_wrapped_higher_order_op import mod_index + from torch._functorch.aot_autograd import AOTConfig, create_joint + from torch._subclasses.fake_tensor import FakeTensorMode, is_fake_tensor + from torch._subclasses.functional_tensor import disable_functional_mode + from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing + + dummy_aot_config = AOTConfig( + fw_compiler=None, # type: ignore[arg-type] + bw_compiler=None, # type: ignore[arg-type] + partition_fn=None, # type: ignore[arg-type] + decompositions={}, + num_params_buffers=0, + aot_id=0, + keep_inference_input_mutations=False, + ) + + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + + def _from_fun( + t: Tensor | torch.SymInt | int, + ) -> Tensor | torch.SymInt | int: + if isinstance(t, torch.Tensor): + return torch.empty_strided( + t.size(), + t.stride(), + device=t.device, + dtype=t.dtype, + requires_grad=t.requires_grad, + ) + return t + + # If someone runs this hop under the default compiler backend ("eager") + # Then this path will be run with the actual user inputs. We convert them + # to fake tensors in order to not perform any actual compute. + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode(index_values) + if fake_mode is None: + fake_mode = FakeTensorMode(allow_non_fake_inputs=True) + + with fake_mode: + unwrapped_score_mod_indexes = pytree.tree_map(_from_fun, index_values) + unwrapped_other_buffers = pytree.tree_map(_from_fun, other_buffers) + + if not all( + is_fake_tensor(t) or isinstance(t, (int, torch.SymInt)) + for t in unwrapped_score_mod_indexes + unwrapped_other_buffers + ): + raise AssertionError( + f"all unwrapped values must be FakeTensor, int, or SymInt, got " + f"{[type(t) for t in unwrapped_score_mod_indexes + unwrapped_other_buffers]}" + ) + + example_flat_out = pytree.tree_map( + _from_fun, + score_mod(*unwrapped_score_mod_indexes, *unwrapped_other_buffers), + ) + if not isinstance(example_flat_out, torch.Tensor): + raise RuntimeError( + "Expected output of score_mod to be a tensor." + f"Got type {type(example_flat_out)}." + ) + example_grad = _from_fun(example_flat_out) + + def joint_f( + score: Tensor, + b: Tensor, + h: Tensor, + m: Tensor, + n: Tensor, + example_grad: Tensor, + *other_buffers: tuple[Tensor, ...], + ) -> list[Tensor | None]: + def fw_with_masks( + *args: tuple[Tensor, ...], + ) -> tuple[tuple[Tensor], tuple[bool]]: + captured_args = [ + mod_index(buffer, []) + if ( + isinstance(buffer, torch.Tensor) + and buffer.requires_grad + and buffer.ndim == 0 + ) + else buffer + for buffer in args[5:] + ] + fw_out = score_mod(*args[:5], *captured_args) + out_requires_grad = fw_out.requires_grad + return ((fw_out,), (out_requires_grad,)) + + joint = create_joint(fw_with_masks, aot_config=dummy_aot_config) + args = [score, b, h, m, n] + list(other_buffers) + optional_grad = [example_grad] if example_grad.requires_grad else [] + _, grads = joint(args, optional_grad) + if grads[0] is None: + raise RuntimeError( + "flex_attention backward requires the output of score_mod to " + "depend on score. Got a score_mod whose output does not " + "require gradients with respect to score." + ) + + return grads + + joint_graph = make_fx(joint_f)( + *unwrapped_score_mod_indexes, example_grad, *unwrapped_other_buffers + ) + # pyrefly: ignore [bad-return] + return score_mod, joint_graph + + +class FlexAttentionAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx: Any, + query: Tensor, + key: Tensor, + value: Tensor, + fw_graph: Callable, + joint_graph: Callable, + block_mask: tuple[Any, ...], + scale: float, + kernel_options: dict[str, Any], + mask_mod_other_buffers: tuple[Any, ...], + *score_mod_other_buffers: tuple[Any, ...], + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + ctx.set_materialize_grads(False) + # Capture sparsity_hint from tracing metadata so backward can re-annotate + ctx._sparsity_hint = current_meta.get("custom", {}).get("sparsity_hint", 0.0) + any_buffer_requires_grad = any( + buffer.requires_grad + for buffer in mask_mod_other_buffers + if isinstance(buffer, torch.Tensor) + ) + if any_buffer_requires_grad: + raise AssertionError( + "Captured buffers from mask mod that require grad are not supported." + ) + ctx._fw_graph = fw_graph + ctx._joint_graph = joint_graph + ctx._mask_graph = block_mask[-1] + ctx.scale = scale + ctx.kernel_options = kernel_options + ctx._score_mod_other_buffers_len = len(score_mod_other_buffers) + with torch._C._AutoDispatchBelowAutograd(): + out, logsumexp, max_scores = flex_attention( + query, + key, + value, + fw_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + # no grads for you sir + ctx.mark_non_differentiable(max_scores) + save_values_for_backward( + ctx, + ( + query, + key, + value, + out, + logsumexp, + max_scores, + *block_mask[:-1], + *score_mod_other_buffers, + *mask_mod_other_buffers, + ), + ) + return out, logsumexp, max_scores + + @staticmethod + def backward( # type: ignore[override] + ctx: Any, + grad_out: Tensor, + grad_logsumexp: Tensor, + grad_max_scores: Tensor, + ) -> tuple[Tensor | None, ...]: + fw_args = saved_values(ctx) + ( + query, + key, + value, + out, + logsumexp, + max_scores, + query_lengths, + kv_lengths, + 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, + Q_BLOCK_SIZE, + KV_BLOCK_SIZE, + *other_buffers, + ) = fw_args + fw_graph = ctx._fw_graph + joint_graph = ctx._joint_graph + mask_graph = ctx._mask_graph + scale = ctx.scale + kernel_options = ctx.kernel_options + score_mod_other_buffers = tuple( + other_buffers[: ctx._score_mod_other_buffers_len] + ) + mask_mod_other_buffers = tuple( + other_buffers[ctx._score_mod_other_buffers_len :] + ) + # We have asserted that mask_mod_other_buffers do not require grad, + # but score_mod_other_buffers can require grad. + none_grads = [None] * 6 + _sparsity_ctx = ( + annotate({"sparsity_hint": ctx._sparsity_hint}) + if ctx._sparsity_hint > 0 + else contextlib.nullcontext() + ) + with _sparsity_ctx: + ( + grad_query, + grad_key, + grad_value, + grad_score_mod_captured, + ) = flex_attention_backward( + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + fw_graph, + joint_graph, + ( + query_lengths, + kv_lengths, + 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, + Q_BLOCK_SIZE, + KV_BLOCK_SIZE, + mask_graph, + ), + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + return grad_query, grad_key, grad_value, *none_grads, *grad_score_mod_captured + + +# TODO: Rework DispatchKey.Autograd to py_autograd_impl +@flex_attention.py_impl(DispatchKey.Autograd) +def flex_attention_autograd( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + score_mod: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple[Tensor, ...] = (), + mask_mod_other_buffers: tuple[Tensor, ...] = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + with TransformGetItemToIndex(): + input_requires_grad = any( + isinstance(t, torch.Tensor) and t.requires_grad + for t in (query, key, value, *score_mod_other_buffers) + ) + if torch.is_grad_enabled() and input_requires_grad: + if block_mask[7] is None: + raise RuntimeError( + "BlockMask q_indices is None. Backward pass requires q_indices to be computed. " + "Please create the BlockMask with compute_q_blocks=True" + ) + example_vals = ( + query.new_zeros((), requires_grad=input_requires_grad), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + ) + fw_graph, bw_graph = create_fw_bw_graph( + score_mod, example_vals, score_mod_other_buffers + ) + else: + fw_graph, bw_graph = score_mod, None + out, logsumexp, max_scores = FlexAttentionAutogradOp.apply( + query, + key, + value, + fw_graph, + bw_graph, + block_mask, + scale, + kernel_options, + mask_mod_other_buffers, + *score_mod_other_buffers, + ) + return out, logsumexp, max_scores + + +# ---------------------------- Backward HOP Implementation ---------------------------- + + +@flex_attention_backward.py_impl(DispatchKey.CompositeExplicitAutograd) +def sdpa_dense_backward( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor | None, + grad_logsumexp: torch.Tensor | None, + fw_graph: Callable, # GraphModule type hint? + joint_graph: Callable, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple, + mask_mod_other_buffers: tuple, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]: + 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}" + ) + if joint_graph is None: + example_vals = ( + query.new_zeros((), requires_grad=True), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + query.new_zeros((), dtype=torch.int), + ) + _, joint_graph = create_fw_bw_graph( + fw_graph, example_vals, score_mod_other_buffers + ) + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + Bq, Hq, seq_len_q, qk_head_dim = query.shape + Bkv, Hkv, seq_len_kv, v_head_dim = value.shape + + # Get outputs before calling repeat interleave and permute to input stride orders + actual_grad_query = query.new_empty((Bq, Hq, seq_len_q, qk_head_dim)) + actual_grad_query = _permute_strides(actual_grad_query, query.stride()) + + actual_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim)) + actual_grad_key = _permute_strides(actual_grad_key, key.stride()) + + actual_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim)) + actual_grad_value = _permute_strides(actual_grad_value, value.stride()) + + actual_grad_score_mod_captured = _new_captured_grad_buffers( + score_mod_other_buffers, joint_graph + ) + + Bq, Bkv = query.size(0), key.size(0) + if not ((Bq == Bkv) or (Bq > 1 and Bkv == 1)): + raise RuntimeError(f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}") + + key = key.expand((Bq, *key.size()[1:])) + value = value.expand((Bq, *value.size()[1:])) + + G = query.size(1) // key.size(1) + key = torch.repeat_interleave(key, G, dim=1) + value = torch.repeat_interleave(value, G, dim=1) + + if grad_out is None: + grad_out = torch.zeros_like(out) + if grad_logsumexp is None: + grad_logsumexp = torch.zeros_like(logsumexp) + + # logsumexp is expected in log2 scale (as returned by the forward HOP). + # The public flex_attention API converts lse to natural log before returning, + # so callers using the public API must not pass that value here directly. + logsumexp = logsumexp * math.log(2) + # The backwards formula for the log -> log2 change of base in the forwards + grad_logsumexp = grad_logsumexp / math.log(2) + scores, post_mod_scores = _math_attention_inner( + query, + key, + value, + fw_graph, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ) + masked_out_rows = logsumexp == -float("inf") + softmax_scores = torch.exp(post_mod_scores - logsumexp.unsqueeze(-1)) + softmax_scores = torch.where(masked_out_rows.unsqueeze(-1), 0, softmax_scores) + + grad_value = softmax_scores.to(query.dtype).transpose(-2, -1) @ grad_out + + grad_softmax_scores = grad_out.to(dtype=softmax_scores.dtype) @ value.to( + dtype=softmax_scores.dtype + ).transpose(-2, -1) + + sum_scores = torch.sum( + out.to(dtype=softmax_scores.dtype) * grad_out.to(dtype=softmax_scores.dtype), + -1, + keepdim=True, + ) + grad_score_mod = softmax_scores * ( + grad_softmax_scores - sum_scores + grad_logsumexp.unsqueeze(-1) + ) + + b = torch.arange(0, scores.size(0), device=scores.device) + h = torch.arange(0, scores.size(1), device=scores.device) + m = torch.arange(0, scores.size(2), device=scores.device) + n = torch.arange(0, scores.size(3), device=scores.device) + + mask_graph = block_mask[-1] + # Gradient of the inline score_mod function, with respect to the scores + captured_buffers_in_dim = (None,) * len(score_mod_other_buffers) + out_dims = [0, None, None, None, None] + [None] * len(score_mod_other_buffers) + from torch.nn.attention.flex_attention import _vmap_for_bhqkv + + # inputs are [score, b, h, q_idx, kv_idx, gradOut, ...] + # score and gradOut are "fully" batched + joint_score_mod = _vmap_for_bhqkv( + joint_graph, + prefix=(0,), + suffix=(0,) + captured_buffers_in_dim, + out_dims=out_dims, + ) + with TransformGetItemToIndex(): + grad_scores, _, _, _, _, *grad_score_mod_captured = joint_score_mod( + scores, b, h, m, n, grad_score_mod, *score_mod_other_buffers + ) + grad_scores = grad_scores * scale + grad_scores = grad_scores.to(query.dtype) + + mask_mod = _vmap_for_bhqkv( + mask_graph, prefix=(), suffix=(None,) * len(mask_mod_other_buffers) + ) + with TransformGetItemToIndex(): + mask_scores = mask_mod(b, h, m, n, *mask_mod_other_buffers) + grad_scores = torch.where( + mask_scores, grad_scores, torch.tensor(0, dtype=query.dtype) + ) + + grad_query = grad_scores @ key + grad_key = grad_scores.transpose(-2, -1) @ query + + # Reduce DK, DV along broadcasted heads. + grad_key = grad_key.view( + grad_key.size(0), -1, G, grad_key.size(-2), grad_key.size(-1) + ) + grad_value = grad_value.view( + grad_value.size(0), -1, G, grad_value.size(-2), grad_value.size(-1) + ) + + grad_key = torch.sum(grad_key, 2, keepdim=False) + grad_value = torch.sum(grad_value, 2, keepdim=False) + + # Fill to correctly strided outputs + actual_grad_query.copy_(grad_query) + actual_grad_key.copy_(grad_key) + actual_grad_value.copy_(grad_value) + + if Bq != Bkv: + if not (Bq > 1 and Bkv == 1): + raise AssertionError( + f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}" + ) + + actual_grad_key = torch.sum(actual_grad_key, 0, keepdim=True) + actual_grad_value = torch.sum(actual_grad_value, 0, keepdim=True) + + score_mod_other_buffer_grads = [] + for actual_grad, grad in zip( + actual_grad_score_mod_captured, grad_score_mod_captured + ): + if not isinstance(grad, torch.Tensor): + score_mod_other_buffer_grads.append(None) + continue + if actual_grad is None: + raise AssertionError("Expected a captured grad buffer for a tensor grad") + score_mod_other_buffer_grads.append(actual_grad.copy_(grad)) + + return ( + actual_grad_query, + actual_grad_key, + actual_grad_value, + tuple(score_mod_other_buffer_grads), + ) + + +def _captured_grad_buffer_mask( + joint_graph: Callable | GraphModule, num_captures: int +) -> tuple[bool, ...]: + """Return which score_mod captures need concrete grad buffers. + + A capture can require grad but still be dead in score_mod, for example when + the function reads a closed-over tensor but returns the original score. AOT + represents that as a None grad in the joint graph, and that None must stay a + None instead of being copied into a materialized buffer. + + Conversely, this is independent of the saved capture's requires_grad flag: + compiled backward may save an intermediate whose grad is needed to propagate + to earlier user inputs. + """ + if not isinstance(joint_graph, GraphModule): + # The @register_fake path for direct flex_attention_backward HOP calls + # can see callable subgraphs before make_fx materializes them. In that + # metadata-only phase, no capture is provably dead. + return (True,) * num_captures + + output_node = next(node for node in joint_graph.graph.nodes if node.op == "output") + score_mod_arg_grads = 5 + captured_grad_outputs = output_node.args[0][score_mod_arg_grads:] + if len(captured_grad_outputs) != num_captures: + raise AssertionError( + f"Expected {num_captures} captured grad outputs, " + f"got {len(captured_grad_outputs)}" + ) + return tuple(grad is not None for grad in captured_grad_outputs) + + +def _new_captured_grad_buffers( + score_mod_other_buffers: tuple, joint_graph: Callable | GraphModule +) -> tuple[torch.Tensor | None, ...]: + """Allocate only the captured grad buffers that the joint graph can produce.""" + needs_grad_buffer = _captured_grad_buffer_mask( + joint_graph, len(score_mod_other_buffers) + ) + # The lowering returns captured grads as contiguous buffers, so match that here. + return tuple( + torch.empty_like(buffer, memory_format=torch.contiguous_format) + if isinstance(buffer, torch.Tensor) and needs_buffer + else None + for buffer, needs_buffer in zip(score_mod_other_buffers, needs_grad_buffer) + ) + + +def trace_flex_attention_backward( + proxy_mode: ProxyTorchDispatchMode, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor, + grad_logsumexp: torch.Tensor, + fw_graph: Callable | GraphModule, + joint_graph: GraphModule, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]: + """We already have the forward graph and joint graph from the forward pass, so we create a proxy attach both graphs""" + from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex + + requires_grad = any(pytree.tree_map(lambda x: x.requires_grad, (query, key))) + fw_example_vals = [query.new_zeros((), requires_grad=requires_grad)] + [ + query.new_zeros((), dtype=torch.int) for _ in range(4) + ] + bw_example_vals = fw_example_vals + [query.new_zeros(())] + mask_example_vals = [query.new_zeros((), dtype=torch.int) for _ in range(4)] + mask_graph = block_mask[-1] + with TransformGetItemToIndex(): + # There's no active make_fx during the compiled autograd graph's initial capture + fw_graph = _maybe_reenter_make_fx(fw_graph)( + *fw_example_vals, *score_mod_other_buffers + ) + joint_graph = _maybe_reenter_make_fx(joint_graph)( + *bw_example_vals, *score_mod_other_buffers + ) + mask_graph = _maybe_reenter_make_fx(mask_graph)( + *mask_example_vals, *mask_mod_other_buffers + ) + block_mask = block_mask[:-1] + (mask_graph,) + example_out = flex_attention_backward( + 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, + ) + + if not isinstance(proxy_mode.tracer, torch.fx.Tracer): + raise AssertionError( + f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}" + ) + + qualname = proxy_mode.tracer.get_fresh_qualname("fw_graph") + proxy_mode.tracer.root.register_module(qualname, fw_graph) # type: ignore[arg-type] + qualname = proxy_mode.tracer.get_fresh_qualname("joint_graph") + proxy_mode.tracer.root.register_module(qualname, joint_graph) + qualname = proxy_mode.tracer.get_fresh_qualname("mask_graph") + proxy_mode.tracer.root.register_module(qualname, mask_graph) + + node_args = ( + 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, + ) + # pyrefly: ignore [missing-attribute] + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", + flex_attention_backward, + proxy_args, + {}, + name="flex_attention_backward", + ) + return track_tensor_tree( + example_out, + out_proxy, + constant=None, + tracer=proxy_mode.tracer, + ) + + +@flex_attention_backward.py_impl(ProxyTorchDispatchMode) +def flex_attention_backward_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor, + grad_logsumexp: torch.Tensor, + fw_graph: Callable | GraphModule, + joint_graph: GraphModule, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]: + if mode is None: + raise AssertionError("Mode should always be enabled for python fallback key") + with torch.fx.experimental.proxy_tensor.set_original_aten_op( + flex_attention_backward + ): + return trace_flex_attention_backward( + mode, + 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, + ) + + +@flex_attention_backward.py_functionalize_impl +def flex_attention_backward_functionalize( + ctx: torch._subclasses.functional_tensor.BaseFunctionalizeAPI, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor, + grad_logsumexp: torch.Tensor, + fw_graph: Callable | GraphModule, + joint_graph: GraphModule, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]: + """Defines the functionalization rules for the flex_attention operator. + + Right now we are unwrapping each tensor and then redispatching to the next, + since we know that the forward score mod function is assured to be free of mutations + to the other_buffers, we skip that mutate check and go straight to redispatching. + """ + + query_unwrapped = ctx.unwrap_tensors(query) + key_unwrapped = ctx.unwrap_tensors(key) + value_unwrapped = ctx.unwrap_tensors(value) + out_unwrapped = ctx.unwrap_tensors(out) + logsumexp_unwrapped = ctx.unwrap_tensors(logsumexp) + grad_out_unwrapped = ctx.unwrap_tensors(grad_out) + grad_logsumexp_unwrapped = ctx.unwrap_tensors(grad_logsumexp) + block_mask_unwrapped = ctx.unwrap_tensors(block_mask) + score_mod_other_buffers_unwrapped = ctx.unwrap_tensors(score_mod_other_buffers) + mask_mod_other_buffers_unwrapped = ctx.unwrap_tensors(mask_mod_other_buffers) + + # Appease the mypy overlords + if not isinstance(query_unwrapped, torch.Tensor): + raise AssertionError( + f"expected query_unwrapped to be torch.Tensor, got {type(query_unwrapped)}" + ) + if not isinstance(key_unwrapped, torch.Tensor): + raise AssertionError( + f"expected key_unwrapped to be torch.Tensor, got {type(key_unwrapped)}" + ) + if not isinstance(value_unwrapped, torch.Tensor): + raise AssertionError( + f"expected value_unwrapped to be torch.Tensor, got {type(value_unwrapped)}" + ) + if not isinstance(out_unwrapped, torch.Tensor): + raise AssertionError( + f"expected out_unwrapped to be torch.Tensor, got {type(out_unwrapped)}" + ) + if not isinstance(logsumexp_unwrapped, torch.Tensor): + raise AssertionError( + f"expected logsumexp_unwrapped to be torch.Tensor, got {type(logsumexp_unwrapped)}" + ) + if grad_out_unwrapped is not None and not isinstance( + grad_out_unwrapped, torch.Tensor + ): + raise AssertionError( + f"expected grad_out_unwrapped to be torch.Tensor or None, got {type(grad_out_unwrapped)}" + ) + if grad_logsumexp_unwrapped is not None and not isinstance( + grad_logsumexp_unwrapped, torch.Tensor + ): + raise AssertionError( + f"expected grad_logsumexp_unwrapped to be torch.Tensor or None, got {type(grad_logsumexp_unwrapped)}" + ) + if not isinstance(block_mask_unwrapped, tuple): + raise AssertionError( + f"expected block_mask_unwrapped to be tuple, got {type(block_mask_unwrapped)}" + ) + if not isinstance(score_mod_other_buffers_unwrapped, tuple): + raise AssertionError( + f"expected score_mod_other_buffers_unwrapped to be tuple, got {type(score_mod_other_buffers_unwrapped)}" + ) + if not isinstance(mask_mod_other_buffers_unwrapped, tuple): + raise AssertionError( + f"expected mask_mod_other_buffers_unwrapped to be tuple, got {type(mask_mod_other_buffers_unwrapped)}" + ) + + with ctx.redispatch_to_next(): + # pyrefly: ignore [bad-argument-type] + functional_fw_graph = ctx.functionalize(fw_graph) + # pyrefly: ignore [bad-argument-type] + functional_joint_graph = ctx.functionalize(joint_graph) + + ( + grad_query, + grad_key, + grad_value, + grad_score_mod_captured, + ) = flex_attention_backward( + query_unwrapped, + key_unwrapped, + value_unwrapped, + out_unwrapped, + logsumexp_unwrapped, + grad_out_unwrapped, + grad_logsumexp_unwrapped, + functional_fw_graph, # type: ignore[arg-type] + functional_joint_graph, # type: ignore[arg-type] + block_mask_unwrapped, + scale, + kernel_options, + score_mod_other_buffers_unwrapped, + mask_mod_other_buffers_unwrapped, + ) + + return ctx.wrap_tensors((grad_query, grad_key, grad_value, grad_score_mod_captured)) # type: ignore[return-value,arg-type] + + +@register_fake(flex_attention_backward) +def flex_attention_backward_fake_tensor_mode( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + logsumexp: torch.Tensor, + grad_out: torch.Tensor, + grad_logsumexp: torch.Tensor, + fw_graph: Callable | GraphModule, + joint_graph: GraphModule, + block_mask: tuple, + scale: float, + kernel_options: dict[str, Any], + score_mod_other_buffers: tuple = (), + mask_mod_other_buffers: tuple = (), +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, tuple[torch.Tensor | None, ...]]: + if has_user_subclass( + ( + query, + key, + value, + out, + logsumexp, + grad_out, + grad_logsumexp, + block_mask, + scale, + kernel_options, + score_mod_other_buffers, + mask_mod_other_buffers, + ), + allowed_subclasses=(FakeTensor,), + ): + return NotImplemented + Bq, _, _, qk_head_dim = query.shape + Bkv, Hkv, seq_len_kv, v_head_dim = value.shape + + grad_query = query.new_empty(query.shape) + grad_query = _permute_strides(grad_query, query.stride()) + + grad_score_mod_captured = _new_captured_grad_buffers( + score_mod_other_buffers, joint_graph + ) + + broadcasted_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim)) + broadcasted_grad_key = _permute_strides(broadcasted_grad_key, key.stride()) + + broadcasted_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim)) + broadcasted_grad_value = _permute_strides(broadcasted_grad_value, value.stride()) + + from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_and + + # This branch chooses fake tensor metadata, including strides. Guarding is + # valid for backed symbolic sizes, while unbacked/data-dependent predicates + # conservatively fall through to the non-broadcast contract below. + if guard_or_false(sym_and(Bkv == 1, Bq > 1)): + grad_key = torch.sum(broadcasted_grad_key, dim=0, keepdim=True) + grad_value = torch.sum(broadcasted_grad_value, dim=0, keepdim=True) + else: + torch._check( + Bq == Bkv, + lambda: "grad_key/grad_value batch must match key/value batch.", + ) + grad_key = broadcasted_grad_key + grad_value = broadcasted_grad_value + + return grad_query, grad_key, grad_value, grad_score_mod_captured + + +flex_attention_backward.py_autograd_impl( + autograd_not_implemented(flex_attention_backward, deferred_error=True) +) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_gemm.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..5be03bddc15c0cb13518e68101a6797746fb4a83 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/flex_gemm.py @@ -0,0 +1,355 @@ +# mypy: allow-untyped-defs +import dataclasses +from collections.abc import Callable, Mapping +from functools import partial +from typing import Any, cast + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.inline_asm_elementwise import inline_asm_elementwise +from torch._higher_order_ops.utils import ( + _check_alias_and_mutation, + autograd_not_implemented, + reenter_make_fx, + register_fake, + unique_graph_id, +) +from torch._ops import HigherOrderOperator +from torch._prims_common import ELEMENTWISE_TYPE_PROMOTION_KIND +from torch._prims_common.wrappers import elementwise_type_promotion_wrapper +from torch._subclasses.fake_tensor import is_fake +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree + + +@dataclasses.dataclass(frozen=True) +class FlexGemmOpSpec: + """Canonical operand positions for a supported FlexGEMM op.""" + + name: str + mat1_index: int + mat2_index: int + input_ndim: int + bias_index: int | None = None + + +FLEX_GEMM_OP_SPECS = { + torch.ops.aten.mm.default: FlexGemmOpSpec("mm", 0, 1, input_ndim=2), + torch.ops.aten.addmm.default: FlexGemmOpSpec( + "addmm", 1, 2, input_ndim=2, bias_index=0 + ), + torch.ops.aten.bmm.default: FlexGemmOpSpec("bmm", 0, 1, input_ndim=3), + torch.ops.aten.baddbmm.default: FlexGemmOpSpec( + "baddbmm", 1, 2, input_ndim=3, bias_index=0 + ), +} +FLEX_GEMM_OP_ALIASES = { + torch.mm: torch.ops.aten.mm.default, + torch.addmm: torch.ops.aten.addmm.default, + torch.bmm: torch.ops.aten.bmm.default, + torch.baddbmm: torch.ops.aten.baddbmm.default, +} +_SUPPORTED_BACKENDS = {"NVGEMM", "QUACK", "TRITON"} + + +_SUPPORTED_FLEX_GEMM_OP_NAMES = "/".join( + spec.name for spec in FLEX_GEMM_OP_SPECS.values() +) +_PRESERVE_FLEX_GEMM_GEMM_OP = "preserve_flex_gemm_gemm_op" + +# Note [Preserving FlexGEMM body GEMMs] +# FlexGEMM lowering materializes the captured epilogue by finding the body GEMM +# node whose target matches the HOP-carried gemm_op. Generic graph passes can +# rewrite batch-size-1 bmm into mm(...).unsqueeze(0), which removes the matching +# node. This body pass tags FlexGEMM GEMM nodes so bmm_to_mm in joint_graph.py +# skips them. + + +def mark_flex_gemm_body_gemm_node( + body_graph: torch.fx.GraphModule, gemm_op: torch._ops.OpOverload +) -> None: + """Mark body GEMMs so Inductor's batch-1 bmm rewrite keeps them matchable.""" + for node in body_graph.graph.find_nodes(op="call_function", target=gemm_op): + node.meta[_PRESERVE_FLEX_GEMM_GEMM_OP] = True + + +FLEX_GEMM_BODY_GRAPH_PASSES: tuple[ + Callable[[torch.fx.GraphModule, torch._ops.OpOverload], None], ... +] = (mark_flex_gemm_body_gemm_node,) + + +@elementwise_type_promotion_wrapper( + type_promoting_args=("x",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +) +def flex_gemm_fast_math_sigmoid(x: torch.Tensor) -> torch.Tensor: + """Use the tanh sigmoid identity selected by QUACK fast math.""" + return torch.tanh(x * 0.5) * 0.5 + 0.5 + + +@elementwise_type_promotion_wrapper( + type_promoting_args=("x",), + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, +) +def flex_gemm_fast_math_silu(x: torch.Tensor) -> torch.Tensor: + """Use the tanh SiLU identity selected by QUACK fast math.""" + half = x * 0.5 + return half * torch.tanh(half) + half + + +def flex_gemm_fast_math_gelu( + x: torch.Tensor, + approximate: str = "none", + *, + fallback: Callable[..., Any], +) -> torch.Tensor: + """Select the standard tanh GELU approximation for exact GELU calls.""" + if approximate == "none": + approximate = "tanh" + return fallback(x, approximate) + + +FLEX_GEMM_FAST_MATH_DECOMPOSITIONS: dict[torch._ops.OpOverload, Callable[..., Any]] = { + torch.ops.aten.sigmoid.default: flex_gemm_fast_math_sigmoid, + torch.ops.aten.silu.default: flex_gemm_fast_math_silu, +} + + +def flex_gemm_body_decomposition_table( + kernel_options: dict[str, Any], + decomposition_table: Mapping[torch._ops.OpOverload, Callable[..., Any]], +) -> dict[torch._ops.OpOverload, Callable[..., Any]] | None: + """Override composite body decompositions enabled by QUACK fast math.""" + if ( + kernel_options.get("backend") != "QUACK" + or kernel_options.get("fast_math") is not True + ): + return None + merged_decompositions = dict(decomposition_table) + merged_decompositions.update(FLEX_GEMM_FAST_MATH_DECOMPOSITIONS) + gelu = torch.ops.aten.gelu.default + if gelu in merged_decompositions: + merged_decompositions[gelu] = partial( + flex_gemm_fast_math_gelu, fallback=merged_decompositions[gelu] + ) + return merged_decompositions + + +def nvfp4_pack(input: torch.Tensor) -> torch.Tensor: + """Pack adjacent Float32 values into E2M1x2 storage for FlexGEMM tests. + + This private helper lets tests spell the intended epilogue with public inline + assembly while a blessed user-facing quantization API is still being decided. + The last dimension is one low/high pair: the PTX x2 conversion consumes both + values and emits one byte, whose same-width dtype view supplies the logical + ``torch.float4_e2m1fn_x2`` type without changing storage. + """ + if input.dtype is not torch.float32 or input.ndim == 0 or input.shape[-1] != 2: + raise ValueError( + "NVFP4 pack input must be Float32 with innermost dimension 2, " + f"got dtype={input.dtype}, shape={tuple(input.shape)}" + ) + if torch.compiler.is_compiling() or is_fake(input): + low = input[..., 0] + high = input[..., 1] + packed = inline_asm_elementwise( + high, + low, + asm_str=( + "{ .reg .b8 packed; " + "cvt.rn.satfinite.e2m1x2.f32 packed, $1, $2; " + "cvt.u32.u8 $0, packed; }" + ), + constraints="=r,r,r", + dtype=torch.uint8, + ) + return packed.contiguous().view(torch.float4_e2m1fn_x2) + + # Eager path is mostly for testing. + input_bits = input.view(torch.int32) + sign = input_bits & 0x80000000 + magnitude = (input_bits ^ sign).view(torch.float32) + saturated = magnitude >= 6.0 + denormal = (~saturated) & (magnitude < 1.0) + normal = ~(saturated | denormal) + denormal_code = ((magnitude + 4194304.0).view(torch.int32) - 1249902592).to( + torch.uint8 + ) + normal_bits = magnitude.view(torch.int32) + mantissa_odd = (normal_bits >> 22) & 1 + normal_code = ((normal_bits - 1054867457 + mantissa_odd) >> 22).to(torch.uint8) + codes = torch.full_like(magnitude, 7, dtype=torch.uint8) + codes = torch.where(denormal, denormal_code, codes) + codes = torch.where(normal, normal_code, codes) + codes = codes | (((sign >> 28).to(torch.uint8)) & 8) + packed = (codes[..., 1] << 4) | codes[..., 0] + return packed.contiguous().view(torch.float4_e2m1fn_x2) + + +def apply_flex_gemm_body_graph_passes( + body_graph: torch.fx.GraphModule, gemm_op: torch._ops.OpOverload +) -> None: + """Apply FlexGEMM body annotations before generic Inductor graph passes.""" + for graph_pass in FLEX_GEMM_BODY_GRAPH_PASSES: + graph_pass(body_graph, gemm_op) + + +class FlexGemm(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("flex_gemm") + + def __call__( + self, + gemm_op: torch._ops.OpOverload, + body_fn: Callable[..., Any], + gemm_args: tuple[Any, ...], + gemm_kwargs: dict[str, Any], + kernel_options: dict[str, Any], + ) -> Any: + if gemm_op not in FLEX_GEMM_OP_SPECS: + raise RuntimeError(f"unsupported GEMM op for FlexGEMM: {gemm_op}") + if not isinstance(gemm_args, (tuple, list)): + raise RuntimeError(f"gemm_args must be a tuple/list, got {type(gemm_args)}") + gemm_args = tuple(gemm_args) + if not all( + isinstance( + arg, + ( + torch.Tensor, + torch.SymInt, + torch.SymFloat, + torch.SymBool, + int, + float, + bool, + ), + ) + for arg in gemm_args + ): + raise RuntimeError( + "gemm_args must be a tuple of tensors, SymInts, SymFloats, " + f"SymBools, ints, floats, or bools, got {gemm_args}" + ) + if not isinstance(gemm_kwargs, dict): + raise RuntimeError(f"gemm_kwargs must be a dict, got {type(gemm_kwargs)}") + if any( + isinstance(value, torch.Tensor) for value in pytree.tree_leaves(gemm_kwargs) + ): + raise RuntimeError( + "gemm_kwargs must not contain tensor values; pass tensor inputs through gemm_args" + ) + if not isinstance(kernel_options, dict): + raise RuntimeError( + f"kernel_options must be a dict, got {type(kernel_options)}" + ) + + kernel_options = dict(kernel_options) + kernel_options.setdefault("backend", "TRITON") + backend = kernel_options["backend"] + if backend not in _SUPPORTED_BACKENDS: + raise RuntimeError( + f"unsupported FlexGEMM backend: {backend}; " + f"expected one of {sorted(_SUPPORTED_BACKENDS)}" + ) + return super().__call__( + gemm_op, body_fn, gemm_args, gemm_kwargs, kernel_options + ) + + +flex_gemm_hop = FlexGemm() + + +def flex_gemm( + gemm_op: Callable[..., Any], + gemm_args: tuple[Any, ...], + epilogue_fn: Callable[[Any], Any], + *, + gemm_kwargs: dict[str, Any] | None = None, + kernel_options: dict[str, Any] | None = None, +) -> Any: + if gemm_kwargs is None: + gemm_kwargs = {} + if kernel_options is None: + kernel_options = {} + gemm_op = cast(torch._ops.OpOverload, FLEX_GEMM_OP_ALIASES.get(gemm_op, gemm_op)) + + def body_fn(*args: Any) -> Any: + # Keep the traced body positional-only; the HOP carries gemm_kwargs for lowering. + return epilogue_fn(gemm_op(*args, **gemm_kwargs)) + + return flex_gemm_hop(gemm_op, body_fn, gemm_args, gemm_kwargs, kernel_options) + + +@flex_gemm_hop.py_impl(DispatchKey.CompositeExplicitAutograd) +def flex_gemm_dense(gemm_op, body_fn, args, kwargs, kernel_options): + return body_fn(*args) + + +flex_gemm_hop.py_autograd_impl( + autograd_not_implemented(flex_gemm_hop, deferred_error=True) +) + + +@register_fake(flex_gemm_hop) +def flex_gemm_fake_tensor_mode(gemm_op, body_fn, args, kwargs, kernel_options): + return body_fn(*args) + + +@flex_gemm_hop.py_functionalize_impl +def flex_gemm_functionalize(ctx, gemm_op, body_fn, args, kwargs, kernel_options): + unwrapped_args = ctx.unwrap_tensors(args) + with ctx.redispatch_to_next(): + _check_alias_and_mutation( + body_fn, + unwrapped_args, + "flex_gemm", + hasattr(ctx, "mode") and ctx.mode.pre_dispatch, + ) + return ctx.wrap_tensors( + flex_gemm_hop( + gemm_op, + ctx.functionalize(body_fn), + unwrapped_args, + ctx.unwrap_tensors(kwargs), + ctx.unwrap_tensors(kernel_options), + ) + ) + + +@flex_gemm_hop.py_impl(ProxyTorchDispatchMode) +def flex_gemm_proxy_torch_dispatch_mode( + proxy_mode, gemm_op, body_fn, args, kwargs, kernel_options +): + if proxy_mode.enable_tracing: + flat_args = tuple(args) + + def tracing_body_fn(*flat_body_args): + return body_fn(*flat_body_args) + + body_graph = reenter_make_fx( + tracing_body_fn, + subgraph_decomp_table=flex_gemm_body_decomposition_table( + kernel_options, proxy_mode.decomposition_table + ), + )(*flat_args) + apply_flex_gemm_body_graph_passes(body_graph, gemm_op) + _, body_graph_name = unique_graph_id(proxy_mode, prefix="flex_gemm_body_graph") + proxy_mode.tracer.root.register_module(body_graph_name, body_graph) + proxy_args = pytree.tree_map( + proxy_mode.tracer.unwrap_proxy, + (gemm_op, body_graph, flat_args, kwargs, kernel_options), + ) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", + flex_gemm_hop, + proxy_args, + {}, + name="flex_gemm", + ) + return track_tensor_tree( + body_fn(*flat_args), + out_proxy, + constant=None, + tracer=proxy_mode.tracer, + ) + return flex_gemm_hop(gemm_op, body_fn, args, kwargs, kernel_options) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/foreach_map.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/foreach_map.py new file mode 100644 index 0000000000000000000000000000000000000000..0d02515d555d3be737011bd4cab32393acbe5b07 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/foreach_map.py @@ -0,0 +1,24 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +from collections.abc import Callable +from typing import Any + +from torch._higher_order_ops.base_hop import BaseHOP, FunctionWithNoFreeVars + + +class ForeachMap(BaseHOP): + def __init__(self): + super().__init__("foreach_map") + + def __call__(self, fn, *operands, **kwargs): # type: ignore[override] + fn = FunctionWithNoFreeVars(fn) + return super().__call__(fn, *operands, **kwargs) + + +_foreach_map = ForeachMap() + + +def foreach_map(op: Callable, *operands: Any, **kwargs: dict[str, Any]): + from torch._dynamo.polyfills import foreach_map_fn + + return _foreach_map(foreach_map_fn, op, *operands, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/hints_wrap.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/hints_wrap.py new file mode 100644 index 0000000000000000000000000000000000000000..925e1f5d946b5c74fdf1d928a11f9ad11e59b498 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/hints_wrap.py @@ -0,0 +1,141 @@ +# mypy: allow-untyped-defs +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + autograd_not_implemented, + reenter_make_fx, + register_fake, + unique_graph_id, +) +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree + + +# used for wrapping a function/op with context hints +class HintsWrapper(HigherOrderOperator): + def __init__(self): + super().__init__("hints_wrapper") + + def __call__(self, body_fn, args, kwargs, hints): + r""" + Call implementation of hints_wrapper + + Args: + body_fn (Callable): A callable function that is within the scope + that is being traced. + + args (Tuple of torch.Tensor/int/float/bool): A tuple of inputs to + body_fn. + + kwargs (dict): Keyword argument to the body_fn. + + hints (dict): A dict of context hints which could be passed to + backend compiler. + """ + if not isinstance(args, tuple): + args = tuple(args) + + if not all(isinstance(t, (torch.Tensor, int, float, bool)) for t in args): + raise RuntimeError( + f"args must be a tuple of tensors, ints, floats, or bools, got {args}" + ) + + if not isinstance(kwargs, dict): + raise RuntimeError(f"kwargs must be a dict, got {type(kwargs)}") + + if len(kwargs) > 0: + raise RuntimeError( + f"kwargs except for hints are not supported, got {kwargs}" + ) + + if not isinstance(hints, dict): + raise RuntimeError(f"hints must be a dict, got {type(hints)}") + + for k, v in hints.items(): + if not isinstance(k, str): + raise RuntimeError(f"hints key must be a str, got {k}.") + + if not isinstance(v, (int, float, bool, str)): + raise RuntimeError( + "hints must be a dict containing int, float, bool or str " + f"value, got value {v} for key {k}." + ) + + # pyrefly: ignore [missing-attribute] + return super().__call__(body_fn, args, kwargs, hints) + + +hints_wrapper = HintsWrapper() + + +@hints_wrapper.py_impl(DispatchKey.CompositeExplicitAutograd) +def hints_wrapper_dense(body_fn, args, kwargs, hints): + return body_fn(*args, **kwargs) + + +hints_wrapper.py_autograd_impl( + autograd_not_implemented(hints_wrapper, deferred_error=True) +) + + +@register_fake(hints_wrapper, skip_cache=True) +def hints_wrapper_fake_tensor_mode(body_func, args, kwargs, hints): + flat_args = pytree.tree_leaves(args) + return body_func(*flat_args, **kwargs) + + +@hints_wrapper.py_functionalize_impl +def hints_wrapper_functionalize(ctx, body_fn, args, kwargs, hints): + from torch._higher_order_ops.utils import _check_alias_and_mutation + + unwrapped_args = ctx.unwrap_tensors(args) + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) + unwrapped_hints = ctx.unwrap_tensors(hints) + with ctx.redispatch_to_next(): + functional_body_fn = ctx.functionalize(body_fn) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + _check_alias_and_mutation( + body_fn, unwrapped_args, "hints_wrapper", pre_dispatch + ) + + outputs = hints_wrapper( + functional_body_fn, + unwrapped_args, + unwrapped_kwargs, + unwrapped_hints, + ) + return ctx.wrap_tensors(outputs) + + +def trace_hints_wrapper(proxy_mode, hints_wrapper, body_fn, args, kwargs, hints): + flat_args = tuple(pytree.tree_leaves(args)) + body_graph = reenter_make_fx(body_fn)(*flat_args, **kwargs) + + _, body_graph_name = unique_graph_id(proxy_mode, prefix="hints_wrapper_body_graph") + proxy_mode.tracer.root.register_module(body_graph_name, body_graph) + + new_args: tuple = (body_graph, flat_args, {}) + # merge hints into kwargs + new_kwargs = {} + new_kwargs["hints"] = hints + + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, new_args) + proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, new_kwargs) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", hints_wrapper, proxy_args, proxy_kwargs, name="hints_wrapper" + ) + + out = body_fn(*flat_args, **kwargs) + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@hints_wrapper.py_impl(ProxyTorchDispatchMode) +def inner(proxy_mode, body_fn, args, kwargs, hints): + if proxy_mode.enable_tracing: + return trace_hints_wrapper( + proxy_mode, hints_wrapper, body_fn, args, kwargs, hints + ) + else: + return hints_wrapper(body_fn, args, kwargs, hints) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/inline_asm_elementwise.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/inline_asm_elementwise.py new file mode 100644 index 0000000000000000000000000000000000000000..039b220841f7e8caa27b45b7938fecd27653ff2c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/inline_asm_elementwise.py @@ -0,0 +1,297 @@ +# mypy: allow-untyped-defs +import functools +import re + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import autograd_not_implemented, register_fake +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree + + +__all__ = ["inline_asm_elementwise"] + + +class InlineAsmElementwiseOp(HigherOrderOperator): + """Execute inline PTX assembly elementwise over tensors. + + This is an elementwise map where the function body is inline assembly. + Input tensors are implicitly broadcast to the same shape. + + Each invocation of the inline asm processes ``pack`` elements at a time. + Exactly which set of inputs a given invocation receives is unspecified. + + Output strides follow PyTorch's standard pointwise striding propagation + rules. + + In eager mode, the assembly is executed via the CUDA Jiterator. Under + ``torch.compile`` the assembly is lowered to Triton's + ``tl.inline_asm_elementwise`` via Inductor, which allows fusion with + surrounding operators. + + Args: + *inputs: Input tensors whose values are passed to the asm block. + asm_str: PTX assembly string. Operands use ``$N`` syntax + (e.g. ``$0`` for the first output, ``$1`` for the first input). + constraints: Inline-asm constraints in LLVM format. Output constraints + are prefixed with ``=`` (e.g. ``"=f,f,f"`` for one float output + and two float inputs). + dtype: Element type of the returned tensor. + is_pure: Must be ``True``. If true, the compiler may assume the asm + block has no side-effects. + pack: Number of elements processed per asm invocation. When + ``pack > 1``, the constraint string must list ``pack`` outputs + and ``pack`` copies of each input. Requires ``torch.compile``. + + Returns: + A tensor with the broadcast shape of the inputs and the given dtype. + + Example:: + + >>> # xdoctest: +SKIP(requires CUDA) + >>> # Float32 fused multiply-add via PTX + >>> result = inline_asm_elementwise( + ... a, b, c, + ... asm_str="fma.rn.f32 $0, $1, $2, $3;", + ... constraints="=f,f,f,f", + ... dtype=torch.float32, + ... ) + + >>> # xdoctest: +SKIP(requires CUDA) + >>> # pack=2: each asm invocation processes two elements + >>> result = inline_asm_elementwise( + ... x, + ... asm_str="mov.b32 $0, $2; mov.b32 $1, $3;", + ... constraints="=r,=r,r,r", + ... dtype=torch.float32, + ... pack=2, + ... ) + """ + + def __init__(self): + super().__init__("inline_asm_elementwise") + + def __call__( + self, + *inputs: torch.Tensor, + asm_str: str, + constraints: str, + dtype: torch.dtype, + is_pure: bool = True, + pack: int = 1, + ) -> torch.Tensor: + if not is_pure: + raise ValueError("inline_asm_elementwise only supports is_pure=True") + # pyrefly: ignore [missing-attribute] + return super().__call__( + *inputs, + asm_str=asm_str, + constraints=constraints, + dtype=dtype, + is_pure=True, + pack=pack, + ) + + +inline_asm_elementwise = InlineAsmElementwiseOp() + + +def _parse_constraints(constraints: str) -> tuple[int, int]: + parts = [p.strip() for p in constraints.split(",")] + n_outputs = sum(1 for p in parts if p.startswith("=")) + n_inputs = len(parts) - n_outputs + return n_outputs, n_inputs + + +_DTYPE_TO_CUDA_TYPE = { + torch.float32: "float", + torch.float64: "double", + torch.float16: "__half", + torch.bfloat16: "__nv_bfloat16", + torch.int32: "int", + torch.int64: "long long", + torch.int16: "short", + torch.int8: "signed char", + torch.uint8: "unsigned char", + torch.uint16: "unsigned short", + torch.uint32: "unsigned int", + torch.bool: "bool", +} + + +_TRITON_ARG_RE = re.compile(r"\$(\d+)") + + +def _triton_asm_to_cuda_asm(asm_str: str) -> str: + return _TRITON_ARG_RE.sub(r"%\1", asm_str) + + +@functools.lru_cache +def _get_jiterator_fn( + asm_str: str, + constraints: str, + n_inputs: int, + input_dtype: torch.dtype, + output_dtype: torch.dtype, +): + from torch.cuda.jiterator import _create_jit_fn + + cuda_asm = _triton_asm_to_cuda_asm(asm_str) + + constraint_parts = [p.strip() for p in constraints.split(",")] + output_constraints = [p.lstrip("=") for p in constraint_parts if p.startswith("=")] + input_constraints = [p for p in constraint_parts if not p.startswith("=")] + + if input_dtype not in _DTYPE_TO_CUDA_TYPE: + raise ValueError(f"Unsupported input dtype for inline asm: {input_dtype}") + if output_dtype not in _DTYPE_TO_CUDA_TYPE: + raise ValueError(f"Unsupported output dtype for inline asm: {output_dtype}") + + input_type = _DTYPE_TO_CUDA_TYPE[input_dtype] + output_type = _DTYPE_TO_CUDA_TYPE[output_dtype] + + input_params = ", ".join(f"{input_type} in{i}" for i in range(n_inputs)) + out_constraints_str = ", ".join(f'"={c}"(result)' for c in output_constraints) + in_constraints_str = ", ".join( + f'"{c}"(in{i})' for i, c in enumerate(input_constraints) + ) + escaped_asm = ( + cuda_asm.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + ) + + code = f""" +template +{output_type} inline_asm_kernel({input_params}) {{ + {output_type} result; + asm volatile ( + "{escaped_asm}" + : {out_constraints_str} + : {in_constraints_str} + ); + return result; +}} +""" + + return _create_jit_fn(code) + + +def _inline_asm_dense(*inputs, asm_str, constraints, dtype, is_pure, pack): + if not inputs: + raise ValueError("inline_asm_elementwise requires at least one input tensor") + + inputs = torch.broadcast_tensors(*inputs) + + if not inputs[0].is_cuda: + raise RuntimeError("inline_asm_elementwise only supports CUDA tensors") + + if pack > 1: + raise RuntimeError( + "inline_asm_elementwise with pack > 1 requires torch.compile" + ) + + n_outputs, n_inputs = _parse_constraints(constraints) + + if n_outputs != 1: + raise ValueError(f"Expected 1 output constraint, got {n_outputs}") + + if n_inputs != len(inputs): + raise ValueError( + f"Constraint string specifies {n_inputs} inputs but got " + f"{len(inputs)} tensor(s)" + ) + + # Jiterator generates a single input type for all inputs — mixed dtypes + # would produce incorrect CUDA code. + input_dtypes = {inp.dtype for inp in inputs} + if len(input_dtypes) > 1: + raise ValueError( + f"All inputs must have the same dtype for eager execution, " + f"got {sorted(str(d) for d in input_dtypes)}" + ) + + jit_fn = _get_jiterator_fn( + asm_str=asm_str, + constraints=constraints, + n_inputs=len(inputs), + input_dtype=inputs[0].dtype, + output_dtype=dtype, + ) + + return jit_fn(*inputs) + + +@inline_asm_elementwise.py_impl(DispatchKey.CompositeExplicitAutograd) +def _(*inputs, asm_str, constraints, dtype, is_pure=True, pack=1): + return _inline_asm_dense( + *inputs, + asm_str=asm_str, + constraints=constraints, + dtype=dtype, + is_pure=is_pure, + pack=pack, + ) + + +inline_asm_elementwise.py_autograd_impl( + autograd_not_implemented(inline_asm_elementwise, deferred_error=True) +) + + +def _elementwise_output_like(*inputs, dtype): + from torch._prims_common import compute_elementwise_output_logical_to_physical_perm + + broadcasted = torch.broadcast_tensors(*inputs) + l2p_perm, _ = compute_elementwise_output_logical_to_physical_perm(*broadcasted) + return torch.empty_permuted( + broadcasted[0].shape, l2p_perm, dtype=dtype, device=broadcasted[0].device + ) + + +@register_fake(inline_asm_elementwise, skip_cache=True) +def _(*inputs, asm_str, constraints, dtype, is_pure=True, pack=1): + return _elementwise_output_like(*inputs, dtype=dtype) + + +@inline_asm_elementwise.py_impl(ProxyTorchDispatchMode) +def _(mode, *inputs, asm_str, constraints, dtype, is_pure=True, pack=1): + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, inputs) + + out_proxy = mode.tracer.create_proxy( + "call_function", + inline_asm_elementwise, + proxy_args, + { + "asm_str": asm_str, + "constraints": constraints, + "dtype": dtype, + "is_pure": is_pure, + "pack": pack, + }, + name="inline_asm_elementwise", + ) + + out = inline_asm_elementwise( + *inputs, + asm_str=asm_str, + constraints=constraints, + dtype=dtype, + is_pure=is_pure, + pack=pack, + ) + return track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + + +@inline_asm_elementwise.py_functionalize_impl +def _(ctx, *inputs, asm_str, constraints, dtype, is_pure=True, pack=1): + unwrapped_inputs = ctx.unwrap_tensors(inputs) + + with ctx.redispatch_to_next(): + res = inline_asm_elementwise( + *unwrapped_inputs, + asm_str=asm_str, + constraints=constraints, + dtype=dtype, + pack=pack, + ) + return ctx.wrap_tensors(res) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_leaf_function.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_leaf_function.py new file mode 100644 index 0000000000000000000000000000000000000000..9a57edbbd91b472caa2647530981d2bba5f94761 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_leaf_function.py @@ -0,0 +1,946 @@ +import contextlib +import functools +from collections.abc import Callable, Generator, Sequence +from dataclasses import dataclass +from typing import Any, NamedTuple + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey, DispatchKeySet +from torch._custom_class_base import CustomClassBase +from torch._higher_order_ops.utils import register_fake +from torch._library.opaque_object import register_custom_class +from torch._ops import HigherOrderOperator +from torch.autograd.graph import get_gradient_edge +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.nn.utils.stateless import _reparametrize_module + + +_leaf_function_module_retriever: Callable[[int], Any] | None = None + +# Separate storage for the make_fx / _invoke_leaf_function_python path. +# We can't use Dynamo's register_user_object because it requires a Source +# (for bytecode generation) and adds entries to index_to_bytecode_constructor. +# In the make_fx path we have neither a Source nor bytecode generation, so we +# maintain our own dict keyed by negative indices to avoid collisions with +# Dynamo's non-negative indices. +_makefx_module_storage: dict[int, torch.nn.Module] = {} +_makefx_next_index = 0 + + +def store_makefx_modules(modules: list[torch.nn.Module]) -> tuple[int, ...]: + """Store modules for the make_fx path and return their assigned indices. + + Uses negative indices to avoid collisions with Dynamo's register_user_object + which uses non-negative indices. + """ + global _makefx_next_index + indices = [] + for mod in modules: + _makefx_next_index -= 1 + _makefx_module_storage[_makefx_next_index] = mod + indices.append(_makefx_next_index) + return tuple(indices) + + +def reset_makefx_module_storage() -> None: + global _makefx_next_index + _makefx_next_index = 0 + _makefx_module_storage.clear() + + +class _LeafCallable(CustomClassBase): + def __init__(self, fn: Callable) -> None: + self._fn = fn + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + return self._fn(*args, **kwargs) + + +register_custom_class(_LeafCallable, typ="symbolic") + + +def set_leaf_function_module_retriever(retriever: Callable[[int], Any]) -> None: + global _leaf_function_module_retriever + _leaf_function_module_retriever = retriever + + +class LeafModuleState(NamedTuple): + """ + In dynamo, nn.Module arguments to leaf functions are converted to this + pytree format (index, parameters, buffers). This structure is then + flattened to produce the actual inputs to invoke_leaf_function. + + At runtime, the original module is reconstructed from it. + """ + + nn_module_index: int + named_parameters: dict[str, torch.nn.Parameter] + named_buffers: dict[str, torch.Tensor] + + +def convert_modules_to_states(values: Any, module_to_index: dict[int, int]) -> Any: + """Replace nn.Module instances in a pytree with LeafModuleState objects. + + Args: + values: A pytree of values that may contain nn.Module instances. + module_to_index: Mapping from id(module) to its integer index. + """ + + def module_to_state(val: Any) -> Any: + if isinstance(val, torch.nn.Module): + return LeafModuleState( + nn_module_index=module_to_index[id(val)], + named_parameters=dict(val.named_parameters()), + named_buffers=dict(val.named_buffers()), + ) + return val + + return pytree.tree_map(module_to_state, values) + + +def _resolve_mutated_flat_indices( + fn: Callable, + mutates_args: frozenset[str], + num_flat_args: int, + input_spec: pytree.TreeSpec, +) -> str: + """Resolve mutates_args expressions to a comma-separated string of flat-arg indices. + + Each expression in mutates_args (e.g. "x", "model.running_mean") is evaluated + against sentinel values to determine which flat-arg positions are mutated. + + Example: for ``def fn(x, model)`` where model is an nn.Module with parameters + ``weight`` and ``bias``, the flat args are ``[x, nn_module_index, weight, bias]``. + Given ``mutates_args={"model.weight"}``, this assigns sentinels ``[0, 1, 2, 3]`` + to the flat args, evaluates ``model.weight`` to ``2``, and returns ``"2"``. + """ + import inspect + + class _AttrDict: + pass + + def _set_nested_attr(obj: _AttrDict, fqn: str, value: Any) -> None: + parts = fqn.split(".") + for part in parts[:-1]: + if not hasattr(obj, part): + setattr(obj, part, _AttrDict()) + obj = getattr(obj, part) + setattr(obj, parts[-1], value) + + def _lms_to_attr_dict(val: Any) -> Any: + if isinstance(val, LeafModuleState): + target = _AttrDict() + for fqn, sentinel in val.named_parameters.items(): + _set_nested_attr(target, fqn, sentinel) + for fqn, sentinel in val.named_buffers.items(): + _set_nested_attr(target, fqn, sentinel) + return target + return val + + sig = inspect.signature(fn) + sentinels = list(range(num_flat_args)) + args_struct, kwargs_struct = pytree.tree_unflatten(sentinels, input_spec) + args_eval, kwargs_eval = pytree.tree_map( + _lms_to_attr_dict, + (args_struct, kwargs_struct), + is_leaf=lambda x: isinstance(x, LeafModuleState), + ) + namespace = dict(sig.bind(*args_eval, **kwargs_eval).arguments) + + indices: list[int] = [] + for expr in mutates_args: + # Empty __builtins__ prevents access to builtins like __import__, open, exec. + result = eval(expr, {"__builtins__": {}}, namespace) + leaves = pytree.tree_leaves(result) + for sentinel in leaves: + if not isinstance(sentinel, int): + raise ValueError( + f"mutates_args expression '{expr}' resolved to a non-leaf value " + f"of type {type(sentinel).__name__}. Expressions must resolve to " + f"individual tensor positions, e.g. 'model.weight' not 'model'." + ) + indices.append(sentinel) + indices.sort() + return ",".join(str(i) for i in indices) + + +@dataclass +class GradientInfo: + """ + We need the gradient edge to trigger the autograd engine backward. + + We need the tensor metadata (size, stride, dtype, device) to create zeros when + gradient is None at runtime but required by the backward graph (because the graph + is traced with fake implementation). + """ + + edge: torch.autograd.graph.GradientEdge + size: torch.Size + stride: tuple[int, ...] + dtype: torch.dtype + device: torch.device + + +def _retrieve_module_by_index(nn_module_index: int) -> torch.nn.Module: + # Check make_fx storage first (used by _invoke_leaf_function_python). + # Fall back to the Dynamo retriever (used by the compiled path). + if nn_module_index in _makefx_module_storage: + if nn_module_index >= 0: + raise RuntimeError( + f"Expected negative nn_module_index for non-strict trace over leaf_function, but got {nn_module_index}." + ) + return _makefx_module_storage[nn_module_index] + + if _leaf_function_module_retriever is None: + raise RuntimeError("Leaf function module retriever not set.") + + mod = _leaf_function_module_retriever(nn_module_index) + if not isinstance(mod, torch.nn.Module): + raise TypeError( + f"Expected nn.Module at index {nn_module_index} for leaf function invocation, " + f"but got {type(mod).__name__}." + ) + return mod + + +def check_escaped_gradients( + outputs: Any, + inputs: Sequence[Any], + requires_grad_indices: set[int], +) -> None: + """ + Check if autograd graph depends on tensors that are not passed as explicit inputs. + + Controlled by torch._dynamo.config.leaf_function_check_escaped_gradients. + """ + if not requires_grad_indices: + return + + import torch._dynamo.config as config + + if not config.leaf_function_check_escaped_gradients: + return + + input_nodes: set[torch.autograd.graph.Node] = set() + for i, inp in enumerate(inputs): + if ( + isinstance(inp, torch.Tensor) + and i in requires_grad_indices + and inp.requires_grad + ): + edge = get_gradient_edge(inp) + if edge.node is not None: + input_nodes.add(edge.node) + + flat_outputs = outputs if isinstance(outputs, tuple) else (outputs,) + start_nodes: set[torch.autograd.graph.Node] = { + out.grad_fn + for out in flat_outputs + if isinstance(out, torch.Tensor) + and out.requires_grad + and out.grad_fn is not None + } + if not start_nodes: + return + + escaped: set[torch.autograd.graph.Node] = set() + visited: set[torch.autograd.graph.Node] = set() + stack = list(start_nodes) + + while stack: + node = stack.pop() + if node in visited or node in input_nodes: + continue + visited.add(node) + + for next_node, _ in node.next_functions: + if next_node is None or next_node in input_nodes: + continue + if not next_node.next_functions: + escaped.add(next_node) + else: + stack.append(next_node) + + if escaped: + tensor_info = [] + for node in escaped: + if hasattr(node, "variable"): + t = node.variable + tensor_info.append( + f" - Tensor(shape={list(t.shape)}, dtype={t.dtype})" + ) + tensor_details = ( + "\n".join(tensor_info) if tensor_info else " (tensor details unavailable)" + ) + + raise RuntimeError( + f"@leaf_function detected {len(escaped)} tensor(s) with requires_grad=True " + f"that are not passed as explicit inputs:\n{tensor_details}\n" + f"Gradients will not flow back to closure-captured or global tensors. " + f"Pass them as explicit arguments to the leaf function." + ) + + +@contextlib.contextmanager +def unflatten_args_with_modules( + flat_args: tuple[Any, ...], input_spec: pytree.TreeSpec +) -> Generator[tuple[list[Any] | tuple[Any, ...], dict[str, Any]], None, None]: + args, kwargs = pytree.tree_unflatten(flat_args, input_spec) + + with contextlib.ExitStack() as stack: + + def process_module_state(state: LeafModuleState) -> torch.nn.Module: + orig_module = _retrieve_module_by_index(state.nn_module_index) + stack.enter_context( + _reparametrize_module( + orig_module, + {**state.named_parameters, **state.named_buffers}, + ) + ) + return orig_module + + new_args, new_kwargs = pytree.tree_map_only( + LeafModuleState, + process_module_state, + (args, kwargs), + is_leaf=lambda x: isinstance(x, LeafModuleState), + ) + yield new_args, new_kwargs + + +def flatten_args_with_modules( + args_kwargs: tuple[Any, ...], +) -> list[Any]: + def expand_module(x: Any) -> Any: + if isinstance(x, torch.nn.Module): + return LeafModuleState( + nn_module_index=-1, + named_parameters=dict(x.named_parameters()), + named_buffers=dict(x.named_buffers()), + ) + return x + + expanded = pytree.tree_map(expand_module, args_kwargs) + return pytree.tree_leaves(expanded) + + +def make_leaf_function_wrappers( + real_fn: Callable[..., Any], + fake_fn: Callable[..., Any], + captured_out_spec: list[pytree.TreeSpec | None], +) -> tuple[Callable[..., tuple[Any, ...]], Callable[..., tuple[Any, ...]]]: + """Wrap real_fn and fake_fn to flatten outputs and capture the output TreeSpec. + + Both wrappers share the same captured output spec: the first call (typically + fake_fn during tracing) records it, and subsequent calls verify consistency. + The caller passes in a single-element list and reads captured_out_spec[0] + after the wrappers have been called. + + Used by both the Dynamo path (_call_leaf_function in torch.py) and the + make_fx path (_invoke_leaf_function_python in decorators.py). + """ + + def _wrap(fn: Callable[..., Any]) -> Callable[..., tuple[Any, ...]]: + if len(captured_out_spec) != 1: + raise RuntimeError( + f"captured_out_spec must be a single-element list, got length {len(captured_out_spec)}" + ) + + def wrapper(*args: Any, **kwargs: Any) -> tuple[Any, ...]: + out = fn(*args, **kwargs) + + flat_out, out_spec = pytree.tree_flatten(out) + if captured_out_spec[0] is None: + captured_out_spec[0] = out_spec + elif captured_out_spec[0] != out_spec: + raise AssertionError( + f"leaf_function output structure mismatch: " + f"expected {captured_out_spec[0]}, got {out_spec}. " + f"This can happen if the real function and fake function return " + f"different pytree structures (e.g., dict vs tuple, different number " + f"of elements). Ensure both functions return the same structure." + ) + return tuple(flat_out) + + return wrapper + + return _wrap(real_fn), _wrap(fake_fn) + + +def autograd_grad_with_gradient_info( + output_infos: Sequence[GradientInfo | None], + input_infos: Sequence[GradientInfo | None], + grad_outputs: Sequence[Any] | None = None, + retain_graph: bool | None = None, + create_graph: bool = False, + allow_unused: bool = False, +) -> tuple[torch.Tensor | None, ...]: + """ + Compute gradients using GradientInfo, it additionally handles the case + where input and output infos are None. + + Args: + output_infos: GradientInfo for each output (None if no grad_fn), + input_infos: GradientInfo for each input (None if not requires_grad) + grad_outputs: Gradients w.r.t. outputs + + Returns a tuple of gradients with None for inputs that don't require grad. + """ + filtered_output_edges = [] + filtered_grad_outputs = [] + for i, info in enumerate(output_infos): + if info is not None and info.edge.node is not None: + filtered_output_edges.append(info.edge) + if grad_outputs is not None: + filtered_grad_outputs.append(grad_outputs[i]) + + filtered_input_edges = [] + filtered_input_infos = [] + input_indices = [] + for i, info in enumerate(input_infos): + if info is not None: + filtered_input_edges.append(info.edge) + filtered_input_infos.append(info) + input_indices.append(i) + + if not filtered_output_edges or not filtered_input_edges: + return tuple(None for _ in input_infos) + + grads = torch.autograd.grad( + outputs=filtered_output_edges, + inputs=filtered_input_edges, + grad_outputs=filtered_grad_outputs if grad_outputs is not None else None, + retain_graph=retain_graph, + create_graph=create_graph, + allow_unused=allow_unused, + ) + + # Reconstruct full gradient tuple with Nones at proper positions. + # + # NB: For unused inputs that require grad, we return zeros instead of None. + # This is necessary because during AOT tracing, we use fake_impl to determine + # the backward graph structure. fake_impl may not accurately reflect which + # inputs are truly used for gradients in real_impl. For example, users often + # write fake_impl by returning torch.empty_like(input) to get the right shape + # without actually using the input in a differentiable computation. So we must + # be permissive and assume all inputs with requires_grad=True could need + # gradients. When multiple invoke_leaf_function calls share an input (e.g., + # a module's forward + hook both receiving the same tensor), the traced + # backward graph generates explicit add operations to accumulate their + # gradients. At runtime, if one leaf function doesn't actually use the input, + # autograd.grad returns None for it, and the traced add(grad1, grad2) fails + # because one operand is None. Returning zeros ensures the add always works. + result: list[torch.Tensor | None] = [None] * len(input_infos) + for filtered_idx, original_idx in enumerate(input_indices): + grad = grads[filtered_idx] + if grad is None: + info = filtered_input_infos[filtered_idx] + grad = torch.empty_strided( + info.size, info.stride, dtype=info.dtype, device=info.device + ).zero_() + result[original_idx] = grad + + return tuple(result) + + +def _make_forward( + fn: Callable, + include_keys: DispatchKeySet, + exclude_keys: DispatchKeySet, +) -> tuple[Callable, dict[str, Any]]: + state: dict[str, Any] = {"inputs": None, "outputs": None} + + @functools.wraps(fn) + def forward(*args, **kwargs): + effective_keys = include_keys + if include_keys.has(DispatchKey.PythonDispatcher): + effective_keys = effective_keys.remove(DispatchKey.PythonDispatcher) + if effective_keys.has(DispatchKey.Python): + effective_keys = effective_keys.remove(DispatchKey.Python) + with torch._C._ForceDispatchKeyGuard(effective_keys, exclude_keys): + with torch.enable_grad(): + outputs = fn(*args, **kwargs) + + flat_inputs = flatten_args_with_modules((args, kwargs)) + requires_grad_indices = { + i + for i, inp in enumerate(flat_inputs) + if isinstance(inp, torch.Tensor) and inp.requires_grad + } + check_escaped_gradients(outputs, flat_inputs, requires_grad_indices) + + state["inputs"] = tuple( + GradientInfo( + edge=get_gradient_edge(inp), + size=inp.size(), + stride=inp.stride(), + dtype=inp.dtype, + device=inp.device, + ) + if isinstance(inp, torch.Tensor) and inp.requires_grad + else None + for inp in flat_inputs + ) + + if outputs is None: + state["outputs"] = () + else: + state["outputs"] = tuple( + GradientInfo( + edge=get_gradient_edge(out), + size=out.size(), + stride=out.stride(), + dtype=out.dtype, + device=out.device, + ) + if isinstance(out, torch.Tensor) + and out.requires_grad + and out.grad_fn is not None + else None + for out in outputs + ) + + return pytree.tree_map_only( + torch.Tensor, + lambda t: t.detach().requires_grad_(t.requires_grad), + outputs, + ) + + return forward, state + + +class InvokeLeafFunction(HigherOrderOperator): + def __init__(self): + super().__init__("invoke_leaf_function", supports_training_input_mutation=True) + + def __call__( + self, + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices="", + ): + """ + real_fn_callable: _LeafCallable wrapping the real function + fake_fn_callable: _LeafCallable wrapping the fake function + input_spec: pytree.TreeSpec for unflattening flat_args back to (args, kwargs) + mutated_arg_indices: comma-separated string of flat-arg indices that are + declared as mutated (e.g. "1,2"), or "" for no mutations. Encoded as a + string so it is a pytree leaf for the HOP schema infrastructure. + requires_grad_indices: comma-separated string of flat-arg indices that + require grad (e.g. "0,1"), or "" for none. + """ + return super().__call__( # type: ignore[attr-defined] + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices=requires_grad_indices, + ) + + # pyrefly: ignore [bad-override] + def gen_schema( + self, + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices="", + ): + from torch._higher_order_ops.schema import HopSchemaGenerator + from torch._higher_order_ops.utils import _maybe_fake_prop_ignore_unbacked + from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing + + mutated_set = _parse_mutated_arg_indices(mutated_arg_indices) + + with disable_proxy_modes_tracing(): + if mutated_set: + schema_flat_args = tuple( + arg.detach().clone() + if isinstance(arg, torch.Tensor) and i in mutated_set + else arg + for i, arg in enumerate(flat_args) + ) + else: + schema_flat_args = flat_args + + def run_fake(*unfunc_flat_args): + with unflatten_args_with_modules(unfunc_flat_args, input_spec) as ( + args, + kwargs, + ): + return fake_fn_callable(*args, **kwargs) + + fake_outputs = _maybe_fake_prop_ignore_unbacked(run_fake, schema_flat_args) + + gen = HopSchemaGenerator(self) + gen.add_arg("real_fn_callable", real_fn_callable) + gen.add_arg("fake_fn_callable", fake_fn_callable) + gen.add_arg("input_spec", input_spec) + gen.add_arg("mutated_arg_indices", mutated_arg_indices) + for i, arg in enumerate(flat_args): + gen.add_arg(f"arg{i}", arg, is_mutated=i in mutated_set) + gen.add_arg( + "requires_grad_indices", + requires_grad_indices, + default_value="", + kw_only=True, + ) + + if isinstance(fake_outputs, tuple): + for out in fake_outputs: + gen.add_output(out) + else: + if fake_outputs is not None: + raise AssertionError( + f"Expected fake_outputs to be a tuple or None, got {type(fake_outputs)}" + ) + gen.add_output(fake_outputs) + + return gen.gen_schema() + + +invoke_leaf_function = InvokeLeafFunction() + + +# NOTE: [Autograd support for invoke_leaf_function] +# +# The overall idea is that when the real forward executes, we are going to build an autograd graph +# and save it. When the real backward executes, we are going to invoke the autograd graph. +# We need to build these "real_forward" and "real_backward" functions from the "real_fn". +# +# Inputs: +# real_fn_callable/fake_fn_callable are _LeafCallable objects that wrap real_fn and fake_fn. +# These functions were created in dynamo by wrapping the user's original leaf function and fake function: +# - They accept *flat_args (flattened LeafModuleState objects + other args) +# - They unflatten flat_args and convert LeafModuleState back to nn.Modules +# - They call the user's original leaf function with the reconstructed args +# - They return the user function's outputs +# +# We wrap real_fn (via _make_forward) to handle autograd properly: +# 1. Detach inputs and outputs to isolate the leaf function's autograd graph from the +# outer graph (gradients flow through our backward, not internal ops) +# 2. Real function is invoked at backend dispatch keys (i.e. CompositeExplicitAutograd) +# where autograd is disabled. We re-enable grad and restore dispatch keys for the autograd engine to work. +# 3. Store GradientInfo (gradient edges + tensor metadata) instead of full tensors for backward, +# which is sufficient for autograd.grad and avoids keeping tensors alive. +# +# We automatically generate backward functions: +# - real_backward uses the stored input/output GradientInfo and invokes the autograd engine +# - fake_backward creates empty gradients for inputs that requires grad + + +class InvokeLeafFunctionAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + ): + include_keys = torch._C._dispatch_tls_local_include_set() + exclude_keys = torch._C._dispatch_tls_local_exclude_set() + + requires_grad_indices = ",".join( + str(i) + for i, arg in enumerate(flat_args) + if isinstance(arg, torch.Tensor) and arg.requires_grad + ) + + real_forward, real_state = _make_forward( + real_fn_callable, include_keys, exclude_keys + ) + + def real_backward(*grads): + if real_state["inputs"] is None or real_state["outputs"] is None: + raise RuntimeError( + "invoke_leaf_function backward expects inputs/outputs to be set in forward." + ) + return autograd_grad_with_gradient_info( + output_infos=real_state["outputs"], + input_infos=real_state["inputs"], + grad_outputs=grads, + allow_unused=True, + ) + + input_infos_for_fake = tuple( + GradientInfo( + edge=None, # type: ignore[arg-type] + size=arg.size(), + stride=arg.stride(), + dtype=arg.dtype, + device=arg.device, + ) + if isinstance(arg, torch.Tensor) and arg.requires_grad + else None + for arg in flat_args + ) + + def fake_backward(*grads): + return tuple( + torch.empty_strided( + info.size, info.stride, dtype=info.dtype, device=info.device + ) + if info is not None + else None + for info in input_infos_for_fake + ) + + new_real_fn_callable = _LeafCallable(real_forward) + + with torch._C._AutoDispatchBelowAutograd(): + fw_outputs = invoke_leaf_function( + new_real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices=requires_grad_indices, + ) + + hook_real = getattr(real_fn_callable, "_leaf_hook_real_fn", None) + hook_fake = getattr(real_fn_callable, "_leaf_hook_fake_fn", None) + if hook_real is not None: + if hook_fake is None: + raise AssertionError("expected hook_fake to be not None") + hook_captured_out_spec: list[pytree.TreeSpec | None] = [None] + wrapped_hook_real, wrapped_hook_fake = make_leaf_function_wrappers( + hook_real, hook_fake, hook_captured_out_spec + ) + hook_real_callable = _LeafCallable(wrapped_hook_real) + hook_fake_callable = _LeafCallable(wrapped_hook_fake) + + grad_tensors = [ + arg + for arg in flat_args + if isinstance(arg, torch.Tensor) and arg.requires_grad + ] + if grad_tensors: + + @torch._dynamo.disable + def _multi_grad_callback( + grads: Sequence[torch.Tensor], + ) -> None: + _, hook_spec = pytree.tree_flatten((tuple(grads), {})) + invoke_leaf_function( + hook_real_callable, + hook_fake_callable, + hook_spec, + "", + *grads, + ) + + torch.autograd.graph.register_multi_grad_hook( + grad_tensors, _multi_grad_callback + ) + + ctx.real_backward = real_backward + ctx.fake_backward = fake_backward + + return fw_outputs + + @staticmethod + # pyrefly: ignore [bad-override] + def backward(ctx, *grads): + real_bw_callable = _LeafCallable(ctx.real_backward) + fake_bw_callable = _LeafCallable(ctx.fake_backward) + _, bw_input_spec = pytree.tree_flatten((grads, {})) + fw_grads = invoke_leaf_function( + real_bw_callable, fake_bw_callable, bw_input_spec, "", *grads + ) + return None, None, None, None, *fw_grads + + +@invoke_leaf_function.py_autograd_impl +def invoke_leaf_function_autograd( + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices="", +): + return InvokeLeafFunctionAutogradOp.apply( + real_fn_callable, fake_fn_callable, input_spec, mutated_arg_indices, *flat_args + ) + + +# TODO: aliasing is not allowed +@invoke_leaf_function.py_functionalize_impl +def invoke_leaf_function_functionalization(ctx, *all_args, **kwargs): + from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, + ) + from torch._higher_order_ops.utils import HopInstance + + unwrapped_args = ctx.unwrap_tensors(all_args) + hop_instance = HopInstance.create(invoke_leaf_function, *unwrapped_args, **kwargs) + if can_auto_functionalize(hop_instance): + return do_auto_functionalize_v2(ctx.mode, hop_instance, all_args, kwargs) + + from torch._higher_order_ops.effects import handle_effects + + return handle_effects( + ctx.mode._allow_token_discovery, + ctx.mode._tokens, + invoke_leaf_function, + all_args, + kwargs, + ) + + +@invoke_leaf_function.py_impl(ProxyTorchDispatchMode) +def invoke_leaf_function_proxy_mode(proxy_mode, *all_args, **kwargs): + out = invoke_leaf_function(*all_args, **kwargs) + proxies = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, all_args) + proxy = proxy_mode.tracer.create_proxy( + "call_function", invoke_leaf_function, proxies, kwargs + ) + return track_tensor_tree(out, proxy, constant=None, tracer=proxy_mode.tracer) + + +def _validate_outputs_match( + fake_output: Any, + real_output: Any, +) -> None: + """ + Validate that fake_fn and real_fn outputs have matching pytree structure, + shapes, and dtypes. + + Raises: + RuntimeError: If outputs don't match with detailed error message. + """ + fake_flat, fake_spec = pytree.tree_flatten(fake_output) + real_flat, real_spec = pytree.tree_flatten(real_output) + + if fake_spec != real_spec: + raise RuntimeError( + f"Output structure mismatch in @leaf_function decorator.\n" + f"fake_impl returned structure: {fake_spec}\n" + f"real_impl returned structure: {real_spec}\n" + f"The fake_impl must return outputs with the same pytree structure as real_impl." + ) + + if len(fake_flat) != len(real_flat): + raise RuntimeError( + f"Output count mismatch in @leaf_function decorator.\n" + f"fake_impl returned {len(fake_flat)} values\n" + f"real_impl returned {len(real_flat)} values" + ) + + for i, (fake_val, real_val) in enumerate(zip(fake_flat, real_flat)): + fake_is_tensor = isinstance(fake_val, torch.Tensor) + real_is_tensor = isinstance(real_val, torch.Tensor) + + if fake_is_tensor != real_is_tensor: + raise RuntimeError( + f"Output type mismatch at position {i} in @leaf_function decorator.\n" + f"fake_impl returned: {type(fake_val).__name__}\n" + f"real_impl returned: {type(real_val).__name__}" + ) + + if fake_is_tensor: + if fake_val.shape != real_val.shape: + raise RuntimeError( + f"Shape mismatch at output position {i} in @leaf_function decorator.\n" + f"fake_impl output shape: {list(fake_val.shape)}\n" + f"real_impl output shape: {list(real_val.shape)}\n" + f"The fake_impl must produce tensors with the same shapes as real_impl." + ) + + if fake_val.dtype != real_val.dtype: + raise RuntimeError( + f"Dtype mismatch at output position {i} in @leaf_function decorator.\n" + f"fake_impl output dtype: {fake_val.dtype}\n" + f"real_impl output dtype: {real_val.dtype}\n" + f"The fake_impl must produce tensors with the same dtypes as real_impl." + ) + + +def _parse_mutated_arg_indices(s: str) -> set[int]: + return {int(x) for x in s.split(",") if x} + + +def _check_no_input_mutation( + flat_args: tuple[Any, ...], + version_before: list[int], + mutated_arg_indices: str = "", +) -> None: + mutated_set = _parse_mutated_arg_indices(mutated_arg_indices) + for i, arg in enumerate(flat_args): + if isinstance(arg, torch.Tensor) and arg._version != version_before[i]: + if i not in mutated_set: + raise RuntimeError( + f"Undeclared in-place mutation on input tensor at position {i}. " + f"Declare it in @leaf_function(mutates_args=...) or avoid mutating inputs." + ) + + +@register_fake(invoke_leaf_function) +def invoke_leaf_function_fake( + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices="", +): + with unflatten_args_with_modules(flat_args, input_spec) as (args, kwargs): + return fake_fn_callable(*args, **kwargs) + + +def _detach_with_grad_dtype(arg): + # Tensor.detach() resets grad_dtype to the tensor's own dtype, dropping + # any caller-set grad_dtype (e.g. param.grad_dtype = torch.float32 on a + # bf16 weight). Propagate it back so the inner autograd graph accumulates + # the kernel's gradient at the requested dtype. grad_dtype is only + # meaningful on leaf tensors. + if not isinstance(arg, torch.Tensor): + return arg + detached = arg.detach() + if arg is not detached and arg.is_leaf and arg.grad_dtype != detached.grad_dtype: + detached.grad_dtype = arg.grad_dtype + return detached + + +@invoke_leaf_function.py_impl(DispatchKey.CompositeExplicitAutograd) +def invoke_leaf_function_dense( + real_fn_callable, + fake_fn_callable, + input_spec, + mutated_arg_indices, + *flat_args, + requires_grad_indices="", +): + from torch._dynamo import config as dynamo_config + + version_before = [ + arg._version if isinstance(arg, torch.Tensor) else 0 for arg in flat_args + ] + + flat_args = tuple(_detach_with_grad_dtype(arg) for arg in flat_args) + requires_grad_indices_set = _parse_mutated_arg_indices(requires_grad_indices) + flat_args = tuple( + arg.requires_grad_(True) if idx in requires_grad_indices_set else arg + for idx, arg in enumerate(flat_args) + ) + + with unflatten_args_with_modules(flat_args, input_spec) as (args, kwargs): + real_output = real_fn_callable(*args, **kwargs) + + _check_no_input_mutation(flat_args, version_before, mutated_arg_indices) + + if dynamo_config.leaf_function_validate_outputs: + fake_output = fake_fn_callable(*args, **kwargs) + _validate_outputs_match(fake_output, real_output) + + return real_output diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_subgraph.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_subgraph.py new file mode 100644 index 0000000000000000000000000000000000000000..ee3b37d65b3d7cad67df6cc16b9e06ea4a7381d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/invoke_subgraph.py @@ -0,0 +1,1457 @@ +# mypy: allow-untyped-defs + +import contextlib +import copy +import functools +import threading +from collections import defaultdict +from collections.abc import Callable +from contextlib import nullcontext +from dataclasses import dataclass, field, replace +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._dispatch.python import suspend_functionalization +from torch._higher_order_ops.utils import ( + _from_fun, + _maybe_reenter_make_fx, + clone_outputs_aliasing_inputs, + FunctionalizeCtxWrapper, + get_dummy_aot_autograd_config, + HopInstance, + prepare_fw_with_masks, + redirect_to_mode, + reenter_make_fx, + register_fake, + save_values_for_backward, + saved_values, +) +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class +from torch._ops import HigherOrderOperator +from torch._subclasses.functional_tensor import disable_functional_mode +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.fx.graph_module import GraphModule +from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts +from torch.utils._debug_mode import DebugMode +from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode + + +invoke_subgraph_counter = 0 + + +# During the tracing of the joint graph, we construct this information. This is +# used to filter out grad_outs/tangents in the `backward` method of +# InvokeSubgraphAutogradOp. +@dataclass +class OutputMetadata: + num_fw_outs: int | None = None + indexes_with_symint: set[int] = field(default_factory=set) + indexes_with_no_grad: set[int] = field(default_factory=set) + + +# This config will be stored in invoke_subgraph HOP node.meta["custom"]["nested_region_config"] +# as well as the subgraph's gm.meta["nested_region_config"]. +@dataclass +class NestedCompileRegionOptions: + # A Callable that takes (gm, example_inputs, decompositions=None, **kwargs) as inputs. + # Returns AOTCompiledArtifact + fw_compiler: Callable | None = None + bw_compiler: Callable | None = None + + # Note: [InvokeSubgraphHOP Partitioner] + # If not None, add "partitioner" to HOP node meta. + # If Callable, directly assign the callable, but the callable cannot be pickled + # If str, the options are "default_partition" and "min_cut_rematerialization_partition". + # The HOP joint graph will be partitioned using the corresponding functions in + # torch/_functorch/partitioners.py + partitioner: Callable | str | None = None + + # If it's None, we'll inherit the parent call's decompositions. + # Otherwise, the nested region will use this decompositions. + decompositions: dict[str, Any] | None = None + + # Inductor config patches to apply while compiling this nested region through + # Inductor's normal invoke_subgraph lowering path. Also used for the backward + # unless bw_inductor_config_patches replaces it. + inductor_config_patches: dict[str, Any] | None = None + + # If set, the full inductor config for the backward subgraph, used instead of + # inductor_config_patches (a replacement, not merged with it), mirroring + # aot_autograd's separate fw_compiler/bw_compiler. If None, the backward + # reuses the forward config. + bw_inductor_config_patches: dict[str, Any] | None = None + + +def _extract_nested_region_config(fn): + """ + Extract the NestedCompileRegionOptions from the HOP subgraph gm.meta["nested_region_config"] + """ + gm_to_compile = None + if isinstance(fn, torch.fx.GraphModule): + gm_to_compile = fn + elif isinstance(fn, FunctionalizeCtxWrapper): + gm_to_compile = fn.subgraph + + if ( + isinstance(gm_to_compile, torch.fx.GraphModule) + and hasattr(gm_to_compile, "meta") + and "nested_region_config" in gm_to_compile.meta + ): + if isinstance( + gm_to_compile.meta["nested_region_config"], NestedCompileRegionOptions + ): + return gm_to_compile.meta["nested_region_config"].decompositions + return None + + +def get_backward_nested_region_config( + fw_config: NestedCompileRegionOptions | None, +) -> NestedCompileRegionOptions | None: + """Region config for compiling the backward subgraph. + + When the region sets bw_inductor_config_patches, the backward compiles under + it (a replacement for inductor_config_patches, not merged with it). Otherwise + the forward config is reused unchanged, so the returned object is identical + (callers rely on this identity to detect a distinct backward config). + """ + if ( + isinstance(fw_config, NestedCompileRegionOptions) + and fw_config.bw_inductor_config_patches is not None + ): + return replace( + fw_config, + inductor_config_patches=fw_config.bw_inductor_config_patches, + bw_inductor_config_patches=None, + ) + return fw_config + + +# Per-call id used by downstream graph passes to pair fw and bw +# invoke_subgraph HOP nodes (e.g. run_joint_graph_passes_on_hops). The +# autograd Function pushes the id around its fw and bw dispatches; the +# proxy-mode handler stamps it on the resulting FX nodes via +# meta["custom"]["call_id"]. +_invoke_subgraph_call_state = threading.local() + + +def _next_invoke_subgraph_call_id() -> int: + counter = getattr(_invoke_subgraph_call_state, "counter", 0) + _invoke_subgraph_call_state.counter = counter + 1 + return counter + + +def _current_invoke_subgraph_call_id() -> int | None: + return getattr(_invoke_subgraph_call_state, "current", None) + + +@contextlib.contextmanager +def _set_invoke_subgraph_call_id(call_id: int): + prev = getattr(_invoke_subgraph_call_state, "current", None) + _invoke_subgraph_call_state.current = call_id + try: + yield + finally: + _invoke_subgraph_call_state.current = prev + + +def warn_and_trace_duplicate_backward( + identifier: str | None, + suffix: int, + bw_graph: torch.fx.GraphModule, + num_primals: int, + tangents: tuple[Any, ...], +) -> None: + if suffix == 0: + return + + from torch._dynamo.utils import warn_once + from torch._logging import trace_structured + + placeholders = [node for node in bw_graph.graph.nodes if node.op == "placeholder"] + tangent_summaries: list[dict[str, Any]] = [] + for idx, tangent in enumerate(tangents): + summary: dict[str, Any] = {} + backward_input_idx = num_primals + idx + if backward_input_idx < len(placeholders): + summary["backward_input_name"] = placeholders[backward_input_idx].name + + if not isinstance(tangent, torch.Tensor): + summary["type"] = "non-Tensor" + tangent_summaries.append(summary) + continue + + summary.update( + { + "shape": [ + int(s) if isinstance(s, int) else str(s) for s in tangent.shape + ], + "stride": [ + int(s) if isinstance(s, int) else str(s) for s in tangent.stride() + ], + "dtype": str(tangent.dtype), + "device": str(tangent.device), + } + ) + tangent_summaries.append(summary) + + warn_once( + "invoke_subgraph traced multiple backward graphs for the same forward " + f"identifier {identifier!r}. This usually means the incoming backward " + "tangent metadata differs across backward invocations. This can happen " + "when upstream backward formulas produce gradients with different " + "layouts, aliases, or other tensor metadata. This can increase compile " + "time and code size. Use tlparse and look for the " + "invoke_subgraph_backward_duplicate artifact for tangent details." + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "invoke_subgraph_backward_duplicate", + "encoding": "json", + }, + payload_fn=lambda: { + "forward_identifier": identifier, + "backward_identifier": f"bw_{identifier}_{suffix}", + "new_variant_suffix": suffix, + "num_variants_for_identifier": suffix + 1, + "new_variant": { + "backward_identifier": f"bw_{identifier}_{suffix}", + "tangents": tangent_summaries, + }, + "explanation": ( + "invoke_subgraph caches backward graphs by both the forward " + "identifier and tangent metadata. Multiple backward variants " + "for one forward identifier usually mean the backward tangents " + "have different tensor metadata, commonly stride." + ), + "common_cause": ( + "This can happen when equivalent forward invocations receive backward " + "tangents from different upstream formulas, or from the same " + "formula with different input metadata. For example, an " + "upstream backward may return a view, alias, slice, expanded " + "tensor, or otherwise non-contiguous gradient whose metadata " + "does not match the tangent seen by another use." + ), + "suggested_action": ( + "If the duplicate backward graph is undesirable, materialize a " + "consistent tangent layout before the nested region backward. " + "One model-level workaround is a custom autograd.Function whose " + "forward returns the input and whose backward returns " + "grad.contiguous()." + ), + }, + ) + + +class InvokeSubgraphHOP(HigherOrderOperator): + def __init__(self) -> None: + # Invoke subgraph does not have any state, it is just a wrapper over a + # subgraph, so we can safely cache the HOP. + super().__init__("invoke_subgraph", cacheable=True) + # This is used by the fake tensor cache key validator to extract the + # subgraph and iterate over the nodes to find if all nodes are fake + # tensor cacheable. + self.subgraph_indexes = [ + 0, + ] + + # identifier is setup by upper part of the stack. This helps us in + # identifying two invoke_subgraph calls have same subgraph. + def __call__( + self, + subgraph: GraphModule | FunctionalizeCtxWrapper, + identifier: str | None, + *operands, + ): + if identifier is not None and not isinstance(identifier, str): + raise AssertionError( + f"identifier must be None or a string, got {type(identifier)}" + ) + + if not all( + isinstance( + o, (torch.Tensor, int, torch.SymInt, torch.Generator, FakeScriptObject) + ) + or is_custom_class(type(o)) + for o in operands + if o is not None + ): + raise AssertionError( + f"invoke_subgraph operands must be a list of tensors/ints/SymInts/Generator, got {operands}" + ) + + # pyrefly: ignore [missing-attribute] + return super().__call__(subgraph, identifier, *operands) + + # pyrefly: ignore [bad-override] + def gen_schema(self, subgraph, identifier, *operands): + from torch._higher_order_ops.schema import HopSchemaGenerator + from torch._higher_order_ops.utils import ( + check_input_alias_and_mutation_return_outputs, + materialize_as_graph, + ) + from torch._subclasses.functional_tensor import FunctionalTensor + + subgraph_decomp_table = _extract_nested_region_config(subgraph) + # When the subgraph is a GraphModule whose captured buffers are + # already FunctionalTensors (produced by an enclosing + # FunctionalTensorMode, e.g. the non-strict export path or + # ``run_decompositions`` on an ExportedProgram that preserved an + # ``invoke_subgraph`` HOP), re-tracing through + # ``materialize_as_graph`` would pop that mode via + # ``_disable_current_modes`` and trigger "FunctionalTensor on its + # own" when the inner trace touches the captured constants. In that + # case the existing graph has already been functionalized by the + # outer pass, so reuse it for schema / mutation analysis. + gm: torch.fx.GraphModule | None = None + if isinstance(subgraph, FunctionalizeCtxWrapper): + candidate = subgraph.subgraph + elif isinstance(subgraph, torch.fx.GraphModule): + candidate = subgraph + else: + candidate = None + bufs = ( + list(candidate.buffers()) + if isinstance(candidate, torch.fx.GraphModule) + else [] + ) + if bufs and all(isinstance(buf, FunctionalTensor) for buf in bufs): + gm = candidate + if gm is None: + gm = materialize_as_graph( + subgraph, operands, subgraph_decomp_table=subgraph_decomp_table + ) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("subgraph", gm) + schema_gen.add_arg("identifier", identifier) + ( + _, + _, + _, + mutated_inputs, + outputs, + ) = check_input_alias_and_mutation_return_outputs(gm) + for idx, arg in enumerate(operands): + schema_gen.add_arg(f"arg{idx}", arg, is_mutated=idx in mutated_inputs) + for out in outputs: + schema_gen.add_output(out) + + return schema_gen.gen_schema() + + +invoke_subgraph = InvokeSubgraphHOP() + + +def invoke_subgraph_infer( + subgraph: GraphModule | FunctionalizeCtxWrapper, + *operands, +): + """Inference-only entrypoint for invoke_subgraph that auto-generates identifier. + + This is intended for use cases where we are building an inference graph and + don't need the forward/backward caching that requires a stable identifier. + The identifier is automatically computed based on the current proxy mode's + tracer state. + + If no proxy mode is active, the subgraph is called directly. + """ + from torch.fx.experimental.proxy_tensor import get_proxy_mode + + proxy_mode = get_proxy_mode() + if proxy_mode is None: + # No tracing active, just call the subgraph directly + if getattr(subgraph, "_boxed_call", False): + return subgraph(list(operands)) + else: + return subgraph(*operands) + + from torch._dynamo.utils import get_unique_name_wrt + + # How exactly should we allocate names for the HOP invoke_subgraph we + # are going to put into the graph? This is a bit tricky. In the + # original design of invoke_subgraph, this HOP never shows up in the + # wild: it is only generated Dynamo, so Dynamo can take sure of + # ensuring it picks unique names in the context of the particular + # Dynamo compilation. However, these invoke_subgraph are different: + # they live as Dynamo compiled code that can potentially get traced + # multiple times! If they get retraced several times in the same + # trace, deduplication occurs; but if I make_fx a function f once, + # and then do a separate new trace, there's no relationship between + # these. Additionally, we also want the name we put in the graph to + # be deterministic, and for it to be indifferent to how many + # unrelated invoke_subgraphs/make_fxs we've done, prior to THIS + # particular make_fx. + # + # To satisfy all of these constraints, it's impossible to preallocate + # a name before tracing actually goes through us (since those names + # would have to all be unique even if a subgraph never gets used.) + # So we allocate the subgraph a fresh name PER proxy mode, and then + # consistently reuse it if it hits again. + # + # Note we do NOT do equality comparison subgraph, since it has + # reference equality semantics. + + if subgraph in proxy_mode._invoke_subgraph_cache: + name = proxy_mode._invoke_subgraph_cache[subgraph] + else: + name = get_unique_name_wrt( + "invoke_subgraph", + proxy_mode._invoke_subgraph_names, + requires_suffix=True, + ) + proxy_mode._invoke_subgraph_names.add(name) + proxy_mode._invoke_subgraph_cache[subgraph] = name + + return invoke_subgraph(subgraph, name, *operands) + + +# Registers dispatches for SAC +redirect_to_mode(invoke_subgraph, _CachingTorchDispatchMode) +redirect_to_mode(invoke_subgraph, _CachedTorchDispatchMode) + + +def invoke_subgraph_placeholder(func, *args, **kwargs): + if torch.compiler.is_dynamo_compiling(): + # This is just a placeholder for Dynamo to replace with invoke_subgraph + raise RuntimeError("invoke_subgraph should not be called directly in Dynamo") + + if torch.compiler.is_exporting(): + # For non-strict export tracing, we still want to go through Dynamo + + def _invoke_subgraph_placeholder_wrapper(func, args, kwargs): + return invoke_subgraph_placeholder(func, *args, **kwargs) + + from torch._higher_order_ops.utils import _hop_compile_and_call + + return _hop_compile_and_call( + _invoke_subgraph_placeholder_wrapper, (func, args, kwargs) + ) + + return func(*args, **kwargs) + + +def mark_compile_region( + fn=None, + options: NestedCompileRegionOptions | None = None, + max_reuse_entries: int = 8, + reuse_hash_fn=None, +): + """ + This wrapper instructs torch.compile to compile the wrapped region once and + reuse the compiled artifact, instead of the usual way of aggressively + inlining the function. + + Under the hood, it tells TorchDynamo to use InvokeSubgraph HOP for the + region. For PyTorch eager, this is a no-op. + + Args: + fn: The function to wrap + options: Optional config to use for compiling the subgraph. + Warning: this is an experimental feature under development and + not ready for use yet. + max_reuse_entries: Maximum number of reuse cache entries per function + before raising an error. If this limit is hit, guards keep failing + across invocations and hierarchical compilation is not effective. + """ + + def wrap(func): + def inner(*args, **kwargs): + # Get the innermost function to avoid nested compile regions + inner_func = func + while hasattr(inner_func, "__marked_compile_region_fn__"): + inner_func = inner_func.__marked_compile_region_fn__ + return invoke_subgraph_placeholder(inner_func, *args, **kwargs) + + inner.__marked_compile_region_fn__ = func # type: ignore[attr-defined] + func.__marked_compile_region_config__ = options # type: ignore[attr-defined] + func.__marked_compile_region_max_reuse_entries__ = max_reuse_entries # type: ignore[attr-defined] + func.__marked_compile_region_reuse_hash_fn__ = reuse_hash_fn # type: ignore[attr-defined] + + return inner + + if fn: + return wrap(fn) + else: + return wrap + + +def get_invoke_subgraph_cache(): + cache = None + if tracing_ctx := torch._guards.TracingContext.try_get(): + cache = tracing_ctx.hop_dispatch_set_cache.get_cache(invoke_subgraph) + return cache + + +# TODO (@anijain2305) - Delete this function when base_hop uses invoke_subgraph infra +def trace_joint_graph(fn, fw_inputs, fw_outputs): + """ + Naively trace out a joint graph. This simplifies the reconstruction of joint + graph in the min-cut partitioner later on. + """ + from torch._functorch.aot_autograd import create_joint + + dummy_aot_config = get_dummy_aot_autograd_config() + + # This joint_fn is inserted as the backward graph as is. This simplifies the + # min-cut partitioner work later on. + # Input signature - (*primals, *tangents) + # Output signature - (*grads, *fw_outs) + # The output signature is deliberately kept grads first and fw_outs second. + # Having grads first makes the min-cut partitioner HOP graph stitching + # easier. + def joint_fn(*primals_and_tangents): + primals = primals_and_tangents[: len(fw_inputs)] + tangents = primals_and_tangents[len(fw_inputs) :] + + fw_outs, grads = create_joint( + prepare_fw_with_masks(fn), aot_config=dummy_aot_config + )(primals, tangents) + + maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents) + + # return signature is deliberately kept (*grads, *fw_outs). This + # simplifies partitioning work later on. + return pytree.tree_map(maybe_clone, tuple(grads + list(fw_outs))) + + primals = list(fw_inputs) + # This assumes that the tangent strides match fw_outputs strides. Check the + # InvokeSubgraphAutogradOp backward op for the contiguous call. + tangents = [_from_fun(out) for out in fw_outputs] + + joint_operands = primals + tangents + + return _maybe_reenter_make_fx(joint_fn)(*joint_operands) + + +# TODO (@anijain2305) - Delete this function when base_hop uses invoke_subgraph infra +def create_fw_bw_graph(subgraph, operands, grad_outputs=None): + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + # args are functional tensors, generate some example tensors + fw_inputs = pytree.tree_map(_from_fun, operands) + + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode(fw_inputs) + context = ( + nullcontext() + if fake_mode is None or fake_mode.shape_env is None + else fake_mode.shape_env.ignore_fresh_unbacked_symbols() + ) + + with context: + fw_outs = pytree.tree_map(_from_fun, subgraph(*fw_inputs)) + + num_fw_outs = len(fw_outs) + + # Collect the indexes of none in the output to check that the grad + # is None at the corresponding index in the backward. This check is + # performed in the autograd.Function - InvokeSubgraphAutogradOp. + # Also collect the indexes of no_grad in the output to filter out + # the grad_outs in the `backward` method. + output_metadata = OutputMetadata() + + output_metadata.num_fw_outs = num_fw_outs + for idx, fw_out in enumerate(fw_outs): + if isinstance(fw_out, torch.SymInt): + output_metadata.indexes_with_symint.add(idx) + elif not fw_out.requires_grad: + output_metadata.indexes_with_no_grad.add(idx) + + if grad_outputs is None: + # Infer grad_outputs to be the same properties as the fw_outputs + # if they're not passed in + # Although fw_outs are equivalent to grad_outputs for tracing + # purposes, we have to carefully handle the None and fw_out that do + # not have require_grad. At those indexes, we will have None in the + # backward graph. + grad_outputs = fw_outs + grad_outputs = [grad for grad in grad_outputs if grad is not None] + grad_outputs = [grad for grad in grad_outputs if grad.requires_grad] + + # Force grad_out to be contiguous. This is because at runtime, + # grad_out could have different strides than fw_outs. So, we + # force the grad_outs to be contiguous for both tracing and + # runtime. + grad_outputs = [grad.contiguous() for grad in grad_outputs] + + if any( + not isinstance(out, torch.Tensor) + for out in grad_outputs + if out is not None + ): + raise RuntimeError( + "Expect outputs of invoke_subgraph to only contains tensors or None. " + f"Got types {[type(out) for out in grad_outputs]}." + ) + + # Trace the forward subgraph + fw_graph = _maybe_reenter_make_fx(subgraph)(*fw_inputs) + + # Trace the joint graph and assign it to the bwd graph + bw_graph = trace_joint_graph( + subgraph, + fw_inputs, + grad_outputs, + ) + return fw_graph, bw_graph, output_metadata + + +def get_output_metadata(subgraph, *operands): + """ + Extract metadata about the subgraph outputs WITHOUT executing the subgraph. + This avoids running side-effectful operations twice (once here, once in forward). + We analyze the graph structure statically to extract metadata. + """ + # Unwrap FunctionalizeCtxWrapper if present + if isinstance(subgraph, FunctionalizeCtxWrapper): + subgraph = subgraph.subgraph + + # If not a GraphModule, fall back to execution-based metadata extraction + if not isinstance(subgraph, torch.fx.GraphModule): + return _get_output_metadata_by_execution(subgraph, *operands) + + output_metadata = OutputMetadata() + + # Extract output arguments from the output node + # The output node has args=(output_values,) where output_values is a tuple/list + output_node = next(reversed(subgraph.graph.find_nodes(op="output"))) + output_metadata.num_fw_outs = len(output_node.args[0]) + + for idx, output_arg in enumerate(output_node.args[0]): + if not isinstance(output_arg, torch.fx.Node): + if isinstance(output_arg, int): + output_metadata.indexes_with_symint.add(idx) + output_metadata.indexes_with_no_grad.add(idx) + continue + + # Check node metadata for type information + if output_arg.meta.get("val") is None: + # If we don't have complete metadata for all outputs, fall back to execution + # This is important for correctness (e.g., detecting SymInts) even though it + # runs side-effectful operations + return _get_output_metadata_by_execution(subgraph, *operands) + + val = output_arg.meta["val"] + if isinstance(val, torch.SymInt): + output_metadata.indexes_with_symint.add(idx) + output_metadata.indexes_with_no_grad.add(idx) + elif isinstance(val, torch.Tensor): + # Check if tensor requires grad from metadata + if hasattr(val, "requires_grad") and not val.requires_grad: + output_metadata.indexes_with_no_grad.add(idx) + else: + # Non-tensor, non-symint (shouldn't happen but be safe) + output_metadata.indexes_with_no_grad.add(idx) + + return output_metadata + + +def _get_output_metadata_by_execution(subgraph, *operands): + """ + Fallback: Extract metadata by executing the subgraph. + This should only be used when static analysis fails. + WARNING: This will run side-effectful operations! + """ + + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + # args are functional tensors, generate some example tensors + fw_inputs = pytree.tree_map(_from_fun, operands) + + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode(fw_inputs) + context = ( + nullcontext() + if fake_mode is None or fake_mode.shape_env is None + else fake_mode.shape_env.ignore_fresh_unbacked_symbols() + ) + + with context: + fw_outs = pytree.tree_map(_from_fun, subgraph(*fw_inputs)) + + num_fw_outs = len(fw_outs) + + output_metadata = OutputMetadata() + output_metadata.num_fw_outs = num_fw_outs + + for idx, fw_out in enumerate(fw_outs): + if isinstance(fw_out, torch.SymInt): + output_metadata.indexes_with_symint.add(idx) + elif not fw_out.requires_grad: + output_metadata.indexes_with_no_grad.add(idx) + + return output_metadata + + +def trace_joint_graph_as_bwd( + subgraph, num_primals, joint_operands, include_key_set, exclude_key_set +): + """ + Naively trace out a joint graph. This simplifies the reconstruction of joint + graph in the min-cut partitioner later on. + """ + from torch._functorch.aot_autograd import create_joint + + dummy_aot_config = get_dummy_aot_autograd_config() + + if isinstance(subgraph, torch.fx.GraphModule): + + def graph_with_interpreter(*args): + # Running graph with interpreter is needed for propagating the stack_trace + with torch.fx.traceback.preserve_node_meta(): + return torch.fx.Interpreter(subgraph).run(*args) + + fn = graph_with_interpreter + else: + fn = subgraph + + # This joint_fn is inserted as the backward graph as is. This simplifies the + # min-cut partitioner work later on. + # Input signature - (*primals, *tangents) + # Output signature - (*grads, *fw_outs) + # The output signature is deliberately kept grads first and fw_outs second. + # Having grads first makes the min-cut partitioner HOP graph stitching + # easier. + def joint_fn(*primals_and_tangents): + primals = primals_and_tangents[:num_primals] + tangents = primals_and_tangents[num_primals:] + + fw_outs, grads = create_joint( + prepare_fw_with_masks(fn), aot_config=dummy_aot_config + )(primals, tangents) + + maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents) + + # return signature is deliberately kept (*grads, *fw_outs). This + # simplifies partitioning work later on. + return pytree.tree_map(maybe_clone, tuple(grads + list(fw_outs))) + + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + joint_operands = [_from_fun(arg) for arg in joint_operands] + with contextlib.ExitStack() as stack: + stack.enter_context( + torch._C._ForceDispatchKeyGuard(include_key_set, exclude_key_set), + ) + subgraph_decomp_table = _extract_nested_region_config(subgraph) + with torch.enable_grad(): + return _maybe_reenter_make_fx( + joint_fn, subgraph_decomp_table=subgraph_decomp_table + )(*joint_operands) + + +def get_non_differentiable_indices(subgraph) -> list[int]: + """Inspect a subgraph's output node metadata to find outputs that + were non-differentiable (requires_grad=False) during Dynamo tracing. + + This uses the example_value stored on each output node, which reflects + the correct requires_grad from the original tracing (where inner + autograd.Functions DID run and mark_non_differentiable was called). + + InvokeSubgraphAutogradOp runs the subgraph under + _AutoDispatchBelowAutograd, which suppresses the autograd key. Inner + autograd.Functions (e.g. FlexAttentionAutogradOp) therefore never call + mark_non_differentiable. The outer autograd engine then sets + requires_grad=True on ALL outputs because the inputs require grad. + We use the Dynamo-traced example_value to restore the correct + non-differentiable status at the outer level. + """ + if not isinstance(subgraph, torch.fx.GraphModule): + return [] + + output_nodes = [n for n in subgraph.graph.nodes if n.op == "output"] + if not output_nodes: + return [] + + output_args = output_nodes[0].args[0] + if not isinstance(output_args, (tuple, list)): + output_args = [output_args] + + non_differentiable: list[int] = [] + for out_idx, arg in enumerate(output_args): + if not isinstance(arg, torch.fx.Node): + continue + example = arg.meta.get("example_value") + if isinstance(example, torch.Tensor) and not example.requires_grad: + non_differentiable.append(out_idx) + + return non_differentiable + + +class InvokeSubgraphAutogradOp(torch.autograd.Function): + """ + Saves the subgraph, i.e. original callable, in the forward method. And then + traces out a joint graph in the backward. This delaying of tracing in + backward, also called as lazy backward, ensures that the assumptions about + the grad_out strides and tensor-subclass-ness are already accounted for. + """ + + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + subgraph, + identifier, + output_metadata, + *operands, + ): + # We want to delay the backward graph construction until the backward. + # So in forward, we just run the fw callable as is. And save all the + # information necessary to construct the backward graph in the ctx. + ctx._subgraph = subgraph + ctx._identifier = identifier + ctx._output_metadata = output_metadata + ctx._call_id = _next_invoke_subgraph_call_id() + # We snapshot the dispatch keys in forward for materializing + # the bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + + save_values_for_backward(ctx, operands) + + with ( + torch._C._AutoDispatchBelowAutograd(), + _set_invoke_subgraph_call_id(ctx._call_id), + ): + out = invoke_subgraph( + subgraph, + f"fw_{identifier}", + *operands, + ) + + # Check that int (coming from symint) is at expected indexes. + for idx, o in enumerate(out): + if isinstance(o, int): + if idx not in output_metadata.indexes_with_symint: + raise AssertionError( + f"unexpected int output at index {idx}, not in indexes_with_symint" + ) + + # Propagate non-differentiable status from the inner subgraph. + # See get_non_differentiable_indices for details on why this is needed. + non_differentiable_indices = get_non_differentiable_indices(subgraph) + if non_differentiable_indices: + non_differentiable = [ + out[i] + for i in non_differentiable_indices + if isinstance(out[i], torch.Tensor) + ] + if non_differentiable: + ctx.mark_non_differentiable(*non_differentiable) + ctx._non_differentiable_indices = non_differentiable_indices + + return out + + @staticmethod + def backward( + ctx, + *grad_outs, + ): + from torch._dynamo.utils import dynamo_timed + + subgraph = ctx._subgraph + identifier = ctx._identifier + output_metadata = ctx._output_metadata + primals = saved_values(ctx) + + # Filter out grads that are None or do not require_grad. This was + # the assumption we made during the tracing of joint_graph. + non_differentiable_indices = ctx._non_differentiable_indices + filtered_grad_outs = [] + for idx, o in enumerate(grad_outs): + if o is None: + if ( + idx not in output_metadata.indexes_with_symint + and idx not in non_differentiable_indices + ): + raise AssertionError( + f"unexpected None grad_out at index {idx}, not in indexes_with_symint" + ) + elif ( + idx in output_metadata.indexes_with_no_grad + or idx in non_differentiable_indices + ): + # Deliberately skip over the grad_outs which we know should be + # None because the corresponding fwd_out does not require_grad. + pass + else: + filtered_grad_outs.append(o) + filtered_grad_outs = tuple(filtered_grad_outs) + + # Important note - Even though the forward graph can be same for + # different invoke_subgraphs, the backward graph can be different + # because the tangent strides can be different. So, here we cache on + # tangent_metadata in addition to identifier + from torch._guards import detect_fake_mode + from torch._subclasses._fake_tensor_utils import _CacheKeyState + from torch._subclasses.fake_tensor import extract_tensor_metadata + + fake_mode = detect_fake_mode(primals + filtered_grad_outs) + if fake_mode is None: + raise AssertionError("fake_mode should be enabled for HOPs") + state = _CacheKeyState(fake_mode.shape_env) + + tangent_metadata: list[object] = [] + for tangent in filtered_grad_outs: + metadata = extract_tensor_metadata(tangent) + metadata._flatten_into(tangent_metadata, fake_mode, state) + + # Add aliasing information to tangent_metadata + # Two tangents are aliased if they are the same tensor object (using id()) + # We create a tuple of tuples where each inner tuple contains indices of aliased tensors + # e.g. ((0, 1),) would mean there is one aliasing group, and the first and second tangents are aliased + # e.g. () would mean there is no aliasing between tangents + tensor_to_indices: dict[int, list[int]] = defaultdict(list) + for i, tangent in enumerate(filtered_grad_outs): + if isinstance(tangent, torch.Tensor): + tensor_to_indices[id(tangent)].append(i) + + aliasing_groups = tuple( + sorted( + tuple(indices) + for indices in tensor_to_indices.values() + if len(indices) > 1 + ) + ) + tangent_metadata.append(aliasing_groups) + + # pyrefly: ignore [bad-assignment] + tangent_metadata = tuple(tangent_metadata) + + # bw_graph is a joint graph with signature (*primals_and_tangents) and + # returns (*grads_and_fw_outs). To get the grads, we use the num_fw_outs + # to extract the grads. + primals_and_tangents = primals + filtered_grad_outs + + # Check if we have already traced the bwd subgraph. + bw_graph = None + suffix = None + invoke_subgraph_cache = get_invoke_subgraph_cache() + cache_hit = False + if invoke_subgraph_cache: + bw_graph, suffix = invoke_subgraph_cache.get_lazy_bwd_entry( + identifier, tangent_metadata + ) + cache_hit = bw_graph is not None + + if bw_graph is None: + if suffix is not None: + raise AssertionError( + f"suffix should be None when bw_graph is None, got {suffix}" + ) + with dynamo_timed( + "invoke_subgraph_trace_joint_graph", log_pt2_compile_event=True + ): + bw_graph = trace_joint_graph_as_bwd( + subgraph, + len(primals), + primals_and_tangents, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + ) + if ( + hasattr(subgraph, "meta") + and "nested_region_config" in subgraph.meta + ): + bw_graph.meta["nested_region_config"] = subgraph.meta[ + "nested_region_config" + ] + + if invoke_subgraph_cache and not cache_hit: + suffix = invoke_subgraph_cache.add_lazy_bwd_entry( + identifier, tangent_metadata, bw_graph + ) + warn_and_trace_duplicate_backward( + identifier, suffix, bw_graph, len(primals), filtered_grad_outs + ) + + with _set_invoke_subgraph_call_id(ctx._call_id): + grads = invoke_subgraph( + bw_graph, f"bw_{identifier}_{suffix}", *primals_and_tangents + )[: -output_metadata.num_fw_outs] + return None, None, None, *grads + + +@invoke_subgraph.py_autograd_impl +def _(subgraph, identifier, *operands): + from torch._guards import detect_fake_mode + + # Eager backends run the captured HOP with real tensors and no AOTAutograd + # fake mode. Let regular autograd record through the subgraph in that case. + if detect_fake_mode(operands) is None: + if getattr(subgraph, "_boxed_call", False): + return subgraph(list(operands)) + return subgraph(*operands) + + # Check if we have already traced the subgraph. + invoke_subgraph_cache = get_invoke_subgraph_cache() + if invoke_subgraph_cache: + if saved_autograd_fn := invoke_subgraph_cache.get_autograd_key_entry( + identifier + ): + return saved_autograd_fn(*operands) + + output_metadata = get_output_metadata(subgraph, *operands) + + def autograd_fn_callable(*args): + return InvokeSubgraphAutogradOp.apply( + subgraph, identifier, output_metadata, *args + ) + + # Save the autograd_fn_callable in the dispatch set cache. + if invoke_subgraph_cache: + invoke_subgraph_cache.add_autograd_key_entry(identifier, autograd_fn_callable) + + return autograd_fn_callable(*operands) + + +@invoke_subgraph.py_impl(DebugMode) +def _(debug_mode, subgraph, identifier, *operands): + # record HOP call + call = torch.utils._debug_mode._OpCall( + invoke_subgraph, + (identifier, *operands), + kwargs={}, + call_depth=debug_mode.call_depth + 1, + stack=debug_mode.record_stack_trace, + ) + debug_mode._record_call(call) + + debug_mode.call_depth += 1 + debug_mode._handle_annotate(f"[enter InvokeSubgraph HOP] {identifier}") + + # If the HOP is dispatched from DebugMode, we should enable debug_mode + # for the subgraph call. + with debug_mode: + if getattr(subgraph, "_boxed_call", False): + result = subgraph(list(operands)) + else: + result = subgraph(*operands) + debug_mode._handle_annotate(f"[exit InvokeSubgraph HOP] {identifier}") + debug_mode.call_depth -= 1 + # record output of HOP + debug_mode._record_call_output(call, result) + return result + + +@invoke_subgraph.py_impl(DispatchKey.CompositeExplicitAutograd) +def _(subgraph, identifier, *operands): + from torch.utils._python_dispatch import _get_current_dispatch_mode + + mode = _get_current_dispatch_mode() + + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + + if getattr(subgraph, "_boxed_call", False): + return subgraph(list(operands)) + else: + return subgraph(*operands) + + +@invoke_subgraph.py_functionalize_impl +def _(ctx, subgraph, identifier, *operands): + from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, + ) + + # (in the functionalization metadata phase) Capture tokens before + tokens_before = dict(ctx.mode._tokens) + + # Check if this subgraph has effects stored in the cache + invoke_subgraph_cache = get_invoke_subgraph_cache() + effects = None + if invoke_subgraph_cache: + effects = invoke_subgraph_cache.get_effects(identifier) + + if effects: + if len(effects) != 1: + raise AssertionError( + f"Multiple effects within a subgraph NYI, got {len(effects)} effects" + ) + tokens = ctx.mode._tokens + effects = next(iter(effects)) + token_input = tokens[effects] + + operands = (token_input, *operands) + + def wrap_subgraph(subgraph): + def wrapped_subgraph(token, *args): + res = subgraph(*args) + return ctx.unwrap_tensors(ctx.mode._tokens[effects]), *res + + return wrapped_subgraph + + subgraph = wrap_subgraph(subgraph) + + unwrapped_operands = ctx.unwrap_tensors(operands) + + functionalize_schema = None + schema_cache_key = None + if invoke_subgraph_cache: + schema_cache_key = ( + id(subgraph), + identifier, + tuple(type(operand) for operand in operands), + ) + functionalize_schema = invoke_subgraph_cache.get_functionalize_schema_entry( + schema_cache_key + ) + + if functionalize_schema is None: + hop_instance = HopInstance.create( + invoke_subgraph, subgraph, identifier, *operands + ) + if invoke_subgraph_cache and schema_cache_key is not None: + invoke_subgraph_cache.add_functionalize_schema_entry( + schema_cache_key, hop_instance._schema + ) + else: + hop_instance = HopInstance(invoke_subgraph, functionalize_schema) + + functionalized_identifier = None + if can_auto_functionalize(hop_instance): + # NOTE: [auto_functionalize x invoke_subgraph caching] + # invoke_subgraph is special because of its identifier based caching mechanism. + # In invoke_subgraph's functionalization key implementation, we create a new + # identifier because the subgraph is replaced by FunctionWithNoFreeVars in a + # functional + epilogue form. + if not isinstance(identifier, str): + raise AssertionError( + f"identifier must be a string for auto_functionalize, got {type(identifier)}" + ) + + if ctx.mode._keep_input_mutations: + # With keep_input_mutations=True, wrap invoke_subgraph in + # auto_functionalized_v2. This allows copy_ epilogues in the subgraph for + # Inductor to fuse where useful. + # See NOTE [Support input mutation of hops] for the overall design. + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + (subgraph, "auto_functionalized_" + identifier, *operands), + {}, + ) + + # With keep_input_mutations=False, the subgraph must not mutate its inputs. + # Return updated inputs so AOTAutograd can generate the copy_ epilogue. + mutated_operand_indices = tuple( + idx + for idx, arg in enumerate(hop_instance._schema.arguments[2:]) + if arg.alias_info is not None and arg.alias_info.is_write + ) + functionalized_subgraph = FunctionalizeCtxWrapper( + ctx, subgraph, mutated_input_indices=mutated_operand_indices + ) + functionalized_identifier = "functionalized_" + identifier + with ctx.redispatch_to_next(): + out = invoke_subgraph( + functionalized_subgraph, + functionalized_identifier, + *unwrapped_operands, + ) + + num_outputs = len(hop_instance._schema.returns) + actual_out = out[:num_outputs] + mutated_out = out[num_outputs:] + for operand_idx, updated_operand in zip(mutated_operand_indices, mutated_out): + operand = operands[operand_idx] + ctx.replace(operand, updated_operand) + ctx.commit_update(operand) + ctx.sync(operand) + out = actual_out + else: + with ctx.redispatch_to_next(): + # NB: There is an assumption that subgraph does not mutate inputs and + # there is no aliasing. It's Dynamo's responsibility to prevent formation + # of invoke_subgraph ops if input aliasing/mutation is detected. + functionalized_subgraph = FunctionalizeCtxWrapper(ctx, subgraph) + out = invoke_subgraph( + functionalized_subgraph, identifier, *unwrapped_operands + ) + + if effects: + (new_token, *out) = out + ctx.mode._tokens[effects] = new_token + + # (in the functionalization metadata phase) Capture tokens after and see if + # there are any differences (there are new effects or the token value for an + # effect type has changed) + tokens_after = dict(ctx.mode._tokens) + discovered_effects = set() + for effect_type, token in tokens_after.items(): + if effect_type not in tokens_before or tokens_before[effect_type] is not token: + discovered_effects.add(effect_type) + + if discovered_effects: + if not ctx.mode._allow_token_discovery: + raise AssertionError( + f"Number of tokens changed by {len(discovered_effects)} when tracing subgraph {subgraph}." + ) + # Later passes look up effects using the identifier on the emitted HOP. + if invoke_subgraph_cache: + invoke_subgraph_cache.add_effects(identifier, discovered_effects) + if functionalized_identifier is not None: + invoke_subgraph_cache.add_effects( + functionalized_identifier, discovered_effects + ) + + return ctx.wrap_tensors(out) + + +# Register the hop fake fn. This will be called in the fake_tensor _dispatch_impl. +@register_fake(invoke_subgraph) +def _(subgraph, identifier, *operands): + from torch._dynamo.utils import dynamo_timed + + with dynamo_timed("invoke_subgraph_fake_tensor", log_pt2_compile_event=True): + if getattr(subgraph, "_boxed_call", False): + return subgraph(list(operands)) + return subgraph(*operands) + + +@invoke_subgraph.py_impl(ProxyTorchDispatchMode) +def _(proxy_mode: ProxyTorchDispatchMode, subgraph, identifier, *operands): + # Check if we have already traced the subgraph. + graph = None + invoke_subgraph_cache = get_invoke_subgraph_cache() + if invoke_subgraph_cache: + graph = invoke_subgraph_cache.get_proxy_dispatch_entry(identifier) + + if graph is None: + from torch._dynamo.utils import dynamo_timed + + with dynamo_timed("invoke_subgraph_proxy_tensor", log_pt2_compile_event=True): + subgraph_decomp_table = _extract_nested_region_config(subgraph) + + # NB: invoke_subgraph subgraph re-trace seq_nr + # The joint graph seq_nr will get wrong in the subsequent re-trace (all nodes will have the same seq_nr), + # so we preserve the original graph's seq_nr here. + with torch.fx.traceback._preserve_node_seq_nr(): + graph = reenter_make_fx( + subgraph, subgraph_decomp_table=subgraph_decomp_table + )(*operands) + + # Propagate nested_region_config from the original subgraph to the + # re-traced graph so it's available for regional compilation. + if ( + isinstance(subgraph, torch.fx.GraphModule) + and hasattr(subgraph, "meta") + and "nested_region_config" in subgraph.meta + and "nested_region_config" not in graph.meta + ): + graph.meta["nested_region_config"] = subgraph.meta["nested_region_config"] + + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode(operands) + # Only insert deferred runtime asserts when we have dynamic shapes. + # When shape_env is None (static shapes), there are no deferred asserts to insert. + if fake_mode is not None and fake_mode.shape_env is not None: + insert_deferred_runtime_asserts( + graph, + fake_mode.shape_env, + "invoke_subgraph_proxy_torch_dispatch_mode", + export=True, + ) + graph.recompile() + + if not isinstance(proxy_mode.tracer, torch.fx.Tracer): + raise AssertionError( + f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}" + ) + if invoke_subgraph_cache: + invoke_subgraph_cache.add_proxy_dispatch_entry(identifier, graph) + + node_args = (graph, identifier, *operands) + + def _unwrap_proxy(arg): + if isinstance(arg, torch.fx.GraphModule): + # NOTE: [invoke_subgraph proxy_mode x auto_functionalize] + # Previously, we assumed that `invoke_subgraph` would always be traced with the same tracer. + # This allowed us to cache modules by their identifiers, assuming they were already registered. + # + # However, this assumption no longer holds when we auto-functionalize `invoke_subgraph`. + # auto_functionalize functionalizes the subgraph and wrap it with `FunctionWithNoFreeVars`. + # In the proxy mode implementation of `auto_functionalized_v2`, we need to materialize `FunctionWithNoFreeVars` + # input as a graph module. To do this, we re-trace the `invoke_subgraph` hop, which starts a new sub-tracer + # (see NOTE [materialize callable inputs as graph]). # When the new sub-tracer traces the `invoke_subgraph` + # with a previously cached identifier, the corresponding graph module might not + # exist as a submodule in the new tracer's root. Therefore, we register it as a submodule below. + # + # The alternative is to give a new identifier when we re-trace the invoke_subgraph but this will increase + # the compilation time, which defeats the purpose of caching. + registered_before = False + for ( + _, + submod, + ) in proxy_mode.tracer.root.named_modules(): # type: ignore[union-attr] + if arg is submod: + registered_before = True + + if not registered_before: + qualname = proxy_mode.tracer.get_fresh_qualname("repeated_subgraph") # type: ignore[union-attr] + proxy_mode.tracer.root.register_module(qualname, arg) # type: ignore[union-attr] + return proxy_mode.tracer.unwrap_proxy(arg) # type: ignore[union-attr] + + proxy_args = pytree.tree_map(_unwrap_proxy, node_args) # type: ignore[union-attr] + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", invoke_subgraph, proxy_args, {} + ) + + # Propagate nested_region_config to the node metadata so the regional + # inductor compiler can compile backward invoke_subgraph nodes. + # Dynamo sets this for forward nodes during tracing. For backward + # nodes created during joint tracing, the config lives on the subgraph + # module (set by InvokeSubgraphAutogradOp.backward) but may be wrapped + # by FunctionalizeCtxWrapper — unwrap to find it. + nested_config = None + orig_subgraph = ( + subgraph.subgraph if isinstance(subgraph, FunctionalizeCtxWrapper) else subgraph + ) + for gm in (graph, orig_subgraph): + if ( + isinstance(gm, torch.fx.GraphModule) + and hasattr(gm, "meta") + and "nested_region_config" in gm.meta + ): + nested_config = gm.meta["nested_region_config"] + break + + call_id = _current_invoke_subgraph_call_id() + + if nested_config is not None or call_id is not None: + node = out_proxy.node + if "custom" not in node.meta: + node.meta["custom"] = {} + if nested_config is not None: + node.meta["custom"]["nested_region_config"] = nested_config + if call_id is not None: + node.meta["custom"]["call_id"] = call_id + + example_out = invoke_subgraph(graph, identifier, *operands) + return track_tensor_tree( + example_out, out_proxy, constant=None, tracer=proxy_mode.tracer + ) + + +def invoke_subgraph_inductor_compile( + gm, example_inputs, inductor_config_patches=None, **kwargs +): + from torch._functorch._aot_autograd.runtime_wrappers import ( + SerializableCompiledFunction, + ) + from torch._functorch._aot_autograd.utils import simple_wraps + from torch._inductor import config + from torch._inductor.compile_fx import compile_fx_inner + from torch._inductor.standalone_compile import AOTCompiledArtifact + + # Used for testing only, should only be changed via _testing_capture_invoke_subgraph_inductor_compile_gms() + if ( + torch._dynamo.testing._testing_invoke_subgraph_inductor_compile_captured_gms + is not None + ): + torch._dynamo.testing._testing_invoke_subgraph_inductor_compile_captured_gms.append( + copy.deepcopy(gm) + ) + + if inductor_config_patches is None: + inductor_config_patches = {} + + # Saved tensors flow across the HOP boundary into a separately-compiled bw + # subgraph whose IR was traced with natural (unpadded) strides. Mark every + # output of this subgraph as user-visible so Inductor's comprehensive_padding + # leaves their strides alone — otherwise the bw's assert_size_stride on the + # incoming saved tensor will fire (e.g. F.linear output padded 200008 -> 200064). + from torch._inductor.compile_fx import _recursive_record_user_visible_output_idxs + + output_node = next(iter(gm.graph.find_nodes(op="output"))) + output_node.meta["user_visible_output_idxs"] = [ + idx + for idx in range(len(output_node.args[0])) + if isinstance(output_node.args[0][idx], torch.fx.Node) + ] + _recursive_record_user_visible_output_idxs(gm) + + compile_fn = config.patch(inductor_config_patches)(compile_fx_inner) + compiled_fn_inner = compile_fn(gm, example_inputs) + if not compiled_fn_inner._boxed_call: + raise AssertionError( + "compiled_fn_inner must have _boxed_call attribute set to True" + ) + + # Follow boxed calling convention + @simple_wraps(compiled_fn_inner) + def forward(*runtime_args: tuple[Any]): + full_args = [] + full_args.extend(runtime_args) + return compiled_fn_inner(full_args) + + # Just for convenience + forward.zero_grad = gm.zero_grad # type: ignore[attr-defined] + forward.named_parameters = gm.named_parameters # type: ignore[attr-defined] + forward.named_buffers = gm.named_buffers # type: ignore[attr-defined] + + # TODO: Do we need the post compile passes in _aot_stage2b_compile_forward_or_inference? + # TODO: add a real serialize function for SerializableCompiledFunction like _cache_inference_info + forward.serialize = SerializableCompiledFunction(forward, lambda: None) # type: ignore[attr-defined] + return AOTCompiledArtifact(forward) + + +def get_invoke_subgraph_compile_options( + fw_inductor_config_patches=None, + decompositions=None, + partitioner="min_cut_rematerialization_partition", + *, + bw_inductor_config_patches=None, +): + if fw_inductor_config_patches is None: + fw_inductor_config_patches = {"triton.autotune_at_compile_time": True} + + # The backward uses bw_inductor_config_patches when set (independently of the + # forward), otherwise it reuses the forward config. + bw_patches = ( + bw_inductor_config_patches + if bw_inductor_config_patches is not None + else fw_inductor_config_patches + ) + + from torch._inductor import config as inductor_config + + # Validate that all config keys exist + for patches in (fw_inductor_config_patches, bw_inductor_config_patches): + for key in patches or {}: + if not hasattr(inductor_config, key): + raise ValueError( + f"Invalid inductor config key '{key}' in get_invoke_subgraph_compile_options. " + f"Available config keys can be found in torch._inductor.config" + ) + + fw_compiler = functools.partial( + invoke_subgraph_inductor_compile, + inductor_config_patches=fw_inductor_config_patches, + ) + bw_compiler = functools.partial( + invoke_subgraph_inductor_compile, + inductor_config_patches=bw_patches, + ) + + return NestedCompileRegionOptions( + fw_compiler=fw_compiler, + bw_compiler=bw_compiler, + partitioner=partitioner, + decompositions=decompositions, + inductor_config_patches=fw_inductor_config_patches, + bw_inductor_config_patches=bw_inductor_config_patches, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/local_map.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/local_map.py new file mode 100644 index 0000000000000000000000000000000000000000..88d6cb542d0206d4eb4fa41a82575f83cc649230 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/local_map.py @@ -0,0 +1,664 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +# NOTE: this file may be removed once we move to a dynamo frontend + +import contextlib +from collections.abc import Callable, Generator, Sequence +from contextlib import contextmanager +from typing import Any, TypeAlias + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + clone_outputs_aliasing_inputs, + redirect_to_mode, + register_fake, + save_values_for_backward, + saved_values, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensor, is_fake_tensor +from torch._subclasses.functional_tensor import FunctionalTensor +from torch.fx import GraphModule +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode + + +# Proxy the HOP instead of inlining into it +# And trace it with local shapes for AP +_DEFER_INLINING = False + +GraphArg: TypeAlias = tuple[torch.Tensor, int, torch.SymInt, None] + + +@contextmanager +def defer_inlining() -> Generator[None, None, None]: + global _DEFER_INLINING + prior = _DEFER_INLINING + try: + _DEFER_INLINING = True + yield + finally: + _DEFER_INLINING = prior + + +# Used to unwrap tensors classes like FunctionalTensor and Parameter +def _new_tensor( + t: Any, + new_shape: Sequence[int] | None = None, + new_stride: Sequence[int] | None = None, +) -> Any: + if isinstance(t, torch.Tensor): + if type(t) not in (FunctionalTensor, FakeTensor, torch.Tensor): + raise AssertionError(f"No subclasses support for now, found {type(t)}") + return torch.empty_strided( + t.size() if new_shape is None else new_shape, + t.stride() if new_stride is None else new_stride, + device=t.device, + dtype=t.dtype, + requires_grad=t.requires_grad, + ) + return t + + +# Autoparallel specific, we want to treat plain tensors as DTensors +def _redistribute( + args: Any, + all_placements: tuple[Any], + mesh: Any, + shape_stride_fn: Callable[[torch.Tensor, Any, Any], tuple[list[int], list[int]]], +) -> GraphArg: + from torch._dispatch.python import suspend_functionalization + from torch._guards import detect_fake_mode + from torch._subclasses.functional_tensor import disable_functional_mode + from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing + + with ( + suspend_functionalization(), + disable_functional_mode(), + disable_proxy_modes_tracing(), + ): + fake_mode = detect_fake_mode(args) + if fake_mode is None: + raise AssertionError("defer_inlining() is only supported for FakeTensors") + + with fake_mode: + new_args = list(pytree.tree_map(_new_tensor, args)) + for i, (tensor, placements) in enumerate(zip(new_args, all_placements)): + if tensor is None: + # Sometimes gradients can be None + continue + + new_shape, new_stride = shape_stride_fn( + tensor, + mesh, + placements, + ) + new_args[i] = _new_tensor( + tensor, new_shape=new_shape, new_stride=new_stride + ) + + new_args = tuple(new_args) + if not all( + (is_fake_tensor(t) or isinstance(t, (int, torch.SymInt, type(None)))) + for t in new_args + ): + raise AssertionError(f"Unexpected element in {args=}") + + return new_args + + +def redistribute_fw_inputs( + global_args: Any, all_placements: Any, mesh: Any, _: int | None = None +) -> GraphArg: + if len(global_args) != len(all_placements): + raise AssertionError( + f"global_args length ({len(global_args)}) != all_placements length ({len(all_placements)})" + ) + return _redistribute( + global_args, + all_placements, + mesh, + torch.distributed.tensor._utils.compute_local_tensor_info, + ) + + +def redistribute_fw_outputs( + local_outs: Any, all_placements: Any, mesh: Any, num_activations: int +) -> GraphArg: + if len(local_outs) != len(all_placements) + num_activations: + raise AssertionError( + f"local_outs length ({len(local_outs)}) != " + f"all_placements length ({len(all_placements)}) + num_activations ({num_activations})" + ) + num_fw_outs = len(local_outs) - num_activations + if num_fw_outs <= 0: + raise AssertionError(f"num_fw_outs must be > 0, got {num_fw_outs}") + outs, activations = local_outs[:num_fw_outs], local_outs[num_fw_outs:] + return ( + *_redistribute( + outs, + all_placements, + mesh, + torch.distributed.tensor._utils.compute_global_tensor_info, + ), + *activations, + ) + + +def redistribute_bw_inputs( + global_args: Any, all_placements: Any, mesh: Any, num_activations: int +) -> GraphArg: + if len(global_args) != len(all_placements) + num_activations: + raise AssertionError( + f"global_args length ({len(global_args)}) != " + f"all_placements length ({len(all_placements)}) + num_activations ({num_activations})" + ) + activations, inputs = global_args[:num_activations], global_args[num_activations:] + if len(inputs) <= 0: + raise AssertionError("inputs must not be empty") + local_inputs = _redistribute( + inputs, + all_placements, + mesh, + torch.distributed.tensor._utils.compute_local_tensor_info, + ) + return ( + *activations, + *local_inputs, + ) + + +def redistribute_bw_outputs( + local_outs: Any, all_placements: Any, mesh: Any, _: int | None = None +) -> GraphArg: + if len(local_outs) != len(all_placements): + raise AssertionError( + f"local_outs length ({len(local_outs)}) != all_placements length ({len(all_placements)})" + ) + return _redistribute( + local_outs, + all_placements, + mesh, + torch.distributed.tensor._utils.compute_global_tensor_info, + ) + + +class LocalMapHOP(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("local_map_hop") + + def __call__(self, gm: GraphModule, *args: Any, **kwargs: Any) -> Any: + # pyrefly: ignore [missing-attribute] + return super().__call__(gm, *args, **kwargs) + + +local_map_hop = LocalMapHOP() + +# Registers dispatches for SAC +redirect_to_mode(local_map_hop, _CachingTorchDispatchMode) +redirect_to_mode(local_map_hop, _CachedTorchDispatchMode) + + +def create_hop_fw_bw( + fw_gm: GraphModule, + *_args: Any, +) -> tuple[GraphModule, GraphModule, int, int, set[int]]: + """ + Traces a joint, applies passes and partitions it + """ + # Keeping these imports here + # Avoid circular dependencies once we upstream with dynamo frontend + from torch._dispatch.python import suspend_functionalization + from torch._functorch.aot_autograd import AOTConfig, create_joint + from torch._guards import detect_fake_mode + from torch._subclasses.fake_tensor import FakeTensorMode + from torch._subclasses.functional_tensor import disable_functional_mode + from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing, make_fx + + local_map_kwargs = fw_gm.meta["local_map_kwargs"] # type: ignore[attr-defined] + if "in_placements" not in local_map_kwargs: + raise AssertionError("'in_placements' not found in local_map_kwargs") + if "out_placements" not in local_map_kwargs: + raise AssertionError("'out_placements' not found in local_map_kwargs") + if "device_mesh" not in local_map_kwargs: + raise AssertionError("'device_mesh' not found in local_map_kwargs") + if len(local_map_kwargs["in_placements"]) != len(_args): + raise AssertionError( + f"in_placements length ({len(local_map_kwargs['in_placements'])}) != _args length ({len(_args)})" + ) + + dummy_aot_config = AOTConfig( + fw_compiler=None, # type: ignore[arg-type] + bw_compiler=None, # type: ignore[arg-type] + partition_fn=None, # type: ignore[arg-type] + decompositions={}, + num_params_buffers=0, + aot_id=0, + keep_inference_input_mutations=False, + ) + + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + # If someone runs this hop under the default compiler backend ("eager") + # Then this path will be run with the actual user inputs. We convert them + # to fake tensors in order to not perform any actual compute. + + fake_mode = detect_fake_mode(_args) + if fake_mode is None: + fake_mode = FakeTensorMode(allow_non_fake_inputs=True) + + with fake_mode: + fw_inputs = redistribute_fw_inputs( + _args, + local_map_kwargs["in_placements"], + local_map_kwargs["device_mesh"], + ) + if len(fw_inputs) != len(local_map_kwargs["in_placements"]): + raise AssertionError( + f"fw_inputs length ({len(fw_inputs)}) != " + f"in_placements length ({len(local_map_kwargs['in_placements'])})" + ) + + if not all( + (is_fake_tensor(t) or isinstance(t, (int, torch.SymInt))) + for t in fw_inputs + ): + raise AssertionError(f"Unexpected element in {fw_inputs=}") + + ctx = ( + fake_mode.shape_env.ignore_fresh_unbacked_symbols + if fake_mode.shape_env is not None + else contextlib.nullcontext + ) + with ctx(): + fw_outs = fw_gm(*fw_inputs) + + example_grads = pytree.tree_map( + _new_tensor, + fw_outs, + ) + if not isinstance(example_grads, (list, tuple)): + example_grads = [example_grads] + + num_fw_inputs = len(fw_inputs) + num_fw_outputs = len(example_grads) + + def joint_f( + *primals_and_tangents: list[torch.Tensor], + ) -> Any: + primals = primals_and_tangents[:num_fw_inputs] + tangents = primals_and_tangents[num_fw_inputs:] + + def prepare_fw_with_masks( + fw_gm: torch.fx.GraphModule, + ) -> Callable[..., Any]: + def fw_with_masks(*args: Any) -> tuple[tuple[Any], list[bool]]: + # The Interpreter here is required to propagate metadata + # from the dynamo graph body to the local_map graph body. + # This is required for fx_traceback.annotate for work. + fw_out = torch.fx.Interpreter(fw_gm).run(*args) + if not isinstance(fw_out, tuple): + raise AssertionError( + "Dynamo traced submodule should return tuple" + ) + return fw_out, [ + bool(isinstance(ret, torch.Tensor) and ret.requires_grad) + for ret in fw_out + ] + + return fw_with_masks + + fw_outs, grads = create_joint( + prepare_fw_with_masks(fw_gm), aot_config=dummy_aot_config + )(primals, tangents) + from torch.fx.experimental.symbolic_shapes import has_free_unbacked_symbols + + if has_free_unbacked_symbols((*fw_outs, *grads)): + raise AssertionError( + "Unbacked symints leaking outside of the joint graph is not yet supported." + ) + + maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents) + # put grads first to work with existing hop utils + return pytree.tree_map(maybe_clone, (*grads, *fw_outs)) + + filtered_grads_idx = set() + for i, example_grad in enumerate(example_grads): + # Filter out grads that are None or do not require_grad. + # The AOTAutograd utils we rely on force this assumption. + # We must also filter the runtime tangents too. + if example_grad is not None and ( + isinstance(example_grad, torch.Tensor) and example_grad.requires_grad + ): + filtered_grads_idx.add(i) + + primals_and_tangents = [ + *fw_inputs, + *[example_grads[i] for i in filtered_grads_idx], + ] + joint_hop_gm = make_fx(joint_f)(*primals_and_tangents) + from torch._functorch._aot_autograd.graph_capture import ( + copy_fwd_metadata_to_bw_nodes, + ) + + copy_fwd_metadata_to_bw_nodes(joint_hop_gm) + + from torch._functorch._aot_autograd.graph_compile import prepare_for_partitioner + from torch._inductor.compile_fx import partition_fn + + # Match partitioner convention + prepped_joint_hop_gm = prepare_for_partitioner( + joint_hop_gm, num_fw_inputs, num_fw_outputs + ) + with disable_proxy_modes_tracing(): + # Also runs joint passes + new_fw_gm, new_bw_gm = partition_fn( + prepped_joint_hop_gm, + [], + num_fwd_outputs=num_fw_outputs, + static_lifetime_input_indices=[], + ) + + # Fix tags because min-cut does not respect fw/bw boundary, breaking + # default partitioner's assumptions. + for node in new_fw_gm.graph.nodes: + node.meta["partitioner_tag"] = "is_forward" + node.meta.pop("autograd_backward", None) + for node in new_bw_gm.graph.nodes: + node.meta["partitioner_tag"] = "is_backward" + node.meta["autograd_backward"] = True + + # Propagate meta onto fw/bw graphs, later will be set on proxied nodes + new_fw_gm.meta["local_map_kwargs"] = local_map_kwargs + new_bw_gm.meta["local_map_kwargs"] = {**local_map_kwargs} + # Okay because Autoparallel assumes same sharding between param and grads + new_bw_gm.meta["local_map_kwargs"]["in_placements"] = tuple( + [local_map_kwargs["out_placements"][i] for i in filtered_grads_idx] + ) + new_bw_gm.meta["local_map_kwargs"]["out_placements"] = local_map_kwargs[ + "in_placements" + ] + + # Validate Forward + fw_kwargs = new_fw_gm.meta["local_map_kwargs"] + expected_fw_inputs = len(fw_kwargs["in_placements"]) + expected_fw_outputs = len(fw_kwargs["out_placements"]) + actual_fw_inputs = len(new_fw_gm.graph.find_nodes(op="placeholder")) + actual_fw_outputs = num_fw_outputs + if expected_fw_inputs != actual_fw_inputs: + raise AssertionError( + f"expected_fw_inputs ({expected_fw_inputs}) != actual_fw_inputs ({actual_fw_inputs})" + ) + if expected_fw_outputs != actual_fw_outputs: + raise AssertionError( + f"expected_fw_outputs ({expected_fw_outputs}) != actual_fw_outputs ({actual_fw_outputs})" + ) + + # Validate Activations + if len(new_fw_gm.graph.find_nodes(op="output")) != 1: + raise AssertionError( + f"Expected exactly 1 output node, got {len(new_fw_gm.graph.find_nodes(op='output'))}" + ) + num_activations = ( + len(new_fw_gm.graph.find_nodes(op="output")[0].args[0]) - num_fw_outputs + ) + # tensors first, then symints + if num_activations < 0: + raise AssertionError(f"num_activations must be >= 0, got {num_activations}") + + # Validate Backward + bw_kwargs = new_bw_gm.meta["local_map_kwargs"] + expected_bw_inputs = len(bw_kwargs["in_placements"]) + expected_bw_outputs = len(bw_kwargs["out_placements"]) + actual_bw_inputs = ( + len(new_bw_gm.graph.find_nodes(op="placeholder")) - num_activations + ) + if actual_bw_inputs <= 0: + raise AssertionError( + f"actual_bw_inputs must be > 0, got {actual_bw_inputs}" + ) + if expected_fw_inputs + expected_bw_inputs != len(primals_and_tangents): + raise AssertionError( + f"expected_fw_inputs ({expected_fw_inputs}) + expected_bw_inputs ({expected_bw_inputs}) " + f"!= primals_and_tangents length ({len(primals_and_tangents)})" + ) + if actual_fw_inputs + actual_bw_inputs != len(primals_and_tangents): + raise AssertionError( + f"actual_fw_inputs ({actual_fw_inputs}) + actual_bw_inputs ({actual_bw_inputs}) " + f"!= primals_and_tangents length ({len(primals_and_tangents)})" + ) + if len(new_bw_gm.graph.find_nodes(op="output")) != 1: + raise AssertionError( + f"Expected exactly 1 bw output node, got {len(new_bw_gm.graph.find_nodes(op='output'))}" + ) + actual_bw_outputs = len(new_bw_gm.graph.find_nodes(op="output")[0].args[0]) + if expected_bw_inputs != actual_bw_inputs: + raise AssertionError( + f"expected_bw_inputs ({expected_bw_inputs}) != actual_bw_inputs ({actual_bw_inputs})" + ) + if expected_bw_outputs != actual_bw_outputs: + raise AssertionError( + f"expected_bw_outputs ({expected_bw_outputs}) != actual_bw_outputs ({actual_bw_outputs})" + ) + + new_fw_gm.meta["num_activations"] = num_activations + new_fw_gm.meta["is_backward"] = False + new_bw_gm.meta["num_activations"] = num_activations + new_bw_gm.meta["is_backward"] = True + + return new_fw_gm, new_bw_gm, num_fw_inputs, num_fw_outputs, filtered_grads_idx + + +class LocalMapAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx: Any, + fw_gm: GraphModule, + bw_gm: GraphModule, + num_fw_ins: int, + num_fw_outs: int, + filtered_grads_idx: set[int], + *args: Any, + **kwargs: Any, + ) -> tuple[torch.Tensor | None, ...]: + from torch._functorch._aot_autograd.schemas import MemoryFormatMeta + + ctx.bw_gm = bw_gm + ctx.num_fw_ins = num_fw_ins + ctx.filtered_grads_idx = filtered_grads_idx + + with torch._C._AutoDispatchBelowAutograd(): + fw_outs_with_saved_activations = local_map_hop(fw_gm, *args, **kwargs) + + fw_outs = fw_outs_with_saved_activations[:num_fw_outs] + saved_activations = fw_outs_with_saved_activations[num_fw_outs:] + save_values_for_backward(ctx, saved_activations) + + # Force memory_format path (not exact size/stride) because local_map forward + # operates on local shapes but backward receives global-shaped tangents. + # TODO(ivankobzarev): Support exact size/stride by converting between local/global shapes. + ctx.expected_tangent_metadata = { + i: MemoryFormatMeta.from_tensor(fw_outs[i], force_use_memory_format=True) + for i in filtered_grads_idx + } + return fw_outs + + @staticmethod + def backward( + ctx: Any, *_grads: tuple[torch.Tensor] + ) -> tuple[torch.Tensor | None, ...]: + from torch._functorch._aot_autograd.runtime_wrappers import ( + coerce_to_expected_memory_format, + ) + + if ctx.pos != sorted(ctx.pos): + raise AssertionError( + "Interleaving saved tensor activations and symints is not expected from min-cut partitioner." + ) + ctx.pos = list(reversed(ctx.pos)) # make saved_values return symints first + saved_activations = saved_values(ctx) + with torch._C._AutoDispatchBelowAutograd(): + # Filter out grads that are None or do not require_grad. + # The AOTAutograd utils we rely on force this assumption. + grads = [_grads[i] for i in ctx.filtered_grads_idx] + if len(grads) != len(ctx.expected_tangent_metadata): + raise AssertionError( + f"{len(grads)=} vs {len(ctx.expected_tangent_metadata)}" + ) + + for i, meta in ctx.expected_tangent_metadata.items(): + grads[i] = coerce_to_expected_memory_format(grads[i], meta) + + grad_ins = local_map_hop(ctx.bw_gm, *saved_activations, *grads) + if len(grad_ins) != ctx.num_fw_ins: + raise RuntimeError( + f"Expected {ctx.num_fw_ins} grad_ins, got {len(grad_ins)}" + ) + return None, None, None, None, None, *grad_ins + + +@local_map_hop.py_impl(torch._C.DispatchKey.Autograd) +def autograd_key( + fw_gm: GraphModule, + *args: Any, + **kwargs: Any, +) -> Any: + local_map_kwargs = fw_gm.meta["local_map_kwargs"] # type: ignore[attr-defined] + if local_map_kwargs.get("in_grad_placements", None) is not None: + raise AssertionError("local_map in_grad_placements are not yet supported.") + if _DEFER_INLINING: + fw_gm, bw_gm, num_fw_ins, num_fw_outs, filtered_grads_idx = create_hop_fw_bw( + fw_gm, *args + ) + return LocalMapAutogradOp.apply( + fw_gm, bw_gm, num_fw_ins, num_fw_outs, filtered_grads_idx, *args, **kwargs + ) + + # TODO: get rid of this when we can install as a subgraph + return torch.fx.Interpreter(fw_gm).run(*args, **kwargs) + + +@local_map_hop.py_functionalize_impl +def functional_mode_key( + ctx: Any, gm: GraphModule, *args: Any, **kwargs: Any +) -> tuple[torch.Tensor]: + if kwargs: + raise AssertionError(f"kwargs must be empty, got {kwargs}") + + unwrapped_inputs = ctx.unwrap_tensors(args) + with ctx.redispatch_to_next(): + out = local_map_hop(gm, *unwrapped_inputs) + return ctx.wrap_tensors(out) + + +@register_fake(local_map_hop, skip_cache=True) +def fake_mode_key( + gm: GraphModule, + *args: Any, + **kwargs: Any, +) -> GraphArg: + if not _DEFER_INLINING: + return gm(*args, **kwargs) + + # otherwise, we need to convert to local shapes for AP + # invoke_subgraph runs its body below Autograd, so local_map_hop's Autograd + # key may not have partitioned the body or set fw/bw metadata. + is_backward = gm.meta.get("is_backward", False) + num_activations = gm.meta.get("num_activations", 0) + redistribute_inputs = ( + redistribute_bw_inputs if is_backward else redistribute_fw_inputs + ) + local_args = redistribute_inputs( + args, + gm.meta["local_map_kwargs"]["in_placements"], + gm.meta["local_map_kwargs"]["device_mesh"], + num_activations, + ) + local_outs = gm(*local_args) + redistribute_outputs = ( + redistribute_bw_outputs if is_backward else redistribute_fw_outputs + ) + global_outs = redistribute_outputs( + local_outs, + gm.meta["local_map_kwargs"]["out_placements"], + gm.meta["local_map_kwargs"]["device_mesh"], + num_activations, + ) + return global_outs + + +def _proxy_mode_arg( + proxy_mode: ProxyTorchDispatchMode, + arg: Any, +) -> Any: + if isinstance(arg, torch.fx.GraphModule): + # Install local_map bodies as real submodules so FX source emission can + # reload them through self instead of closing over a local Python target. + registered = any( + arg is submod + for _, submod in proxy_mode.tracer.root.named_modules() # type: ignore[union-attr] + ) + if not registered: + qualname = proxy_mode.tracer.get_fresh_qualname("local_map_body") # type: ignore[union-attr] + proxy_mode.tracer.root.register_module(qualname, arg) # type: ignore[union-attr] + return proxy_mode.tracer.unwrap_proxy(arg) # type: ignore[union-attr] + + +def proxy_mode_key_common( + proxy_mode: ProxyTorchDispatchMode, + gm: GraphModule, + *args: Any, + **kwargs: Any, +) -> tuple[torch.Tensor]: + if proxy_mode is None: + raise AssertionError("Mode should always be enabled for python fallback key") + if len(kwargs) != 0: + raise AssertionError(f"kwargs must be empty, got {kwargs}") + + example_out = local_map_hop(gm, *args, **kwargs) + proxy_args = pytree.tree_map( + lambda arg: _proxy_mode_arg(proxy_mode, arg), + (gm, *args), + ) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", local_map_hop, proxy_args, {} + ) + + # extract local_map args, post-dispatch operates on GraphModules + if not gm.meta["local_map_kwargs"]: + raise AssertionError("gm.meta['local_map_kwargs'] must be set") + local_map_kwargs = gm.meta["local_map_kwargs"] + + # propagate local_map args to the call_function node + out_proxy.node.meta["local_map_kwargs"] = local_map_kwargs + + return track_tensor_tree( + example_out, out_proxy, constant=None, tracer=proxy_mode.tracer + ) + + +@local_map_hop.py_impl(ProxyTorchDispatchMode) +def proxy_mode_key( + proxy_mode: ProxyTorchDispatchMode, + gm: GraphModule, + *args: Any, + **kwargs: Any, +) -> tuple[torch.Tensor]: + return proxy_mode_key_common(proxy_mode, gm, *args, **kwargs) + + +# Running HOP in eager with real tensors +@local_map_hop.py_impl(DispatchKey.CompositeExplicitAutograd) +def real_impl( + gm: GraphModule, + *args: Any, + **kwargs: Any, +) -> tuple[torch.Tensor]: + return gm(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/map.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/map.py new file mode 100644 index 0000000000000000000000000000000000000000..f1c3f4119fcd508218e763a6fc4ec5ae0b1300e3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/map.py @@ -0,0 +1,426 @@ +# mypy: allow-untyped-defs +import functools +from collections.abc import Callable, Sequence +from typing import Any +from typing_extensions import TypeVarTuple + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._dispatch.python import suspend_functionalization +from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, +) +from torch._higher_order_ops.utils import ( + _from_fun, + _maybe_run_with_interpreter, + _stack_pytree, + _unstack_pytree, + create_bw_fn, + fill_none_with_masks, + filter_with_masks, + first_slice_copy, + get_graph_output_example_values, + HopInstance, + materialize_as_graph, + reenter_make_fx, + register_fake, + save_values_for_backward, + saved_values, + split_into_chunks, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.functional_tensor import disable_functional_mode +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +class MapImpl(HigherOrderOperator): + def __init__(self): + super().__init__("map_impl") + + def __call__( + self, + f: Callable[..., Any], + xs: Sequence[torch.Tensor], + pos_args: Sequence[torch.fx.node.BaseArgumentTypes], + *, + mutated_arg_indices: str = "", + ) -> Any: + # pyrefly: ignore [missing-attribute] + return super().__call__( + f, xs, pos_args, mutated_arg_indices=mutated_arg_indices + ) + + # pyrefly: ignore [bad-override] + def gen_schema(self, f, xs, pos_args, mutated_arg_indices: str = ""): + from torch._higher_order_ops.schema import HopSchemaGenerator + + all_inputs = tuple( + [ + torch.empty_strided( + x.shape[1:], + x.stride()[1:], + dtype=x.dtype, + device=x.device, + requires_grad=x.requires_grad, + ) + for x in xs + ] + + list(pos_args) + ) + body_gm = materialize_as_graph(f, all_inputs) + + # Mutation semantics for map: + # - xs is mutable: each iteration sees a storage-disjoint slice + # (xs[t] and xs[t+1] share no storage), so in-place writes are + # race-free regardless of evaluation order, preserving map's + # "iterations are independent" contract. + # - pos_args is NOT mutable: every iteration sees the same + # tensor, so mutating it makes iterations depend on each + # other, breaking the independence contract and introducing a + # data race under any parallel lowering. Users who need a + # shared mutable buffer should use scan / while_loop, where + # sequential iteration is part of the contract. + outputs = get_graph_output_example_values(body_gm) + mutated_set = {int(i) for i in mutated_arg_indices.split(",") if i} + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("f", body_gm) + + for idx, x in enumerate(xs): + schema_gen.add_arg(f"xs{idx}", x, is_mutated=idx in mutated_set) + + for idx, arg in enumerate(pos_args): + schema_gen.add_arg(f"additional_input{idx}", arg) + + for out in outputs: + schema_gen.add_output(out) + + schema_gen.add_schema_tree_spec(f, xs, pos_args) + return schema_gen.gen_schema() + + +map_impl = MapImpl() + + +def map( + f: Callable[[pytree.PyTree, tuple[pytree.PyTree, ...]], pytree.PyTree], + xs: pytree.PyTree | torch.Tensor, + *args: TypeVarTuple, +): + r""" + Performs a map of f with xs. Intuitively, you can think of the semantic being:: + + out = [] + for idx in len(xs.size(0)): + xs_sliced = xs.select(0, idx) + out.append(f(xs_sliced, *args)) + torch.stack(out) + + .. warning:: + + ``torch._higher_order_ops.map`` is a prototype feature in PyTorch. It currently + does not support autograd and you may run into miscompiles. + Read more about feature classification at: + https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + + Args: + f (Callable): a callable that takes an input x, that could either be a single Tensor + or a nested dict, list of tensors and some additional inputs + xs: the inputs that're to be mapped over. We'll iterate over the first dim of each x + and perform f on each slice. + + *args: additional arguments provided to each step of f. They could also be omitted and + map is able to automatically figure out the read dependency. + + Return: + the stacked output for each step of f + + Example:: + + def f(xs): + return xs[0] + xs[1] + const1 + const2 + + + xs = [torch.randn(2, 3), torch.randn(2, 3)] + const1 = torch.randn(2, 3) + const2 = torch.randn(2, 3) + # returns a tensor of shape [2, 2, 3] + torch._higher_order_ops.map(f, xs) + + """ + flat_xs, xs_spec = pytree.tree_flatten(xs) + flat_args, args_spec = pytree.tree_flatten(args) + if not all(isinstance(t, torch.Tensor) for t in flat_xs): + raise RuntimeError(f"Mapped xs can only consist of tensors. Got xs {flat_xs}.") + + shapes = [xs.shape for xs in flat_xs] + leading_dim_size = shapes[0][0] + if leading_dim_size == 0: + raise RuntimeError("Leading dimensions of mapped xs cannot be 0.") + + if any(cur_shape[0] != leading_dim_size for cur_shape in shapes): + raise RuntimeError( + f"Leading dimensions of mapped xs must be consistent. Got shapes {shapes}." + ) + + def run_flattened_map(f, flat_xs, flat_args): + def wrapped_fn(*flat_args, f, xs_tree_spec, args_tree_spec, num_xs): + xs = pytree.tree_unflatten(flat_args[:num_xs], xs_tree_spec) + args = pytree.tree_unflatten(flat_args[num_xs:], args_tree_spec) + return f(xs, *args) + + inner_f = functools.partial( + wrapped_fn, + f=f, + xs_tree_spec=xs_spec, + args_tree_spec=args_spec, + num_xs=len(flat_xs), + ) + return map_impl(inner_f, flat_xs, flat_args) + + from torch._higher_order_ops.utils import _maybe_compile_and_run_fn + + return _maybe_compile_and_run_fn(run_flattened_map, f, flat_xs, flat_args) + + +class MapAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx, f, num_mapped_args, *flat_args): + ctx._f = f + ctx._num_mapped_args = num_mapped_args + ctx._num_pos_args = len(flat_args) - num_mapped_args + + # We snapshot the dispatch keys in forward for materializing + # the bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + save_values_for_backward(ctx, flat_args) + with torch._C._AutoDispatchBelowAutograd(): + return ( + *map_impl(f, flat_args[:num_mapped_args], flat_args[num_mapped_args:]), + ) + + @staticmethod + def backward(ctx, *flat_grads): + fw_args = saved_values(ctx) + num_mapped_args = ctx._num_mapped_args + num_pos_args = ctx._num_pos_args + num_grads = len(flat_grads) + + fw_mapped_args, pos_args = split_into_chunks( + fw_args, + [ + num_mapped_args, + num_pos_args, + ], + ) + + bw_f = create_bw_fn(ctx._f, fw_args) + + grads_tensor_masks = [] + + # Create a wrapper around thefor the bw_f + def bw_f_wrapper(*args): + nonlocal grads_tensor_masks + + # Dissect args and re-order them for the ``ctx._bw_f`` + # args provided to the wrapper are composed of [*fw_mapped_args, *flat_grads, *pos_args] + # The content of ``bw_f_tangents`` are the upstream gradients, i.e. flat_grads + # The content of ``bw_f_primals`` are the fw_args, i.e., [*fw_mapped_args, *pos_args] + # The bw_f requires *bw_f_primals, *bw_f_tangents + fw_m_args, bw_f_tangents, pos_args = split_into_chunks( + args, [num_mapped_args, num_grads, num_pos_args] + ) + bw_f_primals = *fw_m_args, *pos_args + gradients = bw_f(*bw_f_primals, *bw_f_tangents) + grads_tensor_masks = [ + True if isinstance(out, torch.Tensor) else out for out in gradients + ] + return filter_with_masks(gradients, grads_tensor_masks) + + def construct_args_single_step_bw(): + unwrapped_mapped_xs = pytree.tree_map(_from_fun, fw_mapped_args) + # Use first_slice_copy instead of _unstack_pytree to avoid + # iterating over batch dim, which would guard on symbolic sizes. + example_xs = [ + first_slice_copy(x).requires_grad_(x.requires_grad) + for x in unwrapped_mapped_xs + ] + unwrapped_grads = pytree.tree_map(_from_fun, flat_grads) + example_grads = [ + first_slice_copy(x).requires_grad_(x.requires_grad) + for x in unwrapped_grads + ] + example_pos_args = [ + _from_fun(arg) if isinstance(arg, torch.Tensor) else arg + for arg in pos_args + ] + return *example_xs, *example_grads, *example_pos_args + + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + args_single_step_bw = construct_args_single_step_bw() + + # TODO: we need to materialize the bw graphs because dynamo is unable to + # trace through the joint function when torch.compile torch.autograd.grad. + fn_bw_gm = materialize_as_graph( + bw_f_wrapper, + args_single_step_bw, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + + grads = map_impl(fn_bw_gm, fw_mapped_args + flat_grads, pos_args) + + return None, None, *fill_none_with_masks(grads, grads_tensor_masks) + + +def _broadcast_to_batch(output, batch_size): + """Expand each tensor in output pytree to include batch dimension. + + Note: Although outputs are flattened in the compiled path (via torch.compile), + users may call map_impl directly with pytree outputs, so we support pytrees + for backward compatibility. + """ + + def expand_with_batch(t): + if isinstance(t, torch.Tensor): + # Use contiguous_format to match torch.stack behavior + return ( + t.unsqueeze(0) + .expand(batch_size, *t.shape) + .clone(memory_format=torch.contiguous_format) + ) + return t + + return pytree.tree_map(expand_with_batch, output) + + +def trace_map( + proxy_mode, + func_overload: HigherOrderOperator, + f: Callable[..., Any], + xs: Sequence[torch.Tensor], + pos_args: Sequence[torch.fx.node.BaseArgumentTypes], + mutated_arg_indices: str = "", +) -> Any: + with disable_proxy_modes_tracing(): + # Use first_slice_copy instead of _unstack_pytree to avoid + # iterating over batch dim, which would guard on symbolic sizes. + example_input = pytree.tree_map(first_slice_copy, xs) + + body_graph = reenter_make_fx(f)(*example_input, *pos_args) + + next_name = proxy_mode.tracer.get_fresh_qualname("body_graph_") + proxy_mode.tracer.root.register_module(next_name, body_graph) + + fake_outs = map_impl( + body_graph, xs, pos_args, mutated_arg_indices=mutated_arg_indices + ) + + node_args = (body_graph, list(xs), list(pos_args)) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", + func_overload, + proxy_args, + {"mutated_arg_indices": mutated_arg_indices} if mutated_arg_indices else {}, + name="map_impl", + ) + return track_tensor_tree( + fake_outs, out_proxy, constant=None, tracer=proxy_mode.tracer + ) + + +@map_impl.py_impl(DispatchKey.CompositeExplicitAutograd) +def map_dense(f, xs, pos_args, mutated_arg_indices=""): + pytrees = [f(*inp, *pos_args) for inp in _unstack_pytree(xs)] + return _stack_pytree(pytrees) + + +@map_impl.py_autograd_impl +def map_autograd(f, xs, pos_args, mutated_arg_indices=""): + num_mapped_args = len(xs) + flat_out = MapAutogradOp.apply(f, num_mapped_args, *xs, *pos_args) + return flat_out + + +@map_impl.py_impl(ProxyTorchDispatchMode) +def map_proxy_torch_dispatch_mode(mode, f, xs, pos_args, mutated_arg_indices=""): + return trace_map( + mode, map_impl, f, xs, pos_args, mutated_arg_indices=mutated_arg_indices + ) + + +@register_fake(map_impl, skip_cache=True) +def map_fake_tensor_mode(f, xs, pos_args, mutated_arg_indices=""): + # Use first_slice_copy instead of _unstack_pytree to avoid + # iterating over batch dim, which would guard on symbolic sizes. + first_row = pytree.tree_map(first_slice_copy, xs) + example_output = f(*first_row, *pos_args) + + flat_xs, _ = pytree.tree_flatten(xs) + batch_size = flat_xs[0].shape[0] + + return _broadcast_to_batch(example_output, batch_size) + + +@map_impl.py_functionalize_impl +def map_functionalize(ctx, f, xs, pos_args, mutated_arg_indices=""): + from torch._higher_order_ops.utils import _check_alias_and_mutation + + if hasattr(ctx, "mode"): + hop_instance = HopInstance.create( + map_impl, + f, + xs, + pos_args, + mutated_arg_indices=mutated_arg_indices, + ) + if can_auto_functionalize(hop_instance): + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + tuple(pytree.tree_flatten((f, xs, pos_args))[0]), + {}, + ) + + unwrapped_xs = ctx.unwrap_tensors(xs) + unwrapped_args = ctx.unwrap_tensors(pos_args) + wrapped_fn = ctx.functionalize(_maybe_run_with_interpreter(f)) + + with ctx.redispatch_to_next(): + # Use first_slice_copy instead of _unstack_pytree to avoid + # iterating over batch dim, which would guard on symbolic sizes. + example_inputs = ( + *pytree.tree_map(first_slice_copy, unwrapped_xs), + *unwrapped_args, + ) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + _check_alias_and_mutation(f, example_inputs, "map", pre_dispatch) + map_return = map_impl( + wrapped_fn, + unwrapped_xs, + unwrapped_args, + mutated_arg_indices=mutated_arg_indices, + ) + return ctx.wrap_tensors(map_return) + + +def _fake_map(f, x, *args): + from functorch.experimental.control_flow import _stack_pytree, _unstack_pytree + + x_pytrees = _unstack_pytree(x) + zs = [] + for xp in x_pytrees: + zs.append(f(xp, *args)) + return _stack_pytree(zs) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/out_dtype.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/out_dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..75dbf8e79f421ea5fe3a6987ff958b358b48c149 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/out_dtype.py @@ -0,0 +1,161 @@ +# mypy: allow-untyped-defs + +import torch +import torch.utils._pytree as pytree +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 elementwise_dtypes, ELEMENTWISE_TYPE_PROMOTION_KIND +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + maybe_handle_decomp, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +# TODO to figure out a more generic approach +ALLOWABLE_OPS = [ + torch.ops.aten.linear.default, + torch.ops.aten.mm.default, + torch.ops.aten.conv2d.default, + torch.ops.aten.convolution.default, + torch.ops.aten.mul.Tensor, + torch.ops.aten.mul.Scalar, + torch.ops.aten.div.Tensor, + torch.ops.aten.div.Scalar, +] + + +class OutDtypeOperator(HigherOrderOperator): + """ + The out_dtype operator takes an existing ATen functional operator, an + `out_dtype` argument, and arguments to the original operator, and executes + the original operator and returns a Tensor with the `out_dtype` precision. + This operator does not mandate a compute precision so it allows the + representation to not be opinionated about the exact implementation. + + The general implementation for all operators will be the following: + 1. Promote inputs dtypes based on default PyTorch dtype promotion rules, + using the dtypes of all input Tensors/Scalars and the `out_dtype` + argument. + 2. Execute the operator + 3. Cast the output to `out_dtype` + """ + + def __init__(self) -> None: + super().__init__("out_dtype") + + def __call__(self, op, output_dtype, *args): + if not isinstance(op, torch._ops.OpOverload): + raise ValueError("out_dtype's first argument must be an OpOverload") + if op._schema.is_mutable: + raise ValueError( + "out_dtype's first argument needs to be a functional operator" + ) + if not ( + len(op._schema.returns) == 1 + and isinstance(op._schema.returns[0].type, torch.TensorType) + ): + raise ValueError( + "out_dtype's can only apply to ops that return a single tensor" + f"Instead got {[r.type for r in op._schema.returns]}" + ) + + if op not in ALLOWABLE_OPS: + raise ValueError( + f"out_dtype only allows the following operators: {ALLOWABLE_OPS}." + ) + + # pyrefly: ignore [missing-attribute] + res = super().__call__(op, output_dtype, *args) + + return res + + +out_dtype = OutDtypeOperator() + + +def trace_out_dtype(proxy_mode, func_overload, op, output_dtype, *args): + # NB: Long-term we should put the decomposition logic into + # ProxyTorchDispatchMode so that people do not need to call maybe_handle_decomp + # in all HigherOrderOp proxy implementations. + r = maybe_handle_decomp(proxy_mode, func_overload, (op, output_dtype, *args), {}) + if r is not NotImplemented: + return r + + with disable_proxy_modes_tracing(): + # This is a simplified implementation of this operator just for tracing. + # Actual implementation may also first promote the arguments + out = op(*args).to(dtype=output_dtype) + + node_args = (op, output_dtype, *args) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {}, name="out_dtype" + ) + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@out_dtype.py_impl(DispatchKey.CompositeExplicitAutograd) +def out_dtype_dense(op: torch._ops.OpOverload, output_dtype: torch.dtype, *args): + if is_int_mm(op, output_dtype, args): + return torch._int_mm(*args) + return out_dtype_fallback(op, output_dtype, *args) + + +def is_int_mm(op, output_dtype, args): + return ( + op is torch.ops.aten.mm.default + and output_dtype == torch.int32 + and len(args) == 2 + and args[0].dtype == torch.int8 + and args[1].dtype == torch.int8 + and (args[0].is_cuda or args[0].is_xpu) + and (args[1].is_cuda or args[1].is_xpu) + ) + + +def out_dtype_fallback(op, output_dtype, *args): + flat_inputs = pytree.arg_tree_leaves(*args) + [torch.ones(1, dtype=output_dtype)] + promote_dtype: torch.dtype = elementwise_dtypes( + *flat_inputs, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + )[0] + + casted_args = pytree.tree_map_only( + torch.Tensor, lambda arg: arg.to(dtype=promote_dtype), args + ) + res = op(*casted_args).to(dtype=output_dtype) + return res + + +out_dtype.py_autograd_impl(autograd_not_implemented(out_dtype, deferred_error=True)) + + +@out_dtype.py_impl(ProxyTorchDispatchMode) +def out_dtype_proxy( + mode: ProxyTorchDispatchMode, + op: torch._ops.OpOverload, + output_dtype: torch.dtype, + *args, +): + return trace_out_dtype(mode, out_dtype, op, output_dtype, *args) + + +@register_fake(out_dtype, skip_cache=True) +def out_dtype_fake_tensor_mode( + op: torch._ops.OpOverload, + output_dtype: torch.dtype, + *args, +): + return out_dtype_dense(op, output_dtype, *args) + + +@out_dtype.py_functionalize_impl +def out_dtype_func(ctx, op, output_dtype, *args): + unwrapped_args = tuple(ctx.unwrap_tensors(arg) for arg in args) + + with ctx.redispatch_to_next(): + res = out_dtype(op, output_dtype, *unwrapped_args) + return ctx.wrap_tensors(res) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/partitioner.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/partitioner.py new file mode 100644 index 0000000000000000000000000000000000000000..7bdcc24e45e75d730eb74f8da1653e19f7c6869f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/partitioner.py @@ -0,0 +1,378 @@ +import logging +from collections.abc import Callable +from typing import Any + +import torch +from torch._higher_order_ops.utils import create_bw_fn, materialize_as_graph + + +logger: logging.Logger = logging.getLogger(__name__) + + +def _find_hop_subgraph_outputs(gm: torch.fx.GraphModule) -> tuple[torch.fx.Node]: + output_node_args = gm.graph.find_nodes(op="output")[0].args + if not isinstance(output_node_args, tuple): + raise AssertionError( + f"expected output_node_args to be tuple, got {type(output_node_args)}" + ) + return output_node_args[0] + + +def is_complex_expr(expr: Any) -> bool: + return not expr.is_symbol and not expr.is_constant() + + +class HopPartitionedGraph: + def __init__( + self, + fw_gm: torch.fx.GraphModule, + bw_gm: torch.fx.GraphModule, + n_fw_outputs: int, + n_intermediates: int, + no_complex_exprs_at_boundary: bool, + ): + self.fw_gm = fw_gm + self.bw_gm = bw_gm + self.n_fw_outputs = n_fw_outputs + self.n_intermediates = n_intermediates + self.no_complex_exprs_at_boundary = no_complex_exprs_at_boundary + self._reorder_fw_output() + self._check_partition_boundary() + + def _check_partition_boundary(self) -> None: + """check partitioned graph is in valid state.""" + invalid_reasons = [] + fw_outputs = _find_hop_subgraph_outputs(self.fw_gm) + for i, out in enumerate(fw_outputs): + if "val" not in out.meta: + invalid_reasons.append(f"fw_gm output[{i}] doesn't have a 'val' meta.") + elif not isinstance(out.meta["val"], (torch.SymInt, torch.Tensor)): + invalid_reasons.append( + f"fw_gm output[{i}] is of type {type(out.meta['val'])} but only SymInt or Tensor are allowed." + ) + + elif ( + isinstance(out.meta["val"], torch.SymInt) + and is_complex_expr(out.meta["val"].node.expr) + and self.no_complex_exprs_at_boundary + ): + invalid_reasons.append( + f"fw_gm output[{i}] must be of type SymInt with basic symbols or " + f"Tensor but got {type(out.meta['val'])} {out.meta['val']}" + ) + + if len(fw_outputs) != self.n_fw_outputs + self.n_intermediates: + invalid_reasons.append( + f"len(fw_outputs) ({len(fw_outputs)}) != n_fw_outputs ({self.n_fw_outputs}) + n_intermediates ({self.n_intermediates})" + ) + + bw_phs = list(self.bw_gm.graph.find_nodes(op="placeholder")) + + if len(fw_outputs) != len(bw_phs): + invalid_reasons.append( + f"Expect number of fw_gm's output to be the same as bw_gm's input but " + f"fw_gm has {len(fw_outputs)} outputs, bw_gm takes {len(bw_phs)} inputs." + ) + + original_forward_outputs = fw_outputs[: self.n_fw_outputs] + fw_intermediates = fw_outputs[self.n_fw_outputs :] + + bw_intermediates = bw_phs[: -self.n_fw_outputs] + bw_grads = bw_phs[-self.n_fw_outputs :] + + def _match_size_or_expr( + val1: torch.SymInt | torch.Tensor, + val2: torch.SymInt | torch.Tensor, + ) -> bool: + if type(val1) is not type(val2): + return False + + if isinstance(val1, torch.SymInt) and isinstance(val2, torch.SymInt): + return val1.node.expr == val2.node.expr + elif isinstance(val1, torch.Tensor) and isinstance(val2, torch.Tensor): + return val1.size() == val2.size() + + return False + + for fw, bw in zip(fw_intermediates, bw_intermediates): + if fw.name != bw.name or not _match_size_or_expr( + fw.meta["val"], bw.meta["val"] + ): + invalid_reasons.append("fw intermediates don't match bw intermediates") + + for fw_out, bw_grad in zip(original_forward_outputs, bw_grads): + if not _match_size_or_expr(fw_out.meta["val"], bw_grad.meta["val"]): + invalid_reasons.append("fw outputs don't match bw gradients") + + if len(invalid_reasons) > 0: + newline = "\n" + raise RuntimeError( + f"Invalid HopPartitionedGraph. Reasons:\n{newline.join(invalid_reasons)}" + ) + + def _reorder_fw_output(self) -> None: + """ + Before the pass, fw_gm returns (*fw_outputs, *intermediates1) + and bw_gm takes (*intermediates2, *grad_fw_outputs) as input. + intermediates1 and intermediates2 share the same node names but + they might be in different order. E.g. this could happen if there + are inputs that contain symints. + + To simplify downstream processing, this graph pass normalizes the output of fw_gm + to be consistent with the backward inputs: + + fw_gm: + - input: fw_args + - output: (*fw_outputs, *intermediates) + + bw_gm: + - input: (*intermediates, *grad_fw_outputs) + - output: grad_fw_args + + Example: + + def fw_gm(x, y, z): + a, b, c = f(x), g(y), k(z) + return a, b, c, f_tmp, g_tmp, k_tmp + + , where a, b, c are fw_outputs, f_tmp, g_tmp, k_tmp are intermediates + + The corresponding bw_gm has the following signature: + + def bw_gm(f_tmp, g_tmp, k_tmp, grad_a, grad_b, grac): + return grad_x, grad_y, grad_z + """ + fw_gm_output_nodes = _find_hop_subgraph_outputs(self.fw_gm) + fw_outputs_nodes = fw_gm_output_nodes[: self.n_fw_outputs] + fw_intermediates_nodes = fw_gm_output_nodes[self.n_fw_outputs :] + if len(fw_intermediates_nodes) > 0: + fw_intermediates_name_to_node = {n.name: n for n in fw_intermediates_nodes} + + # First n_intermediates placeholders + bw_names: list[str] = [ + ph.name + for ph in list(self.bw_gm.graph.find_nodes(op="placeholder"))[ + : self.n_intermediates + ] + ] + new_fw_outputs = list(fw_outputs_nodes) + [ + fw_intermediates_name_to_node[name] for name in bw_names + ] + + output_node = self.fw_gm.graph.find_nodes(op="output")[0] + output_node.args = (tuple(new_fw_outputs),) + + self.fw_gm.graph.lint() + self.fw_gm.recompile() + + +class HopJointGraph: + def __init__( + self, + joint_gm: torch.fx.GraphModule, + n_primals: int, + n_fw_outputs: int, + *, + functionalized: bool, + ): + self.joint_gm = joint_gm + self.n_primals = n_primals + self.n_fw_outputs = n_fw_outputs + self.functionalized = functionalized + + self._rename_phs() + self._remove_redundant_sym_size_ops() + + def _rename_phs(self) -> None: + """ + Rename the placeholders for joint_gm so that the partitioner + could recognize which inputs are primals and which are tangents. + """ + self.n_tangents = 0 + for i, ph in enumerate(self.joint_gm.graph.find_nodes(op="placeholder")): + if i < self.n_primals: + ph.target = f"primals_{i}" + ph.name = f"primals_{i}" + else: + self.n_tangents += 1 + ph.target = f"tangents_{i - self.n_primals}" + ph.name = f"tangents_{i - self.n_primals}" + + self.joint_gm.graph.lint() + self.joint_gm.compile() + + def _remove_redundant_sym_size_ops(self) -> None: + """ + Deletes torch.ops.sym_size.int operators whose output is a + corresponding placeholder that holds the same symbol, and replace all usage + of the sym_size node to be directly using the placeholders. + + This is to make sure all basic symbols come from inputs. + """ + placeholder_exprs = {} + for node in self.joint_gm.graph.nodes: + if ( + isinstance(node, torch.fx.Node) + and node.op == "placeholder" + and hasattr(node, "meta") + and "val" in node.meta + ): + val = node.meta["val"] + if isinstance(val, torch.SymInt): + placeholder_exprs[val.node.expr] = node + + nodes_to_remove = [] + for node in self.joint_gm.graph.find_nodes( + op="call_function", target=torch.ops.aten.sym_size.int + ): + if not (hasattr(node, "meta") and "val" in node.meta): + raise AssertionError( + f"node {node} must have 'meta' attribute with 'val' key" + ) + val = node.meta["val"] + expr = val.node.expr + if expr in placeholder_exprs: + placeholder_node = placeholder_exprs[expr] + node.replace_all_uses_with(placeholder_node) + nodes_to_remove.append(node) + + for node in nodes_to_remove: + self.joint_gm.graph.erase_node(node) + + self.joint_gm.graph.lint() + self.joint_gm.recompile() + + def _mark_complex_exprs_as_must_recompute(self) -> None: + """ + For control flow operators such as scan, we don't want to + have symint in the partitioning boundaries because otherwise we would need to support stacking + the symints up, which causes more entropy in the stack. + + By marking the recompute polify for complex nodes as MUST_RECOMPUTE, the partitioning boundary + no longer contains complex expressions. + + Note that this pass doesn't exclude basic symbols from partitioning boundary + and it's up to the downstream to decide whether to return the basic symbol + or have a separate graph pass to remove them. + """ + + from torch._functorch.partitioners import CheckpointPolicy + + for n in ( + node for node in self.joint_gm.graph.nodes if node.op == "call_function" + ): + if "val" not in n.meta: + continue + val = n.meta["val"] + if isinstance(val, torch.SymInt) and is_complex_expr(val.node.expr): + if n.meta.get("recompute", None) is not None: + raise AssertionError( + f"node {n} with complex SymInt expression should not have recompute policy set" + ) + + n.meta["recompute"] = CheckpointPolicy.MUST_RECOMPUTE + + self.joint_gm.graph.lint() + self.joint_gm.recompile() + + def partition( + self, partition_fn: Callable, always_recompute_complex_exprs: bool + ) -> HopPartitionedGraph: + if logger.isEnabledFor(logging.DEBUG): + logger.debug( + "before min_cut_partition:\n%s", + self.joint_gm.print_readable(print_output=False), + ) + + if always_recompute_complex_exprs: + self._mark_complex_exprs_as_must_recompute() + + fw_gm, bw_gm = partition_fn( + self.joint_gm, None, num_fwd_outputs=self.n_fw_outputs + ) + + if logger.isEnabledFor(logging.DEBUG): + logger.debug("after partition_fn:") + logger.debug("fw_gm:\n%s", fw_gm.print_readable(print_output=False)) + logger.debug("bw_gm:\n%s", bw_gm.print_readable(print_output=False)) + + n_intermediates = len(_find_hop_subgraph_outputs(fw_gm)) - self.n_fw_outputs + + return HopPartitionedGraph( + fw_gm, + bw_gm, + self.n_fw_outputs, + n_intermediates, + always_recompute_complex_exprs, + ) + + +def create_hop_joint_graph( + fw_fn: Callable, + fw_args: tuple[torch.Tensor | torch.SymInt, ...], + functionalize: bool, +) -> HopJointGraph: + fw_gm = materialize_as_graph(fw_fn, fw_args, force_enable_grad=True) + fw_gm_output_nodes = _find_hop_subgraph_outputs(fw_gm) + + if not all( + isinstance(n, torch.fx.Node) and "val" in n.meta for n in fw_gm_output_nodes + ): + raise AssertionError( + "all fw_gm output nodes must be torch.fx.Node with 'val' in meta" + ) + fw_gm_output_vals = tuple(n.meta["val"] for n in fw_gm_output_nodes) # type: ignore[arg-type] + + if not all(isinstance(val, torch.Tensor) for val in fw_gm_output_vals): + raise AssertionError( + f"all fw_gm output values must be torch.Tensor, got {[type(v) for v in fw_gm_output_vals]}" + ) + example_grads = tuple(torch.zeros_like(val) for val in fw_gm_output_vals) + + joint_fn = create_bw_fn(fw_fn, fw_args, return_fw_outputs=True) + joint_gm = materialize_as_graph( + joint_fn, fw_args + example_grads, force_enable_grad=True + ) + if functionalize: + # Need to first trace out the joint_fn with autograd info on + # then functionalize the graph otherwise the grad information is lost + joint_gm = materialize_as_graph( + # pyrefly: ignore [bad-argument-type] + torch.func.functionalize(joint_gm, remove="mutations_and_views"), + fw_args + example_grads, + ) + + return HopJointGraph( + joint_gm, + len(fw_args), + len(fw_gm_output_nodes), + functionalized=functionalize, + ) + + +class HopGraphMinCutPartitioner: + @staticmethod + def create_partitioned_graph( + fw_fn: Callable, + fw_args: tuple[torch.Tensor | torch.SymInt, ...], + *, + always_recompute_complex_exprs: bool = False, + ) -> HopPartitionedGraph: + """ + Inputs: + - fw_fn: the forward function that we'll use to create a joint graph and partition + - fw_args: the flat_args to fw_fn + - always_recompute_complex_exprs: when set to True, the bw_gm will do a re-compute + for inputs that are complex expressions such that the partitioning boundary + only consists of basic symbols and tensors. + + Returns a HopPartitionedGraph + """ + from torch._functorch.partitioners import min_cut_rematerialization_partition + + joint_graph: HopJointGraph = create_hop_joint_graph( + fw_fn, fw_args, functionalize=True + ) + return joint_graph.partition( + min_cut_rematerialization_partition, always_recompute_complex_exprs + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__init__.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ce0b13cffe9c1e4bd7fbdaecf550d94a668f838 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/inline_invoke_subgraph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/inline_invoke_subgraph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5da00f8be5015ad681bf660efb1cd633ab313898 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/__pycache__/inline_invoke_subgraph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/inline_invoke_subgraph.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/inline_invoke_subgraph.py new file mode 100644 index 0000000000000000000000000000000000000000..0509a1bda8ddc84645435b7b323dc25a64d9be28 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/passes/inline_invoke_subgraph.py @@ -0,0 +1,153 @@ +import operator +from collections import Counter +from typing import Any, TYPE_CHECKING + +import torch +from torch.fx.graph_module import GraphModule + + +if TYPE_CHECKING: + from torch.fx.node import Node + + +def count_subgraph_uses(gm: GraphModule) -> Counter[str]: + """Count invoke_subgraph references by identifier string across all + descendant GraphModules.""" + counts: Counter[str] = Counter() + for mod in gm.modules(): + if not isinstance(mod, GraphModule): + continue + for node in mod.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ): + counts[str(node.args[1])] += 1 + return counts + + +def inline_single_use_invoke_subgraph(gm: GraphModule) -> GraphModule: + """Inline invoke_subgraph HOPs whose subgraph module has exactly one call + site across the entire module tree. + + When a subgraph has only a single caller, invoke_subgraph adds overhead + without any deduplication benefit, so we inline it unconditionally. + Subgraph modules that are shared across sibling modules (e.g. two AC body + modules referencing the same nested_compile_region) are counted globally + by module identity and preserved when referenced more than once. + """ + global_counts = count_subgraph_uses(gm) + inline_single_use_recursive(gm, global_counts) + return gm + + +def inline_single_use_recursive(gm: GraphModule, global_counts: Counter[str]) -> None: + # Recursively apply to nested subgraph modules first. + for name, mod in gm.named_modules(): + if name and isinstance(mod, GraphModule): + inline_single_use_recursive(mod, global_counts) + + invoke_nodes = list( + gm.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ) + ) + if not invoke_nodes: + return + + single_use_nodes = [ + node + for node in invoke_nodes + if global_counts[str(node.args[1])] == 1 + and not getattr(gm, str(node.args[0].target)).meta.get( + "nested_region_config", None + ) + ] + if not single_use_nodes: + return + + inline_invoke_subgraph_nodes(gm, single_use_nodes) + + +def hoist_submodules(gm: GraphModule, subgraph: GraphModule) -> dict[str, str]: + """Move submodules of *subgraph* onto *gm*, returning a name-remap dict. + + For each direct child module of *subgraph* (e.g. ``fwd_body_0``), register + it on *gm* under a unique name and return a mapping from the old name to the + new name so that ``get_attr`` targets copied from *subgraph*'s graph can be + rewritten. + """ + name_map: dict[str, str] = {} + existing_names = {name for name, _ in gm.named_children()} + for child_name, child_mod in list(subgraph.named_children()): + new_name = child_name + counter = 0 + while new_name in existing_names: + new_name = f"{child_name}_{counter}" + counter += 1 + gm.add_module(new_name, child_mod) + existing_names.add(new_name) + name_map[child_name] = new_name + return name_map + + +def inline_invoke_subgraph_nodes(gm: GraphModule, invoke_nodes: list["Node"]) -> None: + """Shared helper that inlines a list of invoke_subgraph nodes.""" + for node in invoke_nodes: + get_attr_node: torch.fx.Node = node.args[0] # pyrefly: ignore[bad-assignment] + operands = node.args[2:] + + subgraph: GraphModule = getattr(gm, str(get_attr_node.target)) + + # Hoist sub-submodules (e.g. fwd_body_0, bwd_body_0) to gm so that + # get_attr nodes copied from the subgraph resolve correctly. + name_map = hoist_submodules(gm, subgraph) + + env: dict[Node, Any] = dict( + zip(subgraph.graph.find_nodes(op="placeholder"), operands) + ) + + with gm.graph.inserting_before(node): + for sub_node in subgraph.graph.nodes: + if sub_node.op in ("placeholder", "output"): + continue + new_node = gm.graph.node_copy(sub_node, lambda n: env[n]) + if sub_node.op == "get_attr" and sub_node.target in name_map: + new_node.target = name_map[sub_node.target] + env[sub_node] = new_node + + output_values = subgraph.graph.output_node().args[0] + + for user in list(node.users): + if user.op == "call_function" and user.target is operator.getitem: + idx = user.args[1] + user.replace_all_uses_with(env[output_values[idx]]) # pyrefly: ignore + gm.graph.erase_node(user) + + gm.graph.erase_node(node) + + if not get_attr_node.users: + gm.graph.erase_node(get_attr_node) + + +def inline_invoke_subgraph(gm: GraphModule) -> GraphModule: + """Inline all invoke_subgraph HOPs, producing a flat FX graph. + + This is useful when downstream compilers (like vllm-compile) don't support + HOPs or prefer a flat graph, but we still want the Dynamo tracing-time + benefits of auto-caching (trace once, stamp out cached calls). + """ + # Recursively inline nested invoke_subgraph calls inside subgraph + # modules first, so their graphs are flat before we inline them here. + for name, mod in gm.named_modules(): + if name and isinstance(mod, GraphModule): + inline_invoke_subgraph(mod) + + invoke_nodes = list( + gm.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ) + ) + if not invoke_nodes: + return gm + + inline_invoke_subgraph_nodes(gm, invoke_nodes) + return gm diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/print.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/print.py new file mode 100644 index 0000000000000000000000000000000000000000..9ef6666b15bdb734c06124ac5e388840782cf769 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/print.py @@ -0,0 +1,153 @@ +import builtins + +import torch +import torch.utils._pytree as pytree +from torch._higher_order_ops.utils import register_fake +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode + + +class Print(HigherOrderOperator): + """ + print(format_str, *args, **kwargs) -> None + + This Higher Order Operator (HOP) provides a functional version of print for use in PyTorch graphs. + It supports the calling conventions of print(format_str.format(*args, **kwargs)): + + 1. Format string with keyword arguments (named placeholders): + torch._higher_order_ops.print("moo {x} {y}", x=1, y=2) + Output: "moo 1 2" + + 2. Format string with positional arguments (positional placeholders): + torch._higher_order_ops.print("moo {} {}", 1, 2) + Output: "moo 1 2" + + 3. Mixed positional and keyword arguments: + torch._higher_order_ops.print("moo {} {y}", 1, y=2) + Output: "moo 1 2" + + 4. DTensor support: + DTensor args are unwrapped to local tensors via to_local() (no collective). + Each rank prints its own local view, prefixed with [rank N]. + For the global view of a sharded tensor, call full_tensor() before + passing to print. + + dt = DTensor.from_local(local_shard, mesh, [Shard(0)]) + torch._higher_order_ops.print("activations: {}", dt) + # Output: [rank 0] activations: tensor([0., 1.]) + + This HOP enables printing without causing graph break. + """ + + def __init__(self) -> None: + super().__init__("print") + + def __call__(self, format_str: str, *args: object, **kwargs: object) -> None: + if not isinstance(format_str, str): + raise AssertionError(f"format_str must be a string, got {type(format_str)}") + # pyrefly: ignore [missing-attribute] + return super().__call__(format_str, *args, **kwargs) + + # pyrefly: ignore [bad-override] + def gen_schema( + self, format_str: str, *args: object, **kwargs: object + ) -> torch.FunctionSchema: + from torch._higher_order_ops.schema import HopSchemaGenerator + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("format_str", format_str[0]) + + # Add each positional arg + for i, value in enumerate(args): + schema_gen.add_arg(f"arg{i}", value) + + # Add each kwarg as a keyword-only argument + for key, value in kwargs.items(): + schema_gen.add_arg(key, value, kw_only=True) + + schema_gen.add_schema_tree_spec(format_str, *args, **kwargs) + + return schema_gen.gen_schema() + + +print = Print() + + +@print.py_impl(ProxyTorchDispatchMode) +# pyre-ignore +def print_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, format_str: str, *args: object, **kwargs: object +) -> None: + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args) # type: ignore[union-attr] + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) # type: ignore[union-attr] + mode.tracer.create_proxy( + "call_function", print, (format_str, *proxy_args), proxy_kwargs + ) + + +@register_fake(print, skip_cache=True) +# pyre-ignore +def print_fake_tensor_mode(format_str: str, *args: object, **kwargs: object): + return None + + +@print.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd) +# pyre-ignore +def print_impl(format_str: str, *args: object, **kwargs: object) -> None: + # Ensure all immutable_dict/list in args and kwargs are converted to regular dict/list + map_types: dict[type, type] = { + torch.fx.immutable_collections.immutable_dict: dict, + torch.fx.immutable_collections.immutable_list: list, + } + new_args, new_kwargs = pytree.tree_map_only( + tuple(map_types.keys()), + lambda a: map_types[type(a)](a), + (args, kwargs), + lambda a: isinstance(a, tuple(map_types.keys())), + ) + # Use built-in print to avoid recursion with the HOP print + builtins.print(format_str.format(*new_args, **new_kwargs)) + + +print.fallthrough(torch._C.DispatchKey.AutogradCPU) +print.fallthrough(torch._C.DispatchKey.AutogradCUDA) + + +def _register_dtensor_impl() -> None: + from torch.distributed.tensor import DTensor + + @print.py_impl(DTensor) # pyrefly: ignore [missing-attribute] + # pyre-ignore + def print_dtensor(format_str: str, *args: object, **kwargs: object) -> None: + # Unwrap DTensors to local tensors via to_local() — no collective is + # introduced so there is no OOM or performance risk. Every rank prints + # its own local view (including Replicate, where to_local() already + # holds the full tensor). + # + # The output is prefixed with [rank N] so users can identify which rank + # produced each line. + # + # If the user needs the global view of a sharded tensor, they can call + # full_tensor() explicitly before passing it to print. + import torch.distributed as dist + + local_args = pytree.tree_map_only(DTensor, DTensor.to_local, args) + local_kwargs = pytree.tree_map_only(DTensor, DTensor.to_local, kwargs) + if dist.is_initialized() and dist.get_world_size() > 1: + format_str = f"[rank {dist.get_rank()}] {format_str}" + print( # pyrefly: ignore [no-matching-overload] + format_str, *local_args, **local_kwargs + ) + + +@print.py_functionalize_impl +def print_func(ctx, format_str: str, *args: object, **kwargs: object): + from torch._higher_order_ops.effects import handle_effects + + return handle_effects( + ctx.mode._allow_token_discovery, + ctx.mode._tokens, + print, # type: ignore[arg-type] + (format_str, *args), + kwargs, # type: ignore[arg-type] + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/register_hook.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/register_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..56ca41983521cf47be34cc2357700258da9a5eeb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/register_hook.py @@ -0,0 +1,34 @@ +from collections.abc import Callable +from typing import Any + +import torch +from torch._ops import HigherOrderOperator + + +class RegisterHookOp(HigherOrderOperator): + """HOP that registers a backward hook on a tensor. + + The hook body is a traced subgraph that takes (grad, *freevars) + and returns the modified gradient. During make_fx tracing, the + hook registers on the FakeTensor and fires on the accumulated + gradient during backward tracing, capturing the hook's effect + in the joint graph. + """ + + def __init__(self) -> None: + super().__init__("register_hook", cacheable=True) + + def __call__( + self, + tensor: torch.Tensor, + hook_body: Callable[..., Any], + *freevars: Any, + ) -> torch.Tensor: + def hook(grad: torch.Tensor) -> torch.Tensor | None: + return hook_body(grad, *freevars) + + tensor.register_hook(hook) + return tensor + + +register_hook_op = RegisterHookOp() diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/run_const_graph.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/run_const_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..11c9a9ed366471c1e615ef3071947627f94ebc52 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/run_const_graph.py @@ -0,0 +1,83 @@ +from typing import Any, TYPE_CHECKING + +import torch +from torch._C import DispatchKey +from torch._higher_order_ops.utils import autograd_not_implemented, register_fake +from torch._ops import HigherOrderOperator + + +if TYPE_CHECKING: + from torch._subclasses.functional_tensor import BaseFunctionalizeAPI + +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.utils import _pytree as pytree + + +class RunConstGraph(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("run_const_graph") + + def __call__(self, graph: torch.fx.GraphModule, args: tuple[object, ...]) -> object: + # pyrefly: ignore [missing-attribute] + return super().__call__(graph, args) + + +run_const_graph = RunConstGraph() + + +@run_const_graph.py_impl(ProxyTorchDispatchMode) +def run_const_graph_dispatch_mode( + mode: ProxyTorchDispatchMode, graph: torch.fx.GraphModule, args: tuple[object, ...] +) -> object: + const_gm, weights = graph, args + p_args = pytree.tree_map(mode.tracer.unwrap_proxy, (graph, args)) # type: ignore[union-attr] + if not isinstance(const_gm, torch.fx.GraphModule): + raise AssertionError( + f"expected const_gm to be torch.fx.GraphModule, got {type(const_gm)}" + ) + if hasattr(mode.tracer.root, "_const_graph"): # type: ignore[union-attr] + raise AssertionError("mode.tracer.root already has _const_graph attribute") + mode.tracer.root.register_module("_const_graph", const_gm) # type: ignore[union-attr] + + proxy = mode.tracer.create_proxy("call_function", run_const_graph, p_args, {}) + + out = const_gm(*weights) + return track_tensor_tree(out, proxy, constant=None, tracer=mode.tracer) + + +@run_const_graph.py_functionalize_impl +def run_const_graph_functional( + ctx: "BaseFunctionalizeAPI", graph: torch.fx.GraphModule, args: tuple[Any, ...] +) -> Any: + unwrapped_args = ctx.unwrap_tensors(args) + + with ctx.redispatch_to_next(): + out = run_const_graph(graph, unwrapped_args) + return ctx.wrap_tensors(out) # type: ignore[arg-type] + + +run_const_graph.py_autograd_impl( + autograd_not_implemented(run_const_graph, deferred_error=True) +) + + +@register_fake(run_const_graph, skip_cache=True) +def run_const_graph_fake_tensor_mode( + graph: torch.fx.GraphModule, args: tuple[object, ...] +) -> object: + if not isinstance(graph, torch.fx.GraphModule): + raise AssertionError( + f"expected graph to be torch.fx.GraphModule, got {type(graph)}" + ) + return graph(*args) + + +@run_const_graph.py_impl(DispatchKey.CPU) +def run_const_graph_cpu( + graph: torch.fx.GraphModule, args: tuple[object, ...] +) -> object: + if not isinstance(graph, torch.fx.GraphModule): + raise AssertionError( + f"expected graph to be torch.fx.GraphModule, got {type(graph)}" + ) + return graph(*args) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/scan.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/scan.py new file mode 100644 index 0000000000000000000000000000000000000000..2b0231c836296cd7293480a0e54936af098a49d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/scan.py @@ -0,0 +1,1280 @@ +# mypy: allow-untyped-defs +import enum +import functools +import itertools +import logging +from collections.abc import Callable +from typing import Any + +import torch +import torch._prims_common as utils +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._functorch.vmap import restore_vmap, unwrap_batched, wrap_batched +from torch._guards import detect_fake_mode +from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, +) +from torch._higher_order_ops.partitioner import ( + _find_hop_subgraph_outputs, + HopGraphMinCutPartitioner, + HopPartitionedGraph, +) +from torch._higher_order_ops.utils import ( + _maybe_compile_and_run_fn, + check_meta_consistency, + fill_none_with_masks, + filter_with_masks, + first_slice_copy, + get_graph_output_example_values, + get_tensor_mask, + HopInstance, + mask_list, + materialize_as_graph, + reenter_make_fx, + split_into_chunks, + unique_graph_id, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensorMode, is_fake_tensor +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.utils._python_dispatch import _get_current_dispatch_mode + + +logger: logging.Logger = logging.getLogger(__name__) +aten = torch._ops.ops.aten + + +def wrap_combine_fn_flat( + *args, combine_fn, spec_init, spec_xs, num_init_leaves, num_inp_leaves +): + if len(args) != (num_init_leaves + num_inp_leaves): + raise AssertionError( + f"combine_fn received wrong number of arguments, expected {num_init_leaves + num_inp_leaves}, but got {len(args)}" + ) + carry = pytree.tree_unflatten(args[:num_init_leaves], spec_init) + xs = pytree.tree_unflatten(args[num_init_leaves:], spec_xs) + return combine_fn(carry, xs) + + +def _extract_carry_and_out(flat_out: list[Any], num_carry: int): + return split_into_chunks(flat_out, [num_carry, len(flat_out) - num_carry]) + + +# We also do a clone with contiguous_format. This is to be consistent with +# eager semantic of scan, which stacks the outputs. The result is contiguous +# as a result of the stack operation. +def stack_y(y: torch.Tensor, scan_length: int) -> torch.Tensor: + return ( + y.unsqueeze(0) + .repeat(*([scan_length] + [1] * y.ndim)) + .clone(memory_format=torch.contiguous_format) + ) + + +def call_operator(operator, *args): + return pytree.tree_leaves(operator(*args)) + + +def _build_empty_output_for_length_zero( + combine_fn: Callable, init: pytree.PyTree +) -> pytree.PyTree: + """Probe combine_fn(init, None) to learn the output structure for length==0.""" + fake_mode = detect_fake_mode(pytree.tree_leaves(init)) or FakeTensorMode() + with fake_mode: + fake_init = pytree.tree_map( + lambda t: fake_mode.from_tensor(t) + if isinstance(t, torch.Tensor) and not is_fake_tensor(t) + else t, + init, + ) + _, sample_y = combine_fn(fake_init, None) + + def _empty_or_passthrough(l): + if isinstance(l, torch.Tensor): + return torch.empty([0] + list(l.shape), dtype=l.dtype, device=l.device) + if l is not None: + raise AssertionError(f"Expected leaf to be a Tensor or None, got {type(l)}") + return l + + return pytree.tree_map(_empty_or_passthrough, sample_y) + + +def scan( + combine_fn: Callable[ + [pytree.PyTree, pytree.PyTree], tuple[pytree.PyTree, pytree.PyTree] + ], + init: pytree.PyTree, + xs: pytree.PyTree, + *, + dim: int = 0, + reverse: bool = False, + length: int | None = None, +) -> tuple[pytree.PyTree, pytree.PyTree]: + r""" + Performs an inclusive scan with a combine function. + + .. warning:: + + ``torch.scan`` is a prototype feature in PyTorch. You may run into miscompiles. + Read more about feature classification at: + https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + Args: + combine_fn (Callable): A binary callable with type ``(Tensor, Tensor) -> (Tensor, Tensor)``, + or if xs is a pytree ``(pytree, pytree) -> (pytree, pytree)``. + The first input to ``combine_fn`` is the previous or initial scan carry + and the second input element to ``combine_fn`` is a slice of the input along dim. + The first output element of ``combine_fn`` is the next scan carry + and the second output of ``combine_fn`` represents a slice of the output. + This function must be pure, i.e., no lifted arguments are supported at the moment + and may not have any side effects. + init (torch.Tensor or pytree with tensor leaves): The initial scan carry, a tensor, or nested pytree of tensors. + The ``init`` is expected to have the same pytree structure as the first output element (i.e. carry) + of ``combine_fn``. + xs (torch.Tensor or pytree with tensor leaves or None): The input tensor, or nested pytree of tensors. + May be ``None`` when ``length`` is provided, in which case ``combine_fn`` receives ``None`` as ``x`` + each step (counter-loop mode). + + Keyword Args: + dim (int): the dimension to scan over, default 0. + reverse (bool): A boolean stating if the scan should be reversed with respect to ``dim``, default ``False``. + length (int or None): Optional number of scan iterations, default ``None``. + When ``xs`` has tensor leaves, ``length`` is optional; if given it must equal + ``xs.shape[dim]`` and serves only as a consistency check (no constraint when + ``length`` is ``None``). When ``xs`` has no leaves (``None`` or empty pytree), + ``length`` drives the number of iterations and ``combine_fn`` receives + ``x=None`` each step. ``length=0`` with no xs tensors is supported in + eager mode only; it is not supported under ``torch.compile``. + + Returns: + final_carry (torch.Tensor or pytree with tensor leaves), + the final carry of the scan operation with same pytree structure as init. + out (torch.Tensor or pytree with tensor leaves), + each tensor leaf is a stacked output along first dim, where each slice is the output of a scan iteration. + If the scan dimension has size 0, ``final_carry`` equals ``init`` unchanged and each output leaf has + size 0 along ``dim``. The gradient of ``final_carry`` with respect to ``init`` is the identity + (not zero), since the body is never called and the carry passes through untouched. + + Restrictions: + - The combine_fn shouldn't have any aliasing between input-input, input-output, and output-output. E.g. return a view + or the same tensor as input is not supported. As a workaround, can clone the output to avoid aliasing. + + - The combine_fn shouldn't mutate any inputs. We'll remove the mutation restriction for inference soon. Please file an issue + if you input mutation support for training is needed. + + - The combine_fn's init carry should match the next_carry in pytree structure and in tensor metadata. + + Example:: + + def add(x: torch.Tensor, y: torch.Tensor): + next_carry = y = x + y + # clone the output to avoid output-output aliasing + return next_carry, y.clone() + + + i0 = torch.zeros(1) + xs = torch.arange(5) + # returns torch.tensor([10.]), torch.tensor([[0], [1.], [3.], [6.], [10.]]) + last_carry, cumsum = scan(add, init=i0, xs=xs) + + + """ + # The reason we flatten init and xs before calling into dynamo is that + # we want to create a consistent input ordering for combine_fn + # and we also want to the input ordering matches the output ordering. + leaves_init, spec_init = pytree.tree_flatten(init) + leaves_xs_orig, spec_xs = pytree.tree_flatten(xs) + + # Determine whether xs carries any tensor data. + xs_has_tensors = any(isinstance(l, torch.Tensor) for l in leaves_xs_orig) + + # short-cuts + if length is not None: + if isinstance(length, bool) or not isinstance(length, int) or length < 0: + raise RuntimeError( + f"scan() length must be a non-negative integer, got {length!r}" + ) + + if not xs_has_tensors: + if length == 0: + if torch.compiler.is_dynamo_compiling(): + # TODO: Resolve this in a follow-up PR + raise RuntimeError( + "scan() with length=0 and no xs tensors is not supported under torch.compile" + ) + return init, _build_empty_output_for_length_zero(combine_fn, init) + + # No real xs: fabricate a length-N dummy purely as an iteration counter. + # the wrapped combine_fn below discards each slice and passes x=None to the body. + leaves_xs_orig = [torch.zeros(length, dtype=torch.int64)] + spec_xs = pytree.tree_structure(None) + _user_combine_fn = combine_fn + + def combine_fn(carry, _ignored): # noqa: E306 + return _user_combine_fn(carry, None) + elif not xs_has_tensors: + return init, [] + + def _validate_input(cfn, lxs, linit, d, r, l): + # Basic arguments check + if not callable(cfn): + raise RuntimeError(f"Combine_fn must be a callable, but got {cfn}") + if not isinstance(d, int): + raise RuntimeError("Dim must be an int, but got " + str(type(d))) + if not isinstance(r, bool): + raise RuntimeError("Reverse must be a bool, but got " + str(type(r))) + + if l is not None and xs_has_tensors and lxs[0].shape[d] != l: + raise RuntimeError( + f"scan() length={l} does not match xs size along dim={d}: " + f"{lxs[0].shape[d]}" + ) + + # Checks for init + if len(linit) == 0: + raise RuntimeError("scan() operator requires init leaves.") + for x in linit: + if not isinstance(x, torch.Tensor): + raise RuntimeError(f"All init leaves must be a Tensor but got {x}") + + # Checks for xs + for x in lxs: + if not isinstance(x, torch.Tensor): + raise RuntimeError(f"All xs leaves must be a Tensor but got {x}") + if any(x.ndim <= d for x in lxs): + raise RuntimeError("All xs leaves must have at least 'dim + 1' dimensions") + if any(x.shape[d] != lxs[0].shape[d] for x in lxs[1:]): + raise RuntimeError("All xs leaves must have the same scan dimension size") + + ndim = leaves_xs_orig[0].ndim + dim = utils.canonicalize_dim(ndim, dim) + + _validate_input(combine_fn, leaves_xs_orig, leaves_init, dim, reverse, length) + + # Move scan dim to 0 and always perform scan on dim 0 + leaves_xs = [] + for elem in leaves_xs_orig: + leaves_xs.append(torch.movedim(elem, dim, 0) if dim != 0 else elem) + + if reverse: + leaves_xs = [torch.flip(elem, [0]) for elem in leaves_xs] + + # TODO: Support _inductor lowering + # TODO: Unify handling of pytrees for control flow ops, such as cond, while_loop, etc. + + combine_fn = functools.partial( + wrap_combine_fn_flat, + combine_fn=combine_fn, + spec_init=spec_init, + spec_xs=spec_xs, + num_init_leaves=len(leaves_init), + num_inp_leaves=len(leaves_xs), + ) + + def run_flattened_scan(combine_fn, leaves_init, leaves_xs): + return scan_op(combine_fn, leaves_init, leaves_xs, ()) + + carry, out = _maybe_compile_and_run_fn( + run_flattened_scan, + combine_fn, + leaves_init, + leaves_xs, + ) + + if reverse: + out = pytree.tree_map(lambda elem: elem.flip([0]), out) + + # Move the scan dimension from 0 back to the user-specified `dim`. + if dim != 0: + out = pytree.tree_map( + lambda elem: torch.movedim(elem, 0, dim) if dim < elem.ndim else elem, + out, + ) + + return carry, out + + +class ScanOp(HigherOrderOperator): + def __init__(self): + super().__init__("scan") + + def __call__( + self, + combine_fn, + init, + xs, + additional_inputs, + *, + mutated_arg_indices: str = "", + ): + # There is currently an issue that the ScanOp is sometimes called with + # the additional_inputs being a list. See https://github.com/pytorch/pytorch/issues/145785 + # Once this issue is resolved, the assertion should only allow tuples + # and the tuple cast should be removed + if not isinstance(additional_inputs, (tuple, list)): + raise AssertionError( + f"additional_inputs must be a tuple or list, got {type(additional_inputs)}" + ) + additional_inputs = ( + tuple(additional_inputs) + if isinstance(additional_inputs, list) + else additional_inputs + ) + validate_subgraph_args_types(additional_inputs) + kwargs = {} + if mutated_arg_indices: + kwargs["mutated_arg_indices"] = mutated_arg_indices + # pyrefly: ignore [missing-attribute] + return super().__call__(combine_fn, init, xs, additional_inputs, **kwargs) + + # pyrefly: ignore [bad-override] + def gen_schema( + self, combine_fn, init, xs, additional_inputs, mutated_arg_indices="" + ): + from torch._higher_order_ops.schema import HopSchemaGenerator + + all_inputs = tuple( + list(init) + + [ + torch.empty_strided( + x.shape[1:], + x.stride()[1:], + dtype=x.dtype, + device=x.device, + requires_grad=x.requires_grad, + ) + for x in xs + ] + + list(additional_inputs) + ) + combine_gm = materialize_as_graph(combine_fn, all_inputs) + + # Mutation semantics for scan: + # - additional_inputs is mutable: loop-invariant tensor identity + # across sequential iterations, same semantics as while_loop's + # additional_inputs (CUDA-graph-friendly lifted / pre-allocated + # buffers such as KV caches or workspace scratch). + # - init is NOT mutable: init is only the *initial* carry, + # thus an in-place update to init only affects step 0. + # - xs is NOT mutable: each iteration sees a fresh, storage-disjoint + # slice (xs[t] and xs[t+1] share no storage), so a mutation on + # xs[t] cannot be observed by iteration t+1. The only externally- + # observable effect is "write-back to xs's t-th slice", which is + # already expressible via the ys output path at no extra cost. + # If xs-like in-place updates are required, pass the buffer via + # additional_inputs and index into it inside combine_fn. + outputs = get_graph_output_example_values(combine_gm) + mutated_set = ( + {int(i) for i in mutated_arg_indices.split(",") if i} + if mutated_arg_indices + else set() + ) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("combine_fn", combine_gm) + + for idx, arg in enumerate(init): + schema_gen.add_arg(f"init{idx}", arg) + + for idx, arg in enumerate(xs): + schema_gen.add_arg(f"xs{idx}", arg) + + offset = len(init) + len(xs) + for idx, arg in enumerate(additional_inputs): + schema_gen.add_arg( + f"additional_input{idx}", + arg, + is_mutated=(offset + idx) in mutated_set, + ) + + for out in outputs: + schema_gen.add_output(out) + + schema_gen.add_schema_tree_spec(combine_fn, init, xs, additional_inputs) + return schema_gen.gen_schema() + + +scan_op = ScanOp() + + +def generic_scan(operator, init, xs, dim=0, additional_inputs=()): + def _scan(init, xs): + """Perform scan on `elems` using `elems_init.""" + carry = init + if len(xs) == 0: + return carry, [] + + num_elems = xs[0].shape[dim] + num_init_leaves = len(init) + + proto_xs = [first_slice_copy(x, dim) for x in xs] + + # Process element 0 to infer output shapes for pre-allocation + # AND produce the first real result in a single call. The previous + # approach used first_slice_copy() for shape inference and then + # re-processed element 0 in the main loop, calling the operator + # num_elems+1 times. That extra invocation is incorrect for + # operators with side effects. + carry, out_0 = _extract_carry_and_out( + call_operator( + operator, + *carry, + *proto_xs, + *additional_inputs, + ), + num_init_leaves, + ) + + out_tensor_mask = get_tensor_mask(out_0) + out_0_masked = mask_list(out_tensor_mask, out_0) + + # Pre-allocate + # outs -> Output matrix + # idxs -> Index matrix for scatter_ + # out: (num_elems, M, N, ...) + # idx: (1, M, N) + outs = [ + torch.empty( + [num_elems] + list(e.size()), + dtype=e.dtype, + device=e.device, + ) + for e in out_0_masked + ] + idxs = [ + torch.ones_like(e, dtype=torch.int64).unsqueeze(0) for e in out_0_masked + ] + + if num_elems == 0: + outs_expanded = [ + outs.pop(0) if out_m else None for out_m in out_tensor_mask + ] + return (*init, *outs_expanded) + + def store_out_in_outs(out, ind): + # Store the intermediate out in the outs matrix + for o, x, idx in zip(outs, out, idxs): + # o: (num_elems, M, N ...) + # x: (M, N, ...) -> (1, M, N) + # ind * idx: (1, M, N,) with values to be ind + # essentially: o[ind][n][k] = x[0][n][k] + o.scatter_(0, ind * idx, x.unsqueeze(0)) + + # Store element 0's result, then continue from element 1. + store_out_in_outs(out_0_masked, 0) + + for i in range(1, num_elems): + carry, out = _extract_carry_and_out( + call_operator( + operator, + *carry, + *[elem.select(dim, i) for elem in xs], + *additional_inputs, + ), + num_init_leaves, + ) + + store_out_in_outs(mask_list(out_tensor_mask, out), i) + + # Expand outs with None depending on the tensor mask of the output + outs_expanded = [outs.pop(0) if out_m else None for out_m in out_tensor_mask] + + return (*carry, *outs_expanded) + + scans = _scan(init, xs) + return scans + + +def trace_scan( + proxy_mode, + func_overload, + combine_fn: Callable, + init: list[torch.Tensor], + xs: list[torch.Tensor], + additional_inputs: tuple[torch.Tensor], + mutated_arg_indices: str = "", +): + from torch._dynamo.utils import clone_input + + with disable_proxy_modes_tracing(): + sample_inits = [clone_input(x_init) for x_init in init] + sample_inputs = [first_slice_copy(x) for x in xs] + sample_additional_inputs = [ + clone_input(x) if isinstance(x, torch.Tensor) else x + for x in additional_inputs + ] + combine_graph = reenter_make_fx(combine_fn)( + *sample_inits, *sample_inputs, *sample_additional_inputs + ) + + outputs = None + for node in combine_graph.graph.nodes: + if node.op == "output": + if outputs is not None: + raise AssertionError("found multiple output nodes in combine_graph") + if len(node.args) != 1: + raise AssertionError( + f"expected output node to have 1 arg, got {len(node.args)}" + ) + outputs = node.args[0] + + if outputs is None: + raise AssertionError("no output node found in combine_graph") + + carry, output = _extract_carry_and_out(outputs, len(init)) + init_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [ + i.clone() for i in init + ] + carry_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [ + c.meta["val"] for c in carry + ] + check_meta_consistency( + init_fake_tensors, carry_fake_tensors, "init", "carry", include_contiguity=False + ) + + _, combine_graph_name = unique_graph_id(proxy_mode, prefix="scan_combine_graph") + + proxy_mode.tracer.root.register_module(combine_graph_name, combine_graph) + + args = (combine_graph, init, xs, additional_inputs) + kwargs = {} + if mutated_arg_indices: + kwargs["mutated_arg_indices"] = mutated_arg_indices + + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, kwargs, name="scan" + ) + + with disable_proxy_modes_tracing(): + scan_length = xs[0].shape[0] + fake_carry, fake_outputs = _extract_carry_and_out( + [o.meta["val"] if o is not None else None for o in outputs], len(init) + ) + for t in fake_outputs: + if not isinstance(t, torch.Tensor) and t is not None: + raise AssertionError( + f"Expected leaf to be a Tensor or None, got {type(t)}" + ) + out = ( + *fake_carry, + *( + stack_y(t, scan_length) if isinstance(t, torch.Tensor) else t + for t in fake_outputs + ), + ) + + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@scan_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def scan_op_dense(combine_fn, init, xs, additional_inputs, mutated_arg_indices=""): + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + return generic_scan(combine_fn, init, xs, additional_inputs=additional_inputs) + + +class ScanAutogradOp(torch.autograd.Function): + """ + NOTE: [scan partial grad handling] + If any element of init, of xs, of the outputs or of the additional_inputs does not require gradients, + i.e., requires_grad=False, there will be still gradients returned for those elements, + but those gradients will be a tensor filled with zeros of the same shape as the element itself. + + A special case are additional_inputs that are not tensors. Such inputs can occur for example with symbolic tracing, + where the shape symbol (SymInt) becomes an additional_input. + For such cases, we compute a ``additional_inputs_tensor_mask``, which is True for elements of additional_inputs + that are tensors and False otherwise. Gradients of additional_inputs are only accumulated if this mask is True, + otherwise, the value of initial_g_additional_inputs is passed, which is None for non-Tensor values. + """ + + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + hop_partitioned_graph, + n_init, + n_xs, + n_additional_inputs, + *operands, + ): + init, xs, additional_inputs = split_into_chunks( + operands, [n_init, n_xs, n_additional_inputs] + ) + ctx._scan_impl = ScanAutogradImpl( + hop_partitioned_graph, init, xs, additional_inputs + ) + with torch._C._AutoDispatchBelowAutograd(): + return ctx._scan_impl.call_forward() + + @staticmethod + def backward(ctx, *grad_fw_outputs): + return ( + None, + None, + None, + None, + *ctx._scan_impl.call_backward(*grad_fw_outputs), + ) + + +class ScanForwardIntermediatesHandlingPolicy(enum.Enum): + """ + Partitioner can add intermediates to the output of original graph. + These intermediates fall into 4 categories and we want to have different policies for handling them by + modifying the graph: + + CLONE: we clone the intermediate when it is a carried input (i.e. init). In this case, this carry will be + replaced with new values at each forward step so we need to clone the carry as part of return (i.e. ys) + so as to remove the aliasing and that each step's intermediate will be stacked together and saved in backward. + + REMOVE_XS: we remove the intermediate from output when it is part of xs. Since xs is read-only, in this case, + we can directly save them for backward to use. + + REMOVE_ADDITIONAL_INPUTS: we remove the intermediate from output when it is part of additional_inputs. additional_inputs + are also read-only in each step, we can directly save them for backward to use. We differentiate XS and ADDITIONAL_INPUTS + so that we could have different treatment for them in backward. In backward, we need to put xs intermediates in carry but + put additional_inputs as backward scan's additional_inputs. + + KEEP: this corresponds to a real intermediate tensor operations' output. It varies at each forward step, we could just keep + it as part of ys. + + """ + + KEEP = 0 + CLONE = 1 + REMOVE_XS = 2 + REMOVE_ADDITIONAL_INPUTS = 3 + + +class ScanAutogradImpl: + """ + Wraps over partitioned graph and encapsulates scan-specific implementation details + """ + + def __init__( + self, hop_partitioned_graph: HopPartitionedGraph, init, xs, additional_inputs + ): + self.hop_partitioned_graph = hop_partitioned_graph + self.init = init + self.xs = xs + self.additional_inputs = additional_inputs + self.forward_intermediates_handling_policies: list[ + ScanForwardIntermediatesHandlingPolicy + ] = [] + self.saved_fw_xs: list[Any] = [] + self.saved_fw_additional_inputs: list[Any] = [] + self.saved_intermediates: list[Any] = [] + self.fw_spec = pytree.tree_flatten((init, xs, additional_inputs))[1] + self._optimize_forward_intermediates() + self._break_bw_input_output_aliasing() + + def _insert_clone( + self, need_copy_node: torch.fx.Node, output_node: torch.fx.Node + ) -> torch.fx.Node: + graph: torch.fx.Graph = output_node.graph + with graph.inserting_before(output_node): + clone_node = graph.call_function( + torch.ops.aten.clone.default, + args=(need_copy_node,), + ) + clone_node.meta = ( + need_copy_node.meta.copy() if hasattr(need_copy_node, "meta") else {} + ) + return clone_node + + def _break_bw_input_output_aliasing(self) -> None: + """ + The min-cut partitioner can produce a ``bw_gm`` whose output aliases + an input placeholder. The most common case is a direct placeholder + return (e.g. when an input doesn't require grad and its gradient is + ``zeros_like(input)`` saved as a forward intermediate), but transitive + aliases (views, ``_unsafe_view``, slices, ...) can hit the same path. + + When ``bw_gm`` is wrapped as the per-step backward inside ``scan_op``, + any input returned as an output violates ``scan_op``'s aliasing-free + invariant and surfaces as ``UncapturedHigherOrderOpError`` under + dynamo. Clone bw_gm outputs that are direct placeholders or whose + ``meta['val']`` shares storage with any placeholder. + """ + from torch.multiprocessing.reductions import StorageWeakRef + + bw_gm = self.hop_partitioned_graph.bw_gm + bw_output_node = next(iter(bw_gm.graph.find_nodes(op="output"))) + if len(bw_output_node.args) != 1: + raise AssertionError( + f"expected bw_gm output to have 1 arg, got {len(bw_output_node.args)}" + ) + bw_outputs = bw_output_node.args[0] + + ph_storages: set = set() + for ph in bw_gm.graph.find_nodes(op="placeholder"): + val = ph.meta.get("val", None) if hasattr(ph, "meta") else None + if isinstance(val, torch.Tensor): + ph_storages.add(StorageWeakRef(val._typed_storage())) + + def _aliases_placeholder(node: torch.fx.Node) -> bool: + if node.op == "placeholder": + return True + val = node.meta.get("val", None) if hasattr(node, "meta") else None + if isinstance(val, torch.Tensor): + return StorageWeakRef(val._typed_storage()) in ph_storages + return False + + new_bw_outputs = [] + rewrote = False + for out in bw_outputs: + if isinstance(out, torch.fx.Node) and _aliases_placeholder(out): + new_bw_outputs.append(self._insert_clone(out, bw_output_node)) + rewrote = True + else: + new_bw_outputs.append(out) + if rewrote: + bw_output_node.args = (tuple(new_bw_outputs),) + bw_gm.graph.lint() + bw_gm.recompile() + + def _optimize_forward_intermediates(self): + """ + We optimize the forward intermediates by categorize forward intermediates into categories + and construct a ScanForwardIntermediatesHandlingPolicy for them + + """ + if logger.isEnabledFor(logging.DEBUG): + logger.debug( + "Need remove aliasing in fw_gm:\n%s", + self.hop_partitioned_graph.fw_gm.print_readable(print_output=False), + ) + + fw_gm = self.hop_partitioned_graph.fw_gm + fw_all_outputs = _find_hop_subgraph_outputs(fw_gm) + phs = list(fw_gm.graph.find_nodes(op="placeholder")) + fw_outputs = fw_all_outputs[: self.hop_partitioned_graph.n_fw_outputs] + fw_intermediates = fw_all_outputs[self.hop_partitioned_graph.n_fw_outputs :] + + init_phs, xs_phs, additional_inputs_phs = pytree.tree_unflatten( + phs, self.fw_spec + ) + init_node_set, xs_node_set, addi_node_set = ( + set(init_phs), + set(xs_phs), + set(additional_inputs_phs), + ) + + if len(self.forward_intermediates_handling_policies) != 0: + raise AssertionError( + "forward_intermediates_handling_policies should be empty" + ) + if len(self.saved_fw_xs) != 0: + raise AssertionError("saved_fw_xs should be empty") + if len(self.saved_fw_additional_inputs) != 0: + raise AssertionError("saved_fw_additional_inputs should be empty") + intermediate_idx_to_ph_idx = {} + ph_idx = {ph: i for i, ph in enumerate(phs)} + for i, out in enumerate(fw_intermediates): + if out in init_node_set: + self.forward_intermediates_handling_policies.append( + ScanForwardIntermediatesHandlingPolicy.CLONE + ) + intermediate_idx_to_ph_idx[i] = ph_idx[out] + elif out in xs_node_set: + self.forward_intermediates_handling_policies.append( + ScanForwardIntermediatesHandlingPolicy.REMOVE_XS + ) + intermediate_idx_to_ph_idx[i] = ph_idx[out] + elif out in addi_node_set: + self.forward_intermediates_handling_policies.append( + ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS + ) + intermediate_idx_to_ph_idx[i] = ph_idx[out] + else: + self.forward_intermediates_handling_policies.append( + ScanForwardIntermediatesHandlingPolicy.KEEP + ) + + new_output_node = [] + real_graph_inputs = ( + list(self.init) + list(self.xs) + list(self.additional_inputs) + ) + fw_output_node = next(iter(fw_gm.graph.find_nodes(op="output"))) + for intermediate_idx, (node, policy) in enumerate( + zip(fw_intermediates, self.forward_intermediates_handling_policies) + ): + if policy == ScanForwardIntermediatesHandlingPolicy.CLONE: + new_output_node.append(self._insert_clone(node, fw_output_node)) + elif policy == ScanForwardIntermediatesHandlingPolicy.REMOVE_XS: + if intermediate_idx not in intermediate_idx_to_ph_idx: + raise AssertionError( + f"intermediate_idx {intermediate_idx} not in intermediate_idx_to_ph_idx" + ) + inp_idx = intermediate_idx_to_ph_idx[intermediate_idx] + self.saved_fw_xs.append(real_graph_inputs[inp_idx]) + elif ( + policy + == ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS + ): + if intermediate_idx not in intermediate_idx_to_ph_idx: + raise AssertionError( + f"intermediate_idx {intermediate_idx} not in intermediate_idx_to_ph_idx for REMOVE_ADDITIONAL_INPUTS" + ) + inp_idx = intermediate_idx_to_ph_idx[intermediate_idx] + self.saved_fw_additional_inputs.append(real_graph_inputs[inp_idx]) + else: + new_output_node.append(node) + + fw_output_node.args = (tuple(fw_outputs) + tuple(new_output_node),) + fw_gm.graph.lint() + fw_gm.recompile() + + if logger.isEnabledFor(logging.DEBUG): + logger.debug( + "after removing aliasing:\n%s", fw_gm.print_readable(print_output=False) + ) + + def call_forward(self): + fw_outputs_and_intermediates: tuple[Any] = scan_op( + self.hop_partitioned_graph.fw_gm, self.init, self.xs, self.additional_inputs + ) # type: ignore[return-type] + fw_outs = fw_outputs_and_intermediates[ + : self.hop_partitioned_graph.n_fw_outputs + ] + saved_intermediates = fw_outputs_and_intermediates[ + self.hop_partitioned_graph.n_fw_outputs : + ] + if len(self.saved_intermediates) != 0: + raise AssertionError( + "saved_intermediates should be empty before call_forward" + ) + self.saved_intermediates.extend(saved_intermediates) + return tuple(fw_outs) + + def call_backward(self, *grad_fw_outputs): + """ + Recall that fw_outputs = (*carry, *ys), bw_gm takes in (*fw_intermediates, *grad_carry, *grad_ys) + and returns (*grad_init, *grad_xs, *grad_additional_inputs) + The backward is a reversed scan that can be constructed as follows: + + grad_additional_inputs = torch.zeros_like(additional_inputs) + bw_init = (grad_carry, grad_additional_inputs) + bw_xs = (fw_intermediates, grad_ys) + grad_init, grad_additional_inputs, grad_xs = scan( + combine_fn, + bw_init, + bw_xs, + reverse = True + ) + , where combine_fn is defined as follows: + + def combine_fn(bw_init, bw_xs): + grad_carry, grad_additional_inputs = bw_init + fw_intermediates, grad_y = bw_xs + nxt_grad_carry, grad_x, nxt_grad_additional_inputs = bw_gm(*fw_intermediates, *grad_carry, *grad_y) + return (nxt_grad_carry, grad_additional_inputs + nxt_grad_additional_inputs), grad_x + + Note that grad_additional_inputs is accumulated with add, grad_carry is carried over to next iteration and + grad_x is the ys output, which will be stacked together after the loop and will have the same shape as xs. + """ + fw_policy = self.forward_intermediates_handling_policies + saved_intermediates = self.saved_intermediates + saved_fw_xs = self.saved_fw_xs + saved_fw_additional_inputs = self.saved_fw_additional_inputs + + n_carry = len(self.init) + + grad_carry, grad_ys = grad_fw_outputs[:n_carry], grad_fw_outputs[n_carry:] + additional_inputs_tensor_masks = [ + bool(isinstance(t, torch.Tensor)) for t in self.additional_inputs + ] + grad_additional_inputs = [ + torch.zeros_like(t) + for t in filter_with_masks( + self.additional_inputs, additional_inputs_tensor_masks + ) + ] + + bw_init = [grad_carry, grad_additional_inputs] + bw_xs = [ + grad_ys, + saved_fw_xs, + saved_intermediates, + ] + bw_additional_inputs = saved_fw_additional_inputs + + _, flat_spec = pytree.tree_flatten((bw_init, bw_xs, bw_additional_inputs)) + + grad_spec = None + + def bw_single_step_wrapper(*args): + bw_init, bw_xs, bw_additional_inputs = pytree.tree_unflatten( + args, flat_spec + ) + grad_carry, grad_additional_inputs = bw_init + grad_y, saved_fw_xs, saved_intermediates = bw_xs + saved_fw_additional_inputs = bw_additional_inputs + + fw_intermediates = [] + xs_it = iter(saved_fw_xs) + carry_it = iter(saved_intermediates) + addi_it = iter(saved_fw_additional_inputs) + for policy in fw_policy: + if policy in ( + ScanForwardIntermediatesHandlingPolicy.CLONE, + ScanForwardIntermediatesHandlingPolicy.KEEP, + ): + fw_intermediates.append(next(carry_it)) + elif policy == ScanForwardIntermediatesHandlingPolicy.REMOVE_XS: + fw_intermediates.append(next(xs_it)) + elif ( + policy + == ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS + ): + fw_intermediates.append(next(addi_it)) + else: + raise RuntimeError(f"Unknown policy: {policy}") + + grad_fw_outputs = (*grad_carry, *grad_y) + + flat_out = self.hop_partitioned_graph.bw_gm( + *fw_intermediates, + *grad_fw_outputs, + ) + + next_grad_carry, grad_xs, grad_addi = split_into_chunks( + flat_out, # type: ignore[arg-type] + [len(self.init), len(self.xs), len(self.additional_inputs)], + ) + + nonlocal grad_spec + flat_grads, grad_spec = pytree.tree_flatten( + ( + next_grad_carry, + [ + prev + cur + for prev, cur in zip( + grad_additional_inputs, + filter_with_masks( + grad_addi, additional_inputs_tensor_masks + ), + ) + ], + grad_xs, + ) + ) + return flat_grads + + single_step_bw_xs = pytree.tree_map(first_slice_copy, bw_xs) + bw_single_step_gm = materialize_as_graph( + bw_single_step_wrapper, + tuple( + pytree.tree_flatten((bw_init, single_step_bw_xs, bw_additional_inputs))[ + 0 + ] + ), + ) + + flat_grads = scan_op( + bw_single_step_gm, + pytree.tree_flatten(bw_init)[0], + # TODO: torch.flip copies the tensor, we should optimize it away + [torch.flip(x, (0,)) for x in pytree.tree_flatten(bw_xs)[0]], + pytree.tree_flatten(bw_additional_inputs)[0], + ) + if grad_spec is None: + raise AssertionError("grad_spec must not be None after scan_op") + grad_init, grad_additional_inputs, grad_xs = pytree.tree_unflatten( + flat_grads, grad_spec + ) + return ( + *grad_init, + *[torch.flip(elem, (0,)) for elem in grad_xs], + *fill_none_with_masks( + grad_additional_inputs, additional_inputs_tensor_masks + ), + ) + + +@scan_op.py_autograd_impl +def scan_autograd(combine_fn, init, xs, additional_inputs, mutated_arg_indices=""): + with disable_proxy_modes_tracing(): + # If init was passed in with requires_grad=False, AOT joint creation drops it from + # grad_primals and zero-fills, severing the carry chain and silently + # zeroing gradients that should reach closed-over additional_inputs from + # earlier steps. Thus, we temporarily flip requires_grad on the init tensors + # during tracing and restore it afterwards; this only affects the traced + # graphs, not the operands passed to apply. init elements are leaves. + flipped = [ + t + for t in init + if (t.dtype.is_floating_point or t.dtype.is_complex) and not t.requires_grad + ] + try: + for t in flipped: + t.requires_grad_(True) + hop_partitioned_graph: HopPartitionedGraph = ( + HopGraphMinCutPartitioner.create_partitioned_graph( + combine_fn, + (*init, *[first_slice_copy(x) for x in xs], *additional_inputs), + always_recompute_complex_exprs=True, + ) + ) + finally: + for t in flipped: + t.requires_grad_(False) + + return ScanAutogradOp.apply( + hop_partitioned_graph, + len(init), + len(xs), + len(additional_inputs), + *init, + *xs, + *additional_inputs, + ) + + +@scan_op.py_impl(ProxyTorchDispatchMode) +def scan_proxy_mode( + mode, combine_fn, init, xs, additional_inputs, mutated_arg_indices="" +): + return trace_scan( + mode, + scan_op, + combine_fn, + init, + xs, + additional_inputs, + mutated_arg_indices=mutated_arg_indices, + ) + + +@scan_op.py_impl(FakeTensorMode) +def scan_fake_tensor_mode( + mode, combine_fn, init, xs, additional_inputs, mutated_arg_indices="" +): + with mode: + scan_length = xs[0].shape[0] + carry, outputs = _extract_carry_and_out( + combine_fn( + *init, + *[first_slice_copy(inp) for inp in xs], + *additional_inputs, + ), + len(init), + ) + for t in outputs: + if not isinstance(t, torch.Tensor) and t is not None: + raise AssertionError( + f"Expected leaf to be a Tensor or None, got {type(t)}" + ) + out = ( + *carry, + *( + stack_y(t, scan_length) if isinstance(t, torch.Tensor) else t + for t in outputs + ), + ) + return out + + +@scan_op.py_functionalize_impl +def scan_functionalize( + ctx, combine_fn, init, xs, additional_inputs, mutated_arg_indices="" +): + from torch._higher_order_ops.utils import ( + _check_alias_and_mutation, + _maybe_run_with_interpreter, + ) + + if hasattr(ctx, "mode"): + hop_instance = HopInstance.create( + scan_op, + combine_fn, + init, + xs, + additional_inputs, + mutated_arg_indices=mutated_arg_indices, + ) + if can_auto_functionalize(hop_instance): + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + tuple( + pytree.tree_flatten((combine_fn, init, xs, additional_inputs))[0] + ), + {}, + ) + + unwrapped_xs = ctx.unwrap_tensors(xs) + unwrapped_init = ctx.unwrap_tensors(init) + unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs) + + with ctx.redispatch_to_next(): + functional_combine_fn = ctx.functionalize( + _maybe_run_with_interpreter(combine_fn) + ) + sample_unwrapped_xs_sliced = ( + [first_slice_copy(inp) for inp in unwrapped_xs] + if len(unwrapped_xs) > 0 + else [None] + ) + sample_inputs = list( + itertools.chain( + unwrapped_init, + sample_unwrapped_xs_sliced, + unwrapped_additional_inputs, + ) + ) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + _check_alias_and_mutation(combine_fn, sample_inputs, "scan", pre_dispatch) + ret = scan_op( + functional_combine_fn, + unwrapped_init, + unwrapped_xs, + unwrapped_additional_inputs, + mutated_arg_indices=mutated_arg_indices, + ) + return ctx.wrap_tensors(ret) + + +@scan_op.py_impl(torch._C._functorch.TransformType.Vmap) +def scan_batch_rule( + interpreter, combine_fn, init, xs, additional_inputs, mutated_arg_indices="" +): + unbatched_args, in_dims = unwrap_batched( + (init, xs, additional_inputs), interpreter.level() + ) + # move to last dim to not interfere with scan's batching + unbatched_init, unbatched_xs, unbatched_additional_inputs = pytree.tree_map( + lambda x, bdim: x.movedim(bdim, -1) if bdim is not None else x, + unbatched_args, + in_dims, + ) + after_move_dims = tuple( + pytree.tree_flatten( + pytree.tree_map(lambda x: -1 if x is not None else None, in_dims) + )[0] + ) + + with interpreter.lower(): + out_dims = None + + def wrapper(*args): + nonlocal out_dims + outputs, per_slice_out_dims = restore_vmap( + combine_fn, + after_move_dims, + interpreter.batch_size(), + interpreter.randomness(), + )(*args) + # Note: outputs are not batched, we just move the batch dim to the end + # this is to avoid it interfering with scan's batching + outputs = tuple( + pytree.tree_map( + lambda out, out_bdim: out.movedim(out_bdim, -1) + if out_bdim is not None + else out, + outputs, + per_slice_out_dims, + ) + ) + out_dims = tuple( + pytree.tree_map( + lambda out_bdim: -1 if out_bdim is not None else None, + per_slice_out_dims, + ) + ) + return outputs + + op_kwargs = {} + if mutated_arg_indices: + op_kwargs["mutated_arg_indices"] = mutated_arg_indices + unwrapped_out = scan_op( + wrapper, + unbatched_init, + unbatched_xs, + unbatched_additional_inputs, + **op_kwargs, + ) + + if out_dims is None: + raise AssertionError("out_dims must not be None after scan_op") + batched_out = wrap_batched(unwrapped_out, out_dims, interpreter.level()) + return batched_out + + +# dense implementation for scan. Used for testing only. +def _fake_scan(combine_fn, init, xs=None, dim=0, reverse=False, length=None): + carry_leaves, carry_spec = pytree.tree_flatten(init) + inp_leaves, inp_spec = pytree.tree_flatten(xs) + xs_has_tensors = any(isinstance(l, torch.Tensor) for l in inp_leaves) + + if length is not None and not xs_has_tensors: + if length == 0: + return init, _build_empty_output_for_length_zero(combine_fn, init) + + _user_combine_fn = combine_fn + + def combine_fn(carry, _ignored): + return _user_combine_fn(carry, None) + + # Dummy length-N iteration counter; the wrapped combine_fn passes x=None. + inp_leaves = [torch.zeros(length, dtype=torch.int64)] + inp_spec = pytree.tree_structure(None) + xs_has_tensors = True + + if not xs_has_tensors: + return init, [] + result_flat = [] + carry = carry_leaves + op = reversed if reverse else lambda x: x + + _, dummy_out = combine_fn( + pytree.tree_unflatten(carry, carry_spec), + pytree.tree_unflatten( + [first_slice_copy(elem, dim) for elem in inp_leaves], + inp_spec, + ), + ) + dummy_out_leaves, dummy_out_spec = pytree.tree_flatten(dummy_out) + + for ind in op(range(inp_leaves[0].size(dim))): + xs = [elem.select(dim, ind) for elem in inp_leaves] + + carry, y = combine_fn( + pytree.tree_unflatten(carry, carry_spec), + pytree.tree_unflatten(xs, inp_spec), + ) + carry, _ = pytree.tree_flatten(carry) + y, _ = pytree.tree_flatten(y) + result_flat.append(y) + + results: list[torch.Tensor | None] = [] + for leaf_idx, leaf in enumerate(dummy_out_leaves): + if isinstance(leaf, torch.Tensor): + if len(result_flat) == 0: + stacked = torch.empty( + [0] + list(leaf.shape), dtype=leaf.dtype, device=leaf.device + ) + else: + stacked = torch.stack([e[leaf_idx] for e in op(result_flat)]) + results.append( + torch.movedim(stacked, 0, dim) if dim < stacked.ndim else stacked + ) + else: + if leaf is not None: + raise AssertionError( + f"Expected leaf to be a Tensor or None, got {type(leaf)}" + ) + results.append(leaf) + return ( + pytree.tree_unflatten(carry, carry_spec), + pytree.tree_unflatten(results, dummy_out_spec), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/schema.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..e0e80774ddd1af103bf9f3b13e7bde611dbf8604 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/schema.py @@ -0,0 +1,323 @@ +import copy +from dataclasses import dataclass +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class +from torch.fx.node import Target + + +# Below is an implementation of generating FunctionSchema from example values. +# This is helpful for generating FunctionSchema for HigherOrderOperator, where +# we don't have a function to inspect and each call of the higher order operator +# would have different schema. +@dataclass(frozen=True, slots=True) +class HopArgumentInfo: + # Could give a name to the operand by default it's empty string. + name: str + example_value: Any + # Provide a default_value + default_value: Any + # Whether this argument gets mutated in the hop subgraph. + # For output, this should always be False + is_mutated: bool + kw_only: bool + + +class HopArgumentInfoGen: + @staticmethod + def from_example( + example_value: Any, + *, + name: str = "", + default_value: Any | None = None, + is_mutated: bool = False, + kw_only: bool = False, + ) -> HopArgumentInfo: + if default_value is not None: + if type(example_value) is not type(default_value): + raise AssertionError( + f"example_value type {type(example_value)} doesn't match default_value type: {type(default_value)}" + ) + + return HopArgumentInfo( + name=name, + example_value=example_value, + default_value=default_value, + is_mutated=is_mutated, + kw_only=kw_only, + ) + + +class CTypeGen: + convert_to_base_ty = { + int: torch._C.IntType.get(), + float: torch._C.FloatType.get(), + str: torch._C.StringType.get(), + bool: torch._C.BoolType.get(), + } + + # should return torch._C.JitType but that annotation is busted + @staticmethod + def from_example(obj: Any) -> Any: + import torch + + if isinstance(obj, torch.fx.GraphModule): + return torch._C.AnyType.get() + elif isinstance(obj, torch.SymInt): + return torch._C.SymIntType.get() + elif isinstance(obj, torch.SymBool): + return torch._C.SymBoolType.get() + elif isinstance(obj, torch.SymFloat): + return torch._C.FloatType.get() + elif isinstance(obj, (FakeScriptObject, pytree.TreeSpec)) or is_custom_class( + type(obj) + ): + return torch._C.PyObjectType.get() # pyrefly: ignore[missing-attribute] + return torch._C._jit_try_infer_type(obj).type() + + +class CArgumentGen: + @staticmethod + def from_hop_argument_info( + arg_idx: int, arg_info: HopArgumentInfo, is_output: bool = False + ) -> Any: + typ = CTypeGen.from_example(arg_info.example_value) + if is_output: + return torch._C.Argument("", typ, None, None, False, None) + + alias_set = set({f"alias::a{arg_idx}"}) if arg_info.is_mutated else set() + alias_info = torch._C._AliasInfo(arg_info.is_mutated, alias_set, alias_set) # type: ignore[attr-defined] + return torch._C.Argument( + arg_info.name, + typ, + None, + arg_info.default_value, + arg_info.kw_only, + alias_info, + ) + + +class HopSchemaGenerator: + def __init__(self, hop: torch._ops.HigherOrderOperator): + self.arg_infos: list[HopArgumentInfo] = [] + self.example_outputs: list[Any] = [] + self.schema_tree_spec: pytree.TreeSpec | None = None + self.hop = hop + + def add_arg( + self, + name: str, + example_value: Any, + default_value: Any | None = None, + is_mutated: bool = False, + kw_only: bool = False, + ) -> None: + if callable(example_value) and not is_custom_class(type(example_value)): + if not isinstance( + example_value, (torch.fx.GraphModule, torch._ops.OperatorBase) + ): + raise AssertionError( + "Expect callable to be a GraphModule or an OperatorBase. Please call materialize_as_graph first " + f"to turn callable arguments {example_value} into a GraphModule." + ) + _, flat_spec = pytree.tree_flatten(example_value) + if not flat_spec.is_leaf(): + raise RuntimeError( + f"example_value {example_value} is not a leaf node. " + "Please only add flattened inputs to the hop schema. " + "If you need some structure in the arguments, please" + "add_arg for flattened args one by one then " + "call add_schema_tree_spec to register the original pytree " + " spec of the args." + ) + + arg_info = HopArgumentInfoGen.from_example( + example_value=example_value, + name=name, + default_value=default_value, + is_mutated=is_mutated, + kw_only=kw_only, + ) + self.arg_infos.append(arg_info) + + def add_output(self, output: Any) -> None: + self.example_outputs.append(output) + + def add_schema_tree_spec(self, *args: Any, **kwargs: Any) -> None: + """schema tree spec is the tree spec from flattening all inputs to the hop with pytree.tree_flatten + Since torch.FunctionSchema only have proper mutation/alias support for flattened inputs, we need + to store the tree spec in order to reconstruct the inputs to the hop. + """ + self.schema_tree_spec = pytree.tree_flatten((args, kwargs))[1] + + def gen_schema(self) -> torch._C.FunctionSchema: + for i, arg_info in enumerate(self.arg_infos): + arg_spec = pytree.tree_flatten(arg_info.example_value)[1] + if not arg_spec.is_leaf() and self.schema_tree_spec is None: + raise RuntimeError( + f"example_value of arg_infos[{i}] is {arg_info.example_value}, which is not a leaf node. " + "Please call add_schema_tree_spec to add a schema tree spec first. " + "Or consider changing the hop's signature to only take flattened arguments." + ) + + return CFunctionSchemaGen.from_hop_argument_info( + str(self.hop), + self.arg_infos, + HopArgumentInfoGen.from_example(tuple(self.example_outputs), name="out"), + self.schema_tree_spec, + ) + + +class CFunctionSchemaGen: + """ + Note: [HigherOrderOperator schema generation] + Each invocation of a HigherOrderOperator will have a different schema. + For example, the schema of torch.cond varies depending on the true_fn and + false_fn. So we need a way to generate the schema for each invocation of a HOP. + + We want to enforce the following invariants for HOP's schema: + 1. Flattened inputs. There should be no pytree structure in it. + 2. Flattened outputs. Note even if the hop returns a single value, it should be wrapped as a tuple. + 3. No aliasing. This includes inp-inp aliasing, inp-out aliasing and out-out aliasing. + + By enforcing these invariants, we could make HOP's schema meets the requirement of schema parser + and makes hop easier to handle downstream. For example, suppose we have an invoke_quant_test HOP: + + class GraphModule(torch.nn.Module): + def forward(self, l_x_, l_y_): + subgraph_0 = self.subgraph_0 + invoke_quant_test = torch.ops.higher_order.invoke_quant_test(subgraph_0, l_x_, l_y_, scheme = 'nf4'); + + class subgraph_0(torch.nn.Module): + def forward(self, l_x_, l_y_): + add_ = l_x_.add_(1) + matmul = l_x_ @ l_y_ + sin = matmul.sin() + child = sin.cos() + child_1 = l_x_ + l_y_ + child_2 = l_x_ - l_y_ + child_3 = l_x_ @ l_y_ + return (child, child_1, child_2, child_3) + + By encoding the inputs of hop into a list of HopArgumentInfo and output as a single HopArgumentInfo, + we would get the following schema: + invoke_quant_test(Any arg0, Tensor(!) arg1, Tensor arg2, str scheme="\\"nf4\\"") -> (Tensor, Tensor, Tensor, Tensor) + """ + + @staticmethod + def from_hop_argument_info( + op_name: str, + inp_argument_info: list[HopArgumentInfo], + out_argument_info: HopArgumentInfo, + schema_tree_spec: pytree.TreeSpec | None, + ) -> Any: + args = [] + for i, arg_info in enumerate(inp_argument_info): + args.append(CArgumentGen.from_hop_argument_info(i, arg_info)) + + # NOTE: we want the output to always be a single argument with torch._C.TupleType. + if not isinstance(out_argument_info.example_value, tuple): + raise AssertionError( + f"expect out_argument_info's example_value to be a tuple but got {out_argument_info.example_value}" + ) + if out_argument_info.is_mutated: + raise AssertionError( + "out_argument_info.is_mutated should always be set to False." + ) + rets = None + if len(out_argument_info.example_value) == 1: + rets = [CArgumentGen.from_hop_argument_info(0, out_argument_info, True)] + else: + rets = [ + CArgumentGen.from_hop_argument_info( + i, + HopArgumentInfoGen.from_example( + name=f"out{i}", + example_value=val, + default_value=None, + is_mutated=False, + ), + is_output=True, + ) + for i, val in enumerate(out_argument_info.example_value) + ] + + return HopSchema( + op_name, + "", + args, + rets, + False, + False, + schema_tree_spec, + ) + + +class HopSchema(torch._C.FunctionSchema): + def __init__( + self, + name: str, + overload_name: str, + arguments: list[torch._C.Argument], + returns: list[torch._C.Argument], + is_vararg: bool, + is_varret: bool, + schema_tree_spec: pytree.TreeSpec | None, + ): + self.tree_spec = schema_tree_spec + self.is_vararg = is_vararg + self.is_varret = is_varret + super().__init__( + name, + overload_name, + arguments, + returns, + self.is_vararg, + self.is_varret, + ) + + def __deepcopy__(self, memo: Any) -> "HopSchema": + # Need to additionally copy the tree_spec since + # it's not a member of torch._C.FunctionSchema + return HopSchema( + self.name, + self.overload_name, + self.arguments, + self.returns, + self.is_vararg, + self.is_varret, + copy.deepcopy(self.tree_spec), + ) + + +def find_hop_schema( + gm: torch.fx.GraphModule, target: Target +) -> list[torch._C.FunctionSchema]: + schemas = [] + for node in gm.graph.find_nodes(op="call_function", target=target): + + def _get_example_value(node: torch.fx.Node) -> Any: + if node.op == "get_attr": + if not isinstance(node.target, str): + raise AssertionError( + f"expected node.target to be str for get_attr, got {type(node.target)}" + ) + return getattr(gm, node.target) + else: + return ( + node.meta["example_value"] + if "example_value" in node.meta + else node.meta["val"] + ) + + fake_args, fake_kwargs = pytree.tree_map_only( + torch.fx.Node, + _get_example_value, + (node.args, node.kwargs), + ) + schema = node.target.gen_schema(*fake_args, **fake_kwargs) + schemas.append(schema) + return schemas diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/strict_mode.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/strict_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..0257e3edd82879e65f16a6befcab8b2fed57cd43 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/strict_mode.py @@ -0,0 +1,92 @@ +# mypy: allow-untyped-defs + +import torch +import torch._subclasses.functional_tensor +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._functorch.utils import exposed_in +from torch._higher_order_ops.utils import autograd_not_implemented, register_fake +from torch._ops import HigherOrderOperator +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + make_fx, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.utils._python_dispatch import _get_current_dispatch_mode + + +@exposed_in("torch") +def strict_mode(callable, operands): + if torch.compiler.is_dynamo_compiling(): + return strict_mode_op(callable, operands) + + from torch._higher_order_ops.utils import _hop_compile_and_call + + return _hop_compile_and_call(strict_mode_op, (callable, operands)) + + +class StrictMode(HigherOrderOperator): + def __init__(self): + super().__init__("strict_mode") + + def __call__(self, callable, operands): + # pyrefly: ignore [missing-attribute] + return super().__call__(callable, operands) + + +strict_mode_op = StrictMode() + + +@strict_mode_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def strict_mode_op_dense(callable, operands): + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + return callable(*operands) + + +strict_mode_op.py_autograd_impl( + autograd_not_implemented(strict_mode_op, deferred_error=True) +) + + +@strict_mode_op.py_impl(ProxyTorchDispatchMode) +def inner(mode, callable, operands): + return trace_strict_mode(mode, strict_mode_op, callable, operands) + + +def trace_strict_mode(mode, strict_mode_op, callable, operands): + pre_dispatch = getattr(mode, "pre_dispatch", False) + + with disable_proxy_modes_tracing(): + graph = make_fx(callable, pre_dispatch=pre_dispatch)(*operands) + + graph_name = mode.tracer.get_fresh_qualname("strict_graph_") + mode.tracer.root.register_module(graph_name, graph) + + args = (graph, operands) + + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args) + + out_proxy = mode.tracer.create_proxy( + "call_function", strict_mode_op, proxy_args, {}, name="strict_mode" + ) + + out = graph(*operands) + return track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + + +@register_fake(strict_mode_op, skip_cache=True) +def strict_mode_fake_tensor_mode(callable, operands): + return callable(*operands) + + +@strict_mode_op.py_functionalize_impl +def strict_mode_func(ctx, callable, inputs): + unwrapped_inputs = ctx.unwrap_tensors(inputs) + with ctx.redispatch_to_next(): + functional_callable = ctx.functionalize(callable) + + cond_return = strict_mode_op(functional_callable, unwrapped_inputs) + return ctx.wrap_tensors(cond_return) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/switch.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/switch.py new file mode 100644 index 0000000000000000000000000000000000000000..4651afa5d9c6526f01c82340059fc10b8cb88413 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/switch.py @@ -0,0 +1,424 @@ +import contextlib +import functools +import logging +import warnings +from collections.abc import Callable +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._functorch.utils import exposed_in +from torch._higher_order_ops.utils import ( + _maybe_compile_and_run_fn, + _maybe_run_with_interpreter, + check_input_alias_and_mutation_return_outputs, + create_bw_fn, + create_fn_remove_none, + fill_none_with_masks, + materialize_as_graph, + reenter_make_fx, + save_values_for_backward, + saved_values, + unique_graph_id, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.utils._python_dispatch import _get_current_dispatch_mode + + +log = logging.getLogger(__name__) + + +class SwitchOp(HigherOrderOperator): + def __init__(self): + super().__init__("switch") + + def __call__(self, index, branches, operands): + validate_subgraph_args_types(operands) + # pyrefly: ignore [missing-attribute] + return super().__call__(index, branches, operands) + + # pyrefly: ignore [bad-override] + def gen_schema(self, index, branches, operands): + from torch._higher_order_ops.schema import HopSchemaGenerator + from torch._higher_order_ops.utils import materialize_as_graph + + branch_gms: list[torch.fx.GraphModule] = [] + branch0_outputs: list[Any] | tuple[Any, ...] = [] + mutated_inputs: set[int] = set() + for branch in branches: + gm = materialize_as_graph(branch, operands) + ( + _, + _, + _, + branch_mutated_inputs, + branch_outputs, + ) = check_input_alias_and_mutation_return_outputs(gm) + branch_gms.append(gm) + if not branch0_outputs: + branch0_outputs = branch_outputs + mutated_inputs |= set(branch_mutated_inputs) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("index", index) + for i, gm in enumerate(branch_gms): + schema_gen.add_arg(f"branch{i}_fn", gm) + for idx, arg in enumerate(operands): + schema_gen.add_arg(f"operand{idx}", arg, is_mutated=idx in mutated_inputs) + + for out in branch0_outputs: + schema_gen.add_output(out) + schema_gen.add_schema_tree_spec(index, branches, operands) + return schema_gen.gen_schema() + + +switch_op = SwitchOp() + + +def wrap_branch_fn_flat(*args, branch_fn, spec_operands): + operands = pytree.tree_unflatten(args, spec_operands) + return branch_fn(*operands) + + +def _get_branch(branches, idx): + if not 0 <= idx < len(branches): + raise AssertionError( + f"switch index {idx} out of range for {len(branches)} branches" + ) + return branches[idx] + + +@exposed_in("torch") +def switch( + index: int | torch.SymInt | torch.Tensor, + branches: tuple[Callable, ...] | list[Callable], + operands: tuple | list = (), +) -> Any: + r""" + Selects and runs one of N branch functions by index. + + .. warning:: + + `torch.switch` is a prototype feature in PyTorch. It has limited support for input and + output types. Please look forward to a more stable implementation in a future version of + PyTorch. Read more about feature classification at: + https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + Equivalent to: ``branches[index](*operands)`` with index in ``[0, len(branches))``. + + Args: + index (Union[int, torch.Tensor]): An int or single-element integer tensor + indicating which branch to run. Out-of-range values are clamped into + ``[0, len(branches))``. + + branches (Union[tuple[Callable, ...], list[Callable]]): Non-empty sequence of + callables. Each must accept operands and return the same structure of outputs. + + operands (Tuple of possibly nested dict/list/tuple of torch.Tensor): Inputs to + the branch functions. Defaults to (). + + Restrictions: + - Each branch must have the same signature as operands and return the same + output structure (shape, dtype, etc.). Constant ``int`` and ``None`` leaves + are also permitted in branch outputs and are merged across branches (an + unbacked SymInt is introduced when ``int`` leaves differ between branches). + - Branches cannot have in-place mutations on inputs or global variables. + """ + + # Flatten operands so the HOP only sees a flat list of tensors. + # Each branch is wrapped to unflatten the leaves + # back to the user-facing pytree before invocation. + leaves_operands, spec_operands = pytree.tree_flatten(operands) + + def _validate_input(index, branches, operands): + if not isinstance(index, (int, torch.SymInt, torch.Tensor)): + raise RuntimeError( + f"Expected index to be int or single-element tensor, but got {index}." + ) + + if isinstance(index, torch.Tensor) and index.numel() != 1: + raise RuntimeError( + f"Expected index to be int or single-element tensor, but got {index}." + ) + + if not isinstance(branches, (tuple, list)) or len(branches) == 0: + raise RuntimeError( + "Expected branches to be a non-empty tuple or list of callables." + ) + + for i, branch in enumerate(branches): + if not callable(branch): + raise RuntimeError( + f"Expected all branches to be callable. branch{i} is not callable." + ) + + for x in operands: + if not isinstance(x, torch.Tensor): + raise RuntimeError(f"All operand leaves must be a Tensor but got {x}") + + _validate_input(index, branches, leaves_operands) + + wrapped_branches = tuple( + functools.partial( + wrap_branch_fn_flat, + branch_fn=branch_fn, + spec_operands=spec_operands, + ) + for branch_fn in branches + ) + + # Early shortcut: single-branch switch degenerates to a plain call + num_branches = len(wrapped_branches) + if num_branches == 1: + return wrapped_branches[0](*leaves_operands) + + # Clamp out-of-range indices to [0, len(branches) - 1] + if isinstance(index, torch.Tensor): + index = index.clamp(0, num_branches - 1) + elif isinstance(index, torch.SymInt): + index = torch.sym_max(0, torch.sym_min(index, num_branches - 1)) + elif isinstance(index, int): + index = max(0, min(index, num_branches - 1)) + + # Constant index shortcut for eager mode. + if not torch.compiler.is_dynamo_compiling() and isinstance(index, int): + # This is the non-strict export case. Strict export and torch.compile are + # handled below via _maybe_compile_and_run_fn. + if torch.compiler.is_compiling(): + warnings.warn( + "Index is a Python constant. When used with torch.switch, it specializes on one of the branches." + " If you want torch.switch to preserve the branches, please make the index an int tensor or a SymInt.", + UserWarning, + stacklevel=2, + ) + + return _get_branch(wrapped_branches, index)(*leaves_operands) + + # Use _maybe_compile_and_run_fn pattern from scan/associative_scan + def run_switch(index, wrapped_branches, leaves_operands): + return switch_op(index, wrapped_branches, leaves_operands) + + return _maybe_compile_and_run_fn( + run_switch, index, wrapped_branches, leaves_operands + ) + + +def trace_switch(proxy_mode, func_overload, index, branches, operands): + if not isinstance(operands, (list, tuple)): + raise AssertionError( + f"Switch operands must be a list or tuple of tensors and SymInts {operands}" + ) + if not isinstance(branches, (list, tuple)) or len(branches) == 0: + raise AssertionError( + "Switch branches must be a non-empty list or tuple of callables" + ) + + branch_graphs = [reenter_make_fx(branch)(*operands) for branch in branches] + + branch_outs = [list() for _ in branches] + for i, branch_graph in enumerate(branch_graphs): + for node in branch_graph.graph.nodes: + if node.op == "output": + branch_outs[i].extend(node.args) + + branch_out_spec = [pytree.tree_flatten(outs)[1] for outs in branch_outs] + for i, spec in enumerate(branch_out_spec): + if branch_out_spec[0] != spec: + raise RuntimeError( + "Unmatched output spec from torch.switch branches: " + f"branch0 tree_spec {branch_out_spec[0]} vs branch{i} tree_spec {spec}" + ) + + uid, _ = unique_graph_id(proxy_mode, prefix="branch0_graph") + for i, branch_graph in enumerate(branch_graphs): + proxy_mode.tracer.root.register_module(f"branch{i}_graph_{uid}", branch_graph) + + args = (index, branch_graphs, operands) + + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", func_overload, proxy_args, {} + ) + + out = func_overload(index, branch_graphs, operands) + + return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + + +@switch_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def switch_op_dense(index, branches, operands): + if not all(isinstance(o, (torch.Tensor, int)) for o in operands): + raise RuntimeError( + f"Dense implementation operands must be a list of tensors and ints {operands}" + ) + mode = _get_current_dispatch_mode() + if mode is not None: + raise AssertionError("Mode should never be enabled for CPU/CUDA key") + idx: int = int(index.item()) if isinstance(index, torch.Tensor) else int(index) + return _get_branch(branches, idx)(*operands) + + +class SwitchAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + index, + branches, + *operands, + ): + ctx._index = index + # Build one bw fn per branch. + ctx._branch_bw_fns = [ + create_bw_fn(create_fn_remove_none(branch)[0], operands) + for branch in branches + ] + + # We snapshot the dispatch keys in forward for materializing the + # bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + save_values_for_backward(ctx, operands) + + with torch._C._AutoDispatchBelowAutograd(): + outs = switch_op(index, branches, operands) + + # Record which output slots are Tensors. Non-Tensor slots (None, + # int/SymInt) carry no tangent in backward and the joint is built + # to omit them. + ctx._fw_output_is_tensor = [ + isinstance(o, torch.Tensor) for o in pytree.tree_leaves(outs) + ] + return outs + + @staticmethod + def backward(ctx, *flat_grads): + operands = saved_values(ctx) + tensor_grads = tuple( + g for g, keep in zip(flat_grads, ctx._fw_output_is_tensor) if keep + ) + args = operands + tensor_grads + # TODO: we need to materialize the bw graphs because dynamo is unable to + # trace through the joint function when torch.compile torch.autograd.grad. + + branches_bw_gm: list[torch.fx.GraphModule] = [] + grads_tensor_masks: list[bool] = [] + # All branches share the same input signature (see _validate_input) + for bw_fn in ctx._branch_bw_fns: + wrapped_bw, mask = create_fn_remove_none(bw_fn) + bw_gm = materialize_as_graph( + wrapped_bw, + args, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + branches_bw_gm.append(bw_gm) + if not grads_tensor_masks: + grads_tensor_masks = mask + + grads = switch_op( + ctx._index, + branches_bw_gm, + args, + ) + return None, None, *fill_none_with_masks(grads, grads_tensor_masks) + + +@switch_op.py_autograd_impl +def switch_autograd(index, branches, operands): + return SwitchAutogradOp.apply( + index, + branches, + *operands, + ) + + +@switch_op.py_impl(ProxyTorchDispatchMode) +def inner(mode, index, branches, operands): + return trace_switch(mode, switch_op, index, branches, operands) + + +@switch_op.py_impl(FakeTensorMode) +def switch_fake_tensor_mode(mode, index, branches, operands): + # Ignore here, because if you've gotten here but you're not manually + # tracing the inner graphs, that means that you intend to reuse the graph + # directly. Which means the old unbacked symbol bindings are appropriate. + # This strategy will not work if unbacked symbols can escape. + ignore_fresh_unbacked = contextlib.nullcontext() + if mode.shape_env: + ignore_fresh_unbacked = mode.shape_env.ignore_fresh_unbacked_symbols() + + with mode, ignore_fresh_unbacked: + flat_branch_outs, branch_out_spec = zip( + *[pytree.tree_flatten(branch(*operands)) for branch in branches] + ) + for i, spec in enumerate(branch_out_spec): + if branch_out_spec[0] != spec: + raise RuntimeError( + "Unmatched output spec from torch.switch branches: " + f"branch0 tree_spec {branch_out_spec[0]} vs branch{i} tree_spec {spec}" + ) + + merged_outs = [] + for branches_out in zip(*flat_branch_outs): + merged_outs.append(_merge_output(branches_out, mode)) + return pytree.tree_unflatten(merged_outs, branch_out_spec[0]) + + +def _merge_output(xs: tuple[torch.Tensor | int | None, ...], mode: FakeTensorMode): + from torch._higher_order_ops.cond import ( + _merge_ints_to_symint, + _merge_output as cond_merge_output, + ) + + # Shortcut if a branch produces None outputs; then all branches need to produce None + if any(x is None for x in xs): + if not all(x is None for x in xs): + raise AssertionError(f"expected all leaves to be None, got {xs}") + return None + + # In case all branches return an int, use an unbacked symbol as the merge result + if all(type(x) is int for x in xs): + return _merge_ints_to_symint(list(xs), mode) # type: ignore[arg-type] + + return functools.reduce(lambda a, b: cond_merge_output(a, b, mode), xs) + + +@switch_op.py_functionalize_impl +def switch_func(ctx, index, branches, inputs): + from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, + ) + from torch._higher_order_ops.utils import _check_alias_and_mutation, HopInstance + + hop_instance = HopInstance.create(switch_op, index, branches, inputs) + if can_auto_functionalize(hop_instance) and hasattr(ctx, "mode"): + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + tuple(pytree.tree_flatten((index, branches, inputs))[0]), + {}, + ) + + unwrapped_inputs = ctx.unwrap_tensors(inputs) + unwrapped_index = ctx.unwrap_tensors(index) + with ctx.redispatch_to_next(): + functional_branches = [ + ctx.functionalize(_maybe_run_with_interpreter(fn)) for fn in branches + ] + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + for i, branch in enumerate(branches): + _check_alias_and_mutation( + branch, unwrapped_inputs, f"switch_branch{i}", pre_dispatch + ) + switch_return = switch_op( + unwrapped_index, functional_branches, unwrapped_inputs + ) + return ctx.wrap_tensors(switch_return) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/torchbind.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/torchbind.py new file mode 100644 index 0000000000000000000000000000000000000000..bad486b0f025070256954a38204b082825cc6abb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/torchbind.py @@ -0,0 +1,168 @@ +# mypy: allow-untyped-defs +import logging +from contextlib import contextmanager + +import torch +from torch._C import DispatchKey # @manual +from torch._functorch._aot_autograd.utils import KNOWN_TYPES +from torch._higher_order_ops.utils import autograd_not_implemented +from torch._library.fake_class_registry import ( + _is_script_object, + _ns_and_class_name, + FakeScriptObject, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.fx.node import has_side_effect +from torch.utils import _pytree as pytree + + +log = logging.getLogger(__name__) + + +# The call_torchbind operator represents a method invocation on a torchbind +# object. The calling convention is: +# call_torchbind(self: ScriptObject, method_name: str, *method_args, **method_kwargs) +# We do not expect users to write this operator directly. Instead it will be +# emitted by Dynamo when tracing encounters a torchbind object. +class CallTorchBind(HigherOrderOperator): + def __init__(self): + super().__init__("call_torchbind") + + def __call__(self, obj, method, *args, **kwargs): + # pyrefly: ignore [missing-attribute] + return super().__call__(obj, method, *args, **kwargs) + + @staticmethod + def schema(obj, method) -> torch.FunctionSchema: + """ + Returns the schema of ``CallTorchbind.__call__``. + """ + if not isinstance(obj, torch._inductor.ir.TorchBindObject): + raise AssertionError(f"expected obj to be TorchBindObject, got {type(obj)}") + val = obj.get_real_obj() + schema = val._get_method(method).schema + schema_str = str(schema) + new_schema_str = f"call_torchbind({str(schema.arguments[0].real_type)} {schema.arguments[0].name}," + first_comma_index = schema_str.find(",") + if first_comma_index == -1: + # If no comma is found, find the last closing parenthesis + first_comma_index = schema_str.rfind(") ->") + new_schema_str = new_schema_str + " str method" + schema_str[first_comma_index:] + new_schema = torch._C.parse_schema(new_schema_str) + return new_schema + + +call_torchbind = CallTorchBind() + +# Register this operator as side-effectful with FX. +# TODO: this is not really sufficient. While passes (hopefully) check +# Node.is_impure() and make good decisions, we also assume we can execute the +# graph as many times as we want without changing behavior, which is NOT true of +# ops that mutate torchbind object state. +has_side_effect(call_torchbind) + +_orig_scriptmethod_call = torch.ScriptMethod.__call__ + + +def torchbind_method_redispatch(self, *args, **kwargs): + if _is_script_object(self.raw_owner): + return call_torchbind(self.raw_owner, self.name, *args, **kwargs) + return _orig_scriptmethod_call(self, *args, **kwargs) + + +@contextmanager +def enable_torchbind_tracing(): + """Context manager that acts as a feature flag to enable torchbind tracing + behavior. Once torchbind tracing has been stabilized, we can remove this and + turn it always on. + """ + try: + KNOWN_TYPES.append(torch.ScriptObject) + torch.ScriptMethod.__call__ = torchbind_method_redispatch # type: ignore[method-assign] + yield + finally: + if KNOWN_TYPES.pop() is not torch.ScriptObject: + raise AssertionError( + "Someone else messed with KNOWN_TYPES during tracing, exploding." + ) + torch.ScriptMethod.__call__ = _orig_scriptmethod_call # type: ignore[method-assign] + + +@call_torchbind.py_impl(DispatchKey.CompositeExplicitAutograd) +def call_torchbind_impl(obj, method, *args, **kwargs): + if isinstance(obj, torch.ScriptObject): + return _orig_scriptmethod_call(getattr(obj, method), *args, **kwargs) + elif isinstance(obj, FakeScriptObject): + return getattr(obj.wrapped_obj, method)(*args, **kwargs) + else: + raise RuntimeError(f"Unsupported first arg type {type(obj)} for call_torchbind") + + +@call_torchbind.py_impl(ProxyTorchDispatchMode) +def inner(mode, *args, **kwargs): + proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args) + proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) + + out_proxy = mode.tracer.create_proxy( + "call_function", + call_torchbind, + proxy_args, + proxy_kwargs, + ) + out = call_torchbind(*args, **kwargs) + + obj, method, *_rest_args = args + if isinstance(obj, torch.ScriptObject): + ns, class_name = _ns_and_class_name( + obj._type().qualified_name() # type: ignore[attr-defined] + ) + log.warning( + "Tracing torchbind method %s.%s with real ScriptObject. This may" + " cause the original object being mutated. If this is not intended," + ' You can register a fake class with torch._library.register_fake_class("%s::%s").', + class_name, + method, + ns, + class_name, + ) + + ret = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer) + if "val" not in out_proxy.node.meta: + if out is not None and not isinstance(out, (int, float, bool)): + raise AssertionError( + f"Currently, only these constant dtypes are supported to be returned from torchbind methods, got {type(out)}" + ) + out_proxy.node.meta["val"] = out + return ret + + +# When tracing with fake script object, the call_torchbind op will return a fake tensor +# When tracing with real script object, the call_torchbind op may return a real tensor, +# we need to convert it to fake tensor manually. Dynamic shape is supported. +@call_torchbind.py_impl(FakeTensorMode) +def call_torchbind_fake(mode, *args, **kwargs): + with mode: + out = call_torchbind_impl(*args, **kwargs) + return pytree.tree_map_only( + torch.Tensor, + lambda x: mode.from_tensor(x, static_shapes=True) + if not torch._subclasses.fake_tensor.is_fake_tensor(x) + else x, + out, + ) + + +call_torchbind.py_autograd_impl( + autograd_not_implemented(call_torchbind, deferred_error=True) +) + + +@call_torchbind.py_functionalize_impl +def call_torchbind_func(ctx, *args, **kwargs): + from torch._higher_order_ops.effects import handle_effects + + return handle_effects( + ctx.mode._allow_token_discovery, ctx.mode._tokens, call_torchbind, args, kwargs + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/triton_kernel_wrap.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/triton_kernel_wrap.py new file mode 100644 index 0000000000000000000000000000000000000000..4c16850e55427785840b06534f55e8c7860849c1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/triton_kernel_wrap.py @@ -0,0 +1,2676 @@ +import ast +import collections +import copy +import dataclasses +import functools +import inspect +import itertools +import logging +import operator +import threading +import typing +from collections import defaultdict +from collections.abc import Callable, Sequence +from typing import Any, Optional, Protocol, TYPE_CHECKING, Union +from typing_extensions import Never + +import sympy + +import torch.fx as fx +import torch.utils._pytree as pytree +from torch import SymBool, SymFloat, SymInt, Tensor +from torch._C import _dispatch_keys, DispatchKey +from torch._higher_order_ops.utils import redirect_to_mode, register_fake +from torch._ops import HigherOrderOperator +from torch._prims_common import clone_preserve_strides +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) +from torch.fx.experimental.symbolic_shapes import guard_scalar +from torch.types import IntLikeType +from torch.utils._ordered_set import OrderedSet +from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode + + +if TYPE_CHECKING: + from triton._C.libtriton.ir import ( + module as TritonIRModule, + operation as TritonIROperation, + ) + + from torch._dynamo.symbolic_convert import InstructionTranslatorBase + from torch._dynamo.variables.constant import ConstantVariable + from torch._dynamo.variables.functions import TritonKernelVariable + from torch._guards import Source + from torch._inductor.dependencies import ReadWrites + from torch._subclasses.functional_tensor import BaseFunctionalizeAPI + from torch.fx.proxy import Proxy + from torch.utils._triton import has_triton + + TritonMetaParamsType = dict[str, int] + TritonGridTupleType = tuple[int | sympy.Expr | SymInt, ...] + TritonGridCallableType = Callable[[TritonMetaParamsType], tuple[int, ...]] + TritonGridType = TritonGridTupleType | TritonGridCallableType + + if has_triton(): + from triton.runtime.autotuner import Autotuner, Config as TritonConfig + from triton.runtime.jit import JITFunction + else: + + class Autotuner: # type: ignore[no-redef] + pass + + class JITFunction: # type: ignore[no-redef] + pass + + TritonKernelType = Autotuner | JITFunction + # mypy specifically complains that TritonAutotunerType is not a valid type if Autotuner is not inside of a Union. + TritonAutotunerType = Union[Autotuner] # noqa: UP007 + +log = logging.getLogger("torch._dynamo") + +# e.g. for a host-side Triton TMA API call ``create_2d_tma_descriptor(ptr, 50, 60, 32, 15, 4)``, +# the metadata will look like ``("experimental", ([50, 60], [32, 15], 4))`` +TMAExperimentalMetadata = tuple[ + str, # type of TMA (should be "experimental") + tuple[ + list[IntLikeType], # dims + list[IntLikeType], # block_dims + IntLikeType, # element_size + ], +] + +# e.g. for host-side Triton TMA API call ``TensorDescriptor.from_tensor(ptr, [32, 64])`` +# the metadata will look like ``("stable", ([32, 64],))`` +TMAStableMetadata = tuple[ + str, # type of TMA ("experimental" or "stable") + tuple[list[IntLikeType],], # block_shape +] + + +def create_tma_experimental_metadata( + dims: list[IntLikeType], + block_dims: list[IntLikeType], + element_size: IntLikeType, +) -> TMAExperimentalMetadata: + return ("experimental", (dims, block_dims, element_size)) + + +def maybe_unpack_tma_experimental_metadata( + tma_meta: TMAExperimentalMetadata | TMAStableMetadata, +) -> tuple[list[IntLikeType], list[IntLikeType], IntLikeType] | None: + if not tma_meta or len(tma_meta) != 2: + return None + if tma_meta[0] == "experimental": + return tma_meta[1] # type: ignore[return-value] + return None + + +def create_tma_stable_metadata( + block_shape: list[IntLikeType], +) -> TMAStableMetadata: + return ("stable", (block_shape,)) + + +def maybe_unpack_tma_stable_metadata( + tma_meta: TMAExperimentalMetadata | TMAStableMetadata, +) -> tuple[list[IntLikeType]] | None: + if not tma_meta or len(tma_meta) != 2: + return None + if tma_meta[0] == "stable": + return tma_meta[1] # type: ignore[return-value] + return None + + +# TMADescriptorMetadata maps kernel parameter names to the metadata that allows +# reconstructing TMA descriptors from the underlying tensors (passed as kernel +# arguments in the fx graph, instead of the TMA descriptors). +# +# Since there are two TMA APIs (the old "experimental" API and the new "stable" API), +# each entry in the dict is a tuple that starts with a string, either "experimental" +# or "stable". The second entry in the tuple is another tuple, with data that depends +# on the API type (see TMAExperimentalMetadata and TMAStableMetadata above). +# +# These are stored as raw tuples (instead of classes) for ease of serialization. +TMADescriptorMetadata = dict[ + str, # kernel parameter name + TMAExperimentalMetadata | TMAStableMetadata, +] + + +############################################################################### +# Kernel Side Table + + +# We cannot put Triton Kernels into the FX graph as the graph nodes +# do not support arbitrary functions. +# Use a side table. +# We use two dicts so that fetching both the kernel and id are O(1) +class KernelSideTable: + id_to_kernel: dict[int, "TritonKernelType"] = {} + kernel_to_id: dict["TritonKernelType", int] = {} + constant_args: dict[int, dict[str, Any]] = {} + lock = threading.Lock() + + # Returns index on the table + def add_kernel(self, kernel: "TritonKernelType") -> int: + with self.lock: + if kernel in self.kernel_to_id: + return self.kernel_to_id[kernel] + + idx = len(self.id_to_kernel) + self.id_to_kernel[idx] = kernel + self.kernel_to_id[kernel] = idx + return idx + + # Returns the triton kernel at the given index + def get_kernel(self, idx: int) -> "TritonKernelType": + # No need to lock here as fetching from dict is atomic + if idx not in self.id_to_kernel: + raise AssertionError(f"Kernel index {idx} not found in id_to_kernel") + return self.id_to_kernel[idx] + + # Not every constant arg can be added to the graph. Use this side table + # for constant args. + def add_constant_args(self, args: dict[str, Any]) -> int: + with self.lock: + idx = len(self.constant_args) + self.constant_args[idx] = args + return idx + + # Returns the constant args + def get_constant_args(self, idx: int) -> dict[str, Any]: + # No need to lock here as fetching from dict is atomic + if idx not in self.constant_args: + raise AssertionError( + f"Constant args index {idx} not found in constant_args" + ) + return self.constant_args[idx] + + # Resets the table (only meant to be used in unit tests) + # This is only safe assuming single threaded execution + def reset_table(self) -> None: + self.id_to_kernel = {} + self.kernel_to_id = {} + self.constant_args = {} + + +kernel_side_table = KernelSideTable() + + +############################################################################### +# Mutation Tracker + + +@dataclasses.dataclass(frozen=True, slots=True) +class Param: + idx: int + + +@dataclasses.dataclass(frozen=True, slots=True) +class Intermediate: + idx: int + + def fake(self) -> bool: + return self.idx < 0 + + +@dataclasses.dataclass(frozen=True, slots=True) +class Op: + name: str + fn_call_name: str | None + args: list[Param | Intermediate] + ret: Intermediate = dataclasses.field(repr=False) + # used for scf.yield: see [Note: scf.yield fix-up] + sub_idx: int | None = None + # used for tt.elementwise_inline_asm + # `is_pure = True` assumes the asm block has no side-effects + is_pure: bool = False + + def __post_init__(self) -> None: + if self.name == "tt.call": + if self.fn_call_name is None: + raise AssertionError("fn_call_name must not be None for tt.call op") + else: + if self.fn_call_name is not None: + raise AssertionError( + f"fn_call_name must be None for non-tt.call op, got {self.fn_call_name}" + ) + + +def generate_ttir( + kernel: "TritonKernelType", + kwargs: dict[str, Any], + tma_descriptor_metadata: TMADescriptorMetadata, +) -> tuple["TritonIRModule", list[str]]: + """ + Uses Triton's internal code generation to create TTIR + """ + import sympy + import triton + import triton.runtime.jit + from triton.compiler.compiler import ASTSource + from triton.runtime.autotuner import Autotuner + from triton.runtime.jit import JITFunction + + from torch._inductor.utils import ( + get_triton_attrs_descriptor_version, + triton_version_uses_attrs_dict, + TritonAttrsDescriptorVersion, + ) + from torch.utils._triton import has_triton_tensor_descriptor_host_tma + + triton_version = get_triton_attrs_descriptor_version() + + import torch._inductor.ir + from torch._subclasses.fake_tensor import is_fake_tensor + + if isinstance(kernel, Autotuner): + if len(kernel.configs) > 0: + # If we are autotuning, then it doesn't matter which version gets + # picked for tracing purposes, so lets pick the first one + kwargs = {**kwargs, **kernel.configs[0].kwargs} + kernel = kernel.fn + + if not isinstance(kernel, JITFunction): + raise AssertionError(f"Expected kernel to be a JITFunction, got {type(kernel)}") + + context = triton._C.libtriton.ir.context() + target = triton.runtime.driver.active.get_current_target() + backend = triton.compiler.compiler.make_backend(target) + options = backend.parse_options({}) + + # ignore backend-specific kwargs same way as in the native Triton code + # https://github.com/triton-lang/triton/blob/a6bb57d6285e723c58e87dd7cba263db6efff789/python/triton/runtime/jit.py#L594-L596 + # why this is important for user-defined Triton kernels on AMD: https://github.com/pytorch/pytorch/issues/140800 + for name in list(kwargs): + if name not in kernel.arg_names and name in options.__dict__: + kwargs.pop(name) + + if len(kwargs) != len(kernel.arg_names): + raise ValueError( + "Incorrect number of arguments passed to kernel: " + f"passed {list(kwargs.keys())}, expected {kernel.arg_names}." + ) + + # Replace all SymExprs with a regular value for TTIR generation + # Replace all FakeTensor/TensorBox with real tensors + # These replacements are needed for triton's type, key and config functions + ordered_args: dict[str, Any] = {} + for name in kernel.arg_names: + a = kwargs[name] + if isinstance(a, (torch.SymInt, torch.SymFloat, torch.SymBool, sympy.Expr)): + ordered_args[name] = 2 + elif ( + stable_meta := maybe_unpack_tma_stable_metadata( + # pyrefly: ignore [bad-argument-type] + tma_descriptor_metadata.get(name, None) + ) + ) is not None: + from triton.tools.tensor_descriptor import TensorDescriptor + + block_shape = stable_meta[0] + with torch._C._DisableTorchDispatch(): + # need 16-byte aligned strides + elements_per_dim = max(1, 16 // a.dtype.itemsize) + base_tensor = torch.empty( + [elements_per_dim] * len(block_shape), dtype=a.dtype + ) + + ordered_args[name] = TensorDescriptor.from_tensor(base_tensor, block_shape) + elif is_fake_tensor(a) or isinstance(a, torch._inductor.ir.TensorBox): + with torch._C._DisableTorchDispatch(): + ordered_args[name] = torch.empty(2, dtype=a.dtype) + else: + ordered_args[name] = a + + def is_stable_tensor_descriptor_arg(arg: Any) -> bool: + if has_triton_tensor_descriptor_host_tma(): + from triton.tools.tensor_descriptor import TensorDescriptor + + if isinstance(arg, TensorDescriptor): + return True + return False + + def _is_constexpr_or_none(name: str, arg: Any) -> bool: + param_idx = kernel.arg_names.index(name) + return kernel.params[param_idx].is_constexpr or arg is None + + # Note: one would expect that each input to the triton kernel maps to + # one input parameter in the TTIR. This is _not_ true for TMA descriptors: + # one TMA descriptor gets converted into: + # * one TMA descriptor input + # * N strides, for a rank-N tensor + # * N sizes, for a rank-N tensor + # To account for this, we inject some fake arg names as placeholders for + # the stride and size parameters. + # + # Additionally, tensors and scalars are both included as TTIR parameters, + # whereas `constexpr` are inlined, and None are excluded. We both preserve + # scalars and tensors as this matters for "odd" ordering, + # eg. [tensor, scalar, tensor]. + def get_arg_names(name: str, arg: Any) -> list[str]: + if _is_constexpr_or_none(name, arg): + return [] + + if is_stable_tensor_descriptor_arg(arg): + stable_meta = maybe_unpack_tma_stable_metadata( + tma_descriptor_metadata[name] + ) + if stable_meta is None: + raise AssertionError(f"Failed to unpack stable TMA metadata for {name}") + block_shape = stable_meta[0] + tensor_rank = len(block_shape) + names = [name] + names.extend(name + f" STRIDE PLACEHOLDER {i}" for i in range(tensor_rank)) + names.extend(name + f" SIZE PLACEHOLDER {i}" for i in range(tensor_rank)) + return names + + return [name] + + ordered_arg_names = list( + itertools.chain.from_iterable( + get_arg_names(name, arg) for name, arg in ordered_args.items() + ) + ) + + def _get_specialization(args): # type: ignore[no-untyped-def] + # Support multiple triton versions. + # This code basically copies JITFunction.run() logic to get the attrs to construct an ASTSource. + if triton_version == TritonAttrsDescriptorVersion.V1_COMPILER: + return kernel._get_config(*args) + elif triton_version in { + TritonAttrsDescriptorVersion.V2_BACKENDS, + TritonAttrsDescriptorVersion.V3_BACKENDS_TUPLE, + }: + from triton.backends.compiler import AttrsDescriptor # noqa: F401 + + target = triton.runtime.driver.active.get_current_target() + backend_ = triton.compiler.compiler.make_backend(target) + + return backend_.get_attrs_descriptor(args, kernel.params) + else: + if ( + get_triton_attrs_descriptor_version() + != TritonAttrsDescriptorVersion.V4_DICT + ): + raise AssertionError( + f"Expected Triton attrs descriptor version V4_DICT, " + f"got {get_triton_attrs_descriptor_version()}" + ) + # specialize_impl switched to create_specialize_impl in https://github.com/triton-lang/triton/pull/6099 + if hasattr(triton.runtime.jit, "create_specialize_impl"): + try: + # Latest versions of Triton take specialize_extra as an arg to create_specialize_impl + specialize_impl = triton.runtime.jit.create_specialize_impl( + specialize_extra=backend.get_arg_specialization + ) + except TypeError: # Unknown arg `specialize_extra` + # Older versions of Triton take specialize_extra as an arg to specialize_impl + specialize_impl = functools.partial( + triton.runtime.jit.create_specialize_impl(), + specialize_extra=backend.get_arg_specialization, + ) + # create_specialize_impl is removed in https://github.com/triton-lang/triton/pull/7771 + # switch to native_specialize_impl instead + elif hasattr(triton.runtime.jit, "native_specialize_impl"): + from triton.backends import BaseBackend + from triton.runtime.jit import native_specialize_impl + + def _native_specialize_impl( + arg: Any, + is_const: bool = False, + specialize_value: bool = True, + align: bool = True, + ) -> Callable: + return native_specialize_impl( + BaseBackend, arg, is_const, specialize_value, align + ) + + specialize_impl = _native_specialize_impl + else: + from triton.runtime.jit import specialize_impl as specialize_impl_orig + + specialize_impl = functools.partial( + specialize_impl_orig, + specialize_extra=backend.get_arg_specialization, + ) + + from triton._utils import find_paths_if, get_iterable_path + + # logic is copied from: binder = create_function_from_signature(self.signature, self.params, backend) + attrvals = [] + for arg, kp in zip(args, kernel.params): + if kp.is_constexpr: + attrvals.append(arg) + else: + spec = specialize_impl( + arg, + is_const=kp.is_const, + specialize_value=not kp.do_not_specialize, + align=not kp.do_not_specialize_on_alignment, + ) + # pyrefly: ignore [unsupported-operation] + attrvals.append(spec[1]) + + attrs = find_paths_if(attrvals, lambda _, x: isinstance(x, str)) + attrs = { + k: backend.parse_attr(get_iterable_path(attrvals, k)) for k in attrs + } + return attrs + + specialization = _get_specialization(ordered_args.values()) + # Triton explicitly interprets ASTSource.constants entries as constexpr + # Thus, only None and arguments marked `is_constexpr` should be treated as such. + constants = { + name: arg + for name, arg in ordered_args.items() + if _is_constexpr_or_none(name, arg) + } + + if (mangle_type := getattr(triton.runtime.jit, "mangle_type", None)) is not None: + + def get_signature_value(idx: int, arg: Any) -> str: + if kernel.params[idx].is_constexpr: + return "constexpr" + # pyrefly: ignore [not-callable] + result = mangle_type(arg) + # Workaround for Triton i1/u1 AOTI bug: PyTorch stores bool + # tensors as uint8 (1 byte per element), but *i1/*u1 causes + # the compiled kernel to generate bit-packed loads. Use *u8 + # so loads correctly read 1 byte per element. + if result in ("*i1", "*u1"): + result = "*u8" + return result + + else: + + def get_signature_value(idx: int, arg: Any) -> str: + return kernel._type_of(kernel.key_of(arg)) + + if triton_version_uses_attrs_dict(): + # In newer versions of Triton, the signature includes constexpr args + signature = { + name: get_signature_value(i, arg) + for i, (name, arg) in enumerate(ordered_args.items()) + } + else: + # In older versions of Triton, the signature does not include constexpr args + constexprs = [p.num for p in kernel.params if p.is_constexpr] + signature = { + name: get_signature_value(i, arg) + for i, (name, arg) in enumerate(ordered_args.items()) + if i not in constexprs + } + + triton._C.libtriton.ir.load_dialects(context) + backend.load_dialects(context) + + src = ASTSource(kernel, signature, constants, specialization) + + # Triton changes ASTSource.make_ir to take 3/4 arguments. Handle + # backward compatibility here. + make_ir_sig_params = len(inspect.signature(src.make_ir).parameters) + get_codegen_implementation_sig_params = len( + inspect.signature(backend.get_codegen_implementation).parameters + ) + if make_ir_sig_params == 2: + ttir_module = src.make_ir(options, context) + elif make_ir_sig_params == 3: + codegen_fns = backend.get_codegen_implementation() + + ttir_module = src.make_ir(options, codegen_fns, context) + elif make_ir_sig_params == 4: + codegen_args = [options] if get_codegen_implementation_sig_params == 1 else [] + + codegen_fns = backend.get_codegen_implementation(*codegen_args) + module_map = backend.get_module_map() + + ttir_module = src.make_ir(options, codegen_fns, module_map, context) + else: + codegen_args = [options] if get_codegen_implementation_sig_params == 1 else [] + + codegen_fns = backend.get_codegen_implementation(*codegen_args) + module_map = backend.get_module_map() + + ttir_module = src.make_ir(target, options, codegen_fns, module_map, context) + if not ttir_module.verify(): + raise RuntimeError("Verification for TTIR module has failed") + + return ttir_module, ordered_arg_names + + +def ttir_to_functions( + ttir_module: "TritonIRModule", +) -> dict[str, dict[Intermediate, list[Op]]]: + """ + Walk the `ttir_module` bottom up to mine the `functions` from + the structured MLIR entities representing the Triton kernel + (mlir::Operation, mlir::Block, mlir::Region). + """ + functions: dict[str, dict[Intermediate, list[Op]]] = {} + + # block id --> op result (Intermediate) --> one or more ops + op_stack: dict[int, dict[Intermediate, list[Op]]] = defaultdict( + lambda: defaultdict(list) + ) + region_id_to_block_ids: dict[int, list[int]] = defaultdict(list) + block_id_to_block_arg_ids: dict[int, list[int]] = {} + replacements: dict[int, Intermediate | Param] = {} + reindex_map: dict[int, int] = {} + next_fake_intermediate = 0 + + def reindex(idx: int) -> int: + if idx not in reindex_map: + reindex_map[idx] = len(reindex_map) + return reindex_map[idx] + + def mlir_to_functions(op: "TritonIROperation") -> None: + name: str = op.get_name() + if name == "builtin.module": + # this wraps all tt.func ops + return + + operand_ids: list[int] = [ + reindex(op.get_operand(i).id()) for i in range(op.get_num_operands()) + ] + result_ids: list[int] = [ + reindex(op.get_result(i).id()) for i in range(op.get_num_results()) + ] + + child_block_ids: list[int] = [] + for i in [op.get_region(i).id() for i in range(op.get_num_regions())]: + # as the walk is bottom-up, the region_id_to_block_ids[i] + # must be populated by the time we process the enclosing op + child_block_ids.extend(region_id_to_block_ids[i]) + + parent_block_id = -1 + parent_block = op.get_block() + if parent_block is not None: + parent_block_id = parent_block.id() + if parent_block_id not in block_id_to_block_arg_ids: + block_id_to_block_arg_ids[parent_block_id] = [] + for i in range(parent_block.get_num_arguments()): + block_id_to_block_arg_ids[parent_block_id].append( + reindex(parent_block.get_argument(i).id()), + ) + # the region info is collected via ops' parent blocks to be + # used later when the region's enclosing op is traversed + parent_region = parent_block.get_parent() + if parent_region is not None: + region_id_to_block_ids[parent_region.id()].append(parent_block_id) + + nonlocal next_fake_intermediate + + if name == "tt.func": + # for function ops: gather and inline + # the ops from all child blocks + fn_ops = defaultdict(list) + for child_block_id in child_block_ids: + for result, block_fn_ops in op_stack.pop(child_block_id).items(): + for block_fn_op in block_fn_ops: + fn_ops[result].append(block_fn_op) + + # replace the corresponding Intermediates in the + # child op args with the function args (Params) + for i, idx in enumerate(block_id_to_block_arg_ids[child_block_ids[0]]): + replacements[idx] = Param(i) + + for fn_op_list in fn_ops.values(): + for fn_op in fn_op_list: + for i in range(len(fn_op.args)): + arg = fn_op.args[i] + seen = set() # to break cycles + # there can be transitive replacements, but likely + # no cycles (we keep the `seen` set just in case) + while ( + isinstance(arg, Intermediate) + and arg.idx in replacements + and arg.idx not in seen + ): + seen.add(arg.idx) + arg = fn_op.args[i] = replacements[arg.idx] + + # next function capture starts + # with empty replacements + replacements.clear() + + fn_name = op.get_str_attr("sym_name") + functions[fn_name] = fn_ops + elif child_block_ids: + if name in {"scf.if", "scf.for", "scf.while", "tt.reduce", "tt.scan"}: + # for blocked ops: inline the enclosed ops into + # the parent block + rewire the last op in each + # child block to return the block result + return_ops = [] + for block_id in child_block_ids: + if name == "scf.for": + # example: + # %result = scf.for %iv = %lb to %ub step %step iter_args(%arg = %init) -> (i32) ... + # block args: 2 (%iv, %arg) + # op operands: 4 (%lb, %ub, %step, %init) + # `%arg` is mapping to `%init` + for i, idx in enumerate(block_id_to_block_arg_ids[block_id]): + if i == 0: + next_fake_intermediate -= 1 + replacements[idx] = Intermediate(next_fake_intermediate) + else: + replacements[idx] = Intermediate(operand_ids[i + 2]) + elif name == "scf.while": + # example: + # %3:3 = scf.while (%arg2 = %1, %arg3 = %2, %arg4 = %c0_i32_8) ... + # block args: 3 (%arg2, %arg3, %arg4) + # op operands: 3 (%1, %2, %c0_i32_8) + # `%arg2` is mapping to `%1`, `%arg3` is mapping to `%2`, ... + for i, idx in enumerate(block_id_to_block_arg_ids[block_id]): + replacements[idx] = Intermediate(operand_ids[i]) + elif name == "scf.if": + # the scf block args are ignored by the pass. but, as they + # may be used as operands of the ops inside the block + # (and nested blocks inlined in the current block by now), + # they are replaced by new fake Intermediates to avoid "this + # operand is not returned by any other op in the fn" error + # in the downstream analysis + for idx in block_id_to_block_arg_ids[block_id]: + next_fake_intermediate -= 1 + replacements[idx] = Intermediate(next_fake_intermediate) + else: + if name not in ("tt.reduce", "tt.scan"): + raise AssertionError( + f"Expected op name to be 'tt.reduce' or 'tt.scan', got {name}" + ) + # wire the block arguments to the op arguments + num_operands = len(operand_ids) + block_arg_ids = block_id_to_block_arg_ids[block_id] + if len(block_arg_ids) != 2 * num_operands: + raise AssertionError( + f"{name} is expected to have twice as " + "many block arguments as op arguments: " + f"{operand_ids=}, {block_arg_ids=}." + ) + for i, idx in enumerate(block_arg_ids): + # for a tt.reduce/tt.scan op with N arguments, the block + # arguments comprise N reduced values followed by + # N current values corresponding to the N op args + replacements[idx] = Intermediate( + operand_ids[i % num_operands] + ) + + if block_id in op_stack: + block_ops = op_stack.pop(block_id) + if not block_ops: + continue + last_ret, last_ops = block_ops.popitem() + if all( + op.name + in ("scf.yield", "tt.reduce.return", "tt.scan.return") + for op in last_ops + ): + # if last_ops are all return ops, treat them separately + return_ops.extend(last_ops) + else: + # otherwise, return last_ops to the block + block_ops[last_ret] = last_ops + for op_result, child_ops in block_ops.items(): + op_stack[parent_block_id][op_result].extend(child_ops) + + scf_results = [Intermediate(idx) for idx in result_ids] + + if return_ops and all( + (op.name == "scf.yield" and len(result_ids) == len(op.args)) + for op in return_ops + ): + # [Note: scf.yield fix-up] + # + # TL;DR: if our scf.yield takes N args, then we'll create N scf.yield ops to handle each of the + # args. + # + # **Context**: + # During mutation analysis, the analysis pass will identify mutating ops (e.g. tt.store) + # and then DFS upwards towards the parameters of the function. Specifically, the analysis pass + # looks at the mutated arg in tt.store; then looks for its source ops; and then recurses on the + # arguments to each of the source ops. + # + # In the case of scf.if/scf.for, we may have multiple return ops, each passed as an arg + # to scf.yield: + # + # %18:2 = scf.if %... -> (!tt.ptr, !tt.ptr) { + # ... + # scf.yield %1, %2 + # } else { + # scf.yield %3, %4 + # } + # + # And for each of the returns of the scf.if, we'd naively assign the source op of each of the + # return values to be the scf.yields. But the scf.yields take _all_ the returns as arguments. + # Therefore, if _any_ of the return values of the scf.if are mutated, then the analysis pass + # would mark _all_ of the yield args as mutated. + # + # **Solution**: + # For the purposes of this analysis pass, we create N yield ops - one for each + # return-val/yield-arg. In the example above, we'll have two scf.yield's for each branch of the + # scf.if. + + for return_op in return_ops: + for i, (scf_result, yield_arg) in enumerate( + zip(scf_results, return_op.args) + ): + sub_yield_op = Op( + return_op.name, + return_op.fn_call_name, + [yield_arg], + return_op.ret, + sub_idx=i, + ) + op_stack[parent_block_id][scf_result].append(sub_yield_op) + + else: + for scf_result in scf_results: + for return_op in return_ops: + op_stack[parent_block_id][scf_result].append(return_op) + else: + raise RuntimeError( + f"Unknown blocked function: {name}. Can't capture the TTIR." + ) + else: + callee = None + if name == "tt.call": + callee = op.get_flat_symbol_ref_attr("callee") + args: list[Param | Intermediate] = [ + Intermediate(operand) for operand in operand_ids + ] + block_ops = op_stack[parent_block_id] + + is_pure = False + # Handle the case for tt.elementwise_inline_asm to set `is_pure` for mutation analysis + if name == "tt.elementwise_inline_asm": + is_pure = op.get_bool_attr("pure") + + if result_ids: + for result_id in result_ids: + res = Intermediate(result_id) + block_ops[res].append(Op(name, callee, args, res, is_pure=is_pure)) + else: + next_fake_intermediate -= 1 + fake_res = Intermediate(next_fake_intermediate) + block_ops[fake_res].append( + Op(name, callee, args, fake_res, is_pure=is_pure) + ) + + ttir_module.walk(mlir_to_functions) + + return functions + + +class MemoizeWithCycleCheck: + fn: Callable[..., Any] + cache: dict[tuple[Any], Any] + + def __init__(self, fn: Callable[..., Any]) -> None: + self.fn = fn + self.reset() + + def __call__( + self, + functions: dict[str, dict[Intermediate, list[Op]]], + fn_name: str, + *args: Any, + ) -> Any: + key: tuple[Any, ...] = (fn_name, *args) + if key not in self.cache: + self.cache[key] = None + self.cache[key] = self.fn(functions, fn_name, *args) + if self.cache[key] is None: + raise RuntimeError("Recursion is not supported") + return self.cache[key] + + def reset(self) -> None: + self.cache = {} + + +@MemoizeWithCycleCheck +def get_tma_stores( + functions: dict[str, dict[Intermediate, list[Op]]], fn_name: str +) -> set[Intermediate | Param]: + """ + Identifies all intermediates and parameters that are written to by a + `tt.experimental_descriptor_store`. It tracks only the specific values + written to via experimental_descriptor_store and the input values to + `tt.reinterpret_tensor_descriptor` used to construct the direct inputs + to tt.experimental_descriptor_store - not any recursive values + used to construct those values. + + For example: for + tt.reinterpret_tensor_descriptor(Intermediate(idx=0), ...) + Intermediate(idx=1) = tt.experimental_descriptor_store(Intermediate(idx=0), ...) + this function will return [Intermediate(idx=0), Intermediate(idx=1)], + + However + Intermediate(idx=4) = arith.addptr(Intermediate(idx=2), Intermediate(idx=3)) + Intermediate(idx=5) = tt.experimental_descriptor_store(Intermediate(idx=4), ...) + tt.experimental_descriptor_store(Intermediate(idx=5), ...) + this function will mark only idx=4 and idx=5 (but not idx=2 or idx=3) + + If an intermediate/parameter is passed into a function and is written to + via experimental_descriptor_store within that function, the argument to the + function will also be marked. + """ + + result: set[Intermediate | Param] = set() + + ops = functions[fn_name] + for op_list in ops.values(): + for op in op_list: + if op.name == "tt.call": + if op.fn_call_name not in functions: + raise AssertionError( + f"Function {op.fn_call_name} not found in functions for TMA stores" + ) + # pyrefly: ignore [bad-argument-type] + tma_stores = get_tma_stores(functions, op.fn_call_name) + for i, inp in enumerate(op.args): + if Param(idx=i) in tma_stores: + result.add(inp) + else: + op_info = _KERNEL_ACCESS_OPS.get(op.name) + if ( + op_info is not None + and op_info.is_tma_store + and op_info.write_indexes is not None + ): + result.update(op.args[idx] for idx in op_info.write_indexes(op)) + + for val in list(result): + if val in ops: + if not isinstance(val, Intermediate): + continue + for op in ops[val]: + if op.name == "tt.reinterpret_tensor_descriptor": + if len(op.args) < 1: + raise AssertionError( + "tt.reinterpret_tensor_descriptor expected at least 1 arg, " + f"got {len(op.args)}" + ) + result.add(op.args[0]) + + return result + + +@dataclasses.dataclass +class TensorAccesses: + read_writes: "ReadWrites" + can_fuse_epilogue: bool + + +class IgnoreUnknownOp(Protocol): + """Returns True if the op should be skipped; otherwise the caller raises.""" + + def __call__(self, op: Op) -> bool: ... + + +class ReadWriteIndexes(Protocol): + """Return the argument indexes read / written.""" + + def __call__(self, op: Op) -> Sequence[int]: ... + + +def first_arg(op: Op) -> list[int]: + """Return the first argument index after checking that it exists.""" + if len(op.args) < 1: + raise AssertionError(f"{op.name} expected at least 1 arg, got {len(op.args)}") + return [0] + + +@dataclasses.dataclass(frozen=True) +class _KernelAccessOpInfo: + read_indexes: ReadWriteIndexes | None = None + write_indexes: ReadWriteIndexes | None = None + is_tma_store: bool = False + ignore_if: IgnoreUnknownOp | None = None + + +# List from Triton Github include/triton/Dialect/Triton/IR/TritonOps.td. +# What if Triton exposed this? +_KERNEL_ACCESS_OPS: dict[str, _KernelAccessOpInfo] = { + "tt.experimental_descriptor_store": _KernelAccessOpInfo( + write_indexes=first_arg, is_tma_store=True + ), + "tt.descriptor_store": _KernelAccessOpInfo( + write_indexes=first_arg, is_tma_store=True + ), + "tt.store": _KernelAccessOpInfo(write_indexes=first_arg), + "tt.atomic_cas": _KernelAccessOpInfo(write_indexes=first_arg), + "tt.atomic_rmw": _KernelAccessOpInfo( + read_indexes=first_arg, write_indexes=first_arg + ), + "tt.experimental_tensormap_create": _KernelAccessOpInfo(write_indexes=first_arg), + "tt.load": _KernelAccessOpInfo(read_indexes=first_arg), + "tt.load_tensor_descriptor": _KernelAccessOpInfo(read_indexes=first_arg), + "tt.descriptor_load": _KernelAccessOpInfo(read_indexes=first_arg), + "tt.elementwise_inline_asm": _KernelAccessOpInfo(ignore_if=lambda op: op.is_pure), +} + + +def _read_write_indexes(indexes: Sequence[int] | ReadWriteIndexes) -> ReadWriteIndexes: + if callable(indexes): + return indexes + index_tuple = tuple(indexes) + return lambda op: index_tuple + + +def register_kernel_access_op( + name: str, + *, + read_indexes: Sequence[int] | ReadWriteIndexes | None = None, + write_indexes: Sequence[int] | ReadWriteIndexes | None = None, + is_tma_store: bool = False, + ignore_if: IgnoreUnknownOp | None = None, +) -> None: + """Register a Triton op for kernel read/write analysis.""" + if is_tma_store and write_indexes is None: + raise AssertionError( + f"{name} is marked as a TMA store but has no write indexes" + ) + has_indexes = read_indexes is not None or write_indexes is not None + if ignore_if is not None and has_indexes: + raise AssertionError( + f"{name}: ignore_if cannot be combined with read/write indexes" + ) + _KERNEL_ACCESS_OPS[name] = _KernelAccessOpInfo( + read_indexes=( + None if read_indexes is None else _read_write_indexes(read_indexes) + ), + write_indexes=( + None if write_indexes is None else _read_write_indexes(write_indexes) + ), + is_tma_store=is_tma_store, + ignore_if=ignore_if, + ) + + +def unregister_kernel_access_op(name: str) -> None: + """ + Unregister a Triton op from kernel read/write analysis. + + This is mainly useful for tests and temporary backend registrations. It + does not reset memoized analysis, so direct analyze_kernel_access callers + must reset their own caches. + """ + _KERNEL_ACCESS_OPS.pop(name, None) + + +@MemoizeWithCycleCheck +def analyze_kernel_access( + functions: dict[str, dict[Intermediate, list[Op]]], + fn_name: str, + num_args: int, + tensor_names: tuple[str, ...], + tensor_arg_indices: frozenset[int] | None, +) -> TensorAccesses: + """ + Analyzes the graph to detect which arguments are written to and which are read. + + For writes: traverses from write sinks (tt.store, tt.atomic_cas, etc.) backwards + to identify input pointers that are written to. + + For reads: traverses from read operations (tt.load) backwards to identify + input pointers that are read from. + + Returns ReadWrites with StarDep objects for each accessed tensor. + """ + from torch._inductor.dependencies import Dep, ReadWrites, StarDep + + write_stack: list[Param | Intermediate] = [] + read_stack: list[Param | Intermediate] = [] + + ops = functions[fn_name] + tma_stores = get_tma_stores(functions, fn_name) + + for op_list in ops.values(): + for op in op_list: + # If we encounter an operation with effects that cannot be reliably analyzed + # (e.g. `tt.elementwise_inline_asm`), we assume it does not mutate any input parameters. + op_info = _KERNEL_ACCESS_OPS.get(op.name) + if op_info is not None and op_info.ignore_if is not None: + if op_info.ignore_if(op): + continue + raise RuntimeError( + f"ttir analysis hit an op we do not know how to analyze: {op.name}" + ) + + if op.name == "tt.experimental_tensormap_create": + # Note: this is how we implement experimental_descriptor_store mutation analysis. + # for on-device TMA. + # experimental_tensormap_store(a, b, ...) stores b to the location specified + # by descriptor in the memory of a. + # To track this, we first find all the intermediates/params to which we store via + # experimental_tensormap_store (get_tma_stores, called above). Then, during this + # analysis we wait to find the corresponding experimental_tensormap_create (if it + # exists), at which point we will mark the global_ptr as mutated (as done below). + if len(op.args) < 2: + raise AssertionError( + f"tt.experimental_tensormap_create expected at least 2 args, " + f"got {len(op.args)}" + ) + if op.args[0] in tma_stores: + write_stack.append(op.args[1]) + + if op.name == "tt.call": + if op.fn_call_name not in functions: + raise AssertionError( + f"Function {op.fn_call_name} not found in functions dict" + ) + # Create placeholder names for nested function arguments + nested_names = tuple(f"_arg{i}" for i in range(len(op.args))) + + # Do not pass tensor_arg_indices, most outer call of + # analyze_kernel_access will filter Param nodes. + accesses = analyze_kernel_access( + functions, + # pyrefly: ignore [bad-argument-type] + op.fn_call_name, + len(op.args), + nested_names, + None, + ) + # Map back from StarDep names to args + written_set = {dep.name for dep in accesses.read_writes.writes} + read_set = {dep.name for dep in accesses.read_writes.reads} + for arg, name in zip(op.args, nested_names): + if name in written_set: + write_stack.append(arg) + if name in read_set: + read_stack.append(arg) + else: + if op_info is not None and op_info.write_indexes is not None: + write_stack.extend( + op.args[idx] for idx in op_info.write_indexes(op) + ) + if op_info is not None and op_info.read_indexes is not None: + read_stack.extend(op.args[idx] for idx in op_info.read_indexes(op)) + + # For these ops, only the first argument (base pointer) refers to actual + # memory. The remaining arguments are shape/stride/offset metadata and + # should not be traced during mutation analysis. + POINTER_ONLY_OPS = { + "tt.make_tensor_ptr", + "tt.advance", + "tt.make_tensor_descriptor", + } + + def _find_arg_access_count( + initial_stack: list[Param | Intermediate], + skip_loads: bool, + ) -> dict[int, int]: + """DFS traversal to find argument indices that are accessed (and how many times they are accessed).""" + access_count = dict() + stack = initial_stack[:] + + while stack: + arg = stack.pop() + + if isinstance(arg, Param): + if arg.idx >= num_args: + continue + if tensor_arg_indices is not None and arg.idx not in tensor_arg_indices: + continue + if arg.idx not in access_count: + access_count[arg.idx] = 1 + else: + access_count[arg.idx] += 1 + elif isinstance(arg, Intermediate) and not arg.fake(): + for op in ops[arg]: + if skip_loads and op.name == "tt.load": + continue + if op.name in POINTER_ONLY_OPS: + stack.append(op.args[0]) + else: + stack.extend(op.args) + + return access_count + + write_count = _find_arg_access_count(write_stack, skip_loads=True) + read_count = _find_arg_access_count(read_stack, skip_loads=False) + + writes: OrderedSet[Dep] = OrderedSet( + StarDep(tensor_names[i]) for i in sorted(write_count.keys()) + ) + reads: OrderedSet[Dep] = OrderedSet( + StarDep(tensor_names[i]) for i in sorted(read_count.keys()) + ) + + read_writes = ReadWrites( + reads=reads, + writes=writes, + index_exprs=OrderedSet(), + ) + + def _decide_can_fuse_epilogue(): + # only do epilogue fusion if the kernel has a single output tensor + if len(write_count) != 1: + return False + + written_arg_index = next(iter(write_count)) + # only do epilogue fusion if the written tensor is written exactly once + if write_count[written_arg_index] != 1: + return False + + written_arg_name = next(iter(writes)).name + # cannot fuse if the kernel also reads from the output buffer + if any(read_dep.name == written_arg_name for read_dep in reads): + return False + + return True + + can_fuse_epilogue = _decide_can_fuse_epilogue() + + return TensorAccesses(read_writes=read_writes, can_fuse_epilogue=can_fuse_epilogue) + + +def identify_accessed_tensors( + kernel: "TritonKernelType", + kwargs: dict[str, Any], + tma_descriptor_metadata: TMADescriptorMetadata, +) -> TensorAccesses: + """ + Given a triton kernel and the arguments for this kernel, this function + 1) Retrieves the TTIR converted version of the kernel from Triton's API. + 2) Parses the TTIR and creates a control flow graph + 3) Analyzes the graph to detect which input tensors are read and/or written + """ + + from torch._inductor.dependencies import Dep, ReadWrites, StarDep + from torch._inductor.ir import TensorBox + + ttir_module = None + functions = None + try: + ttir_module, ordered_arg_names = generate_ttir( + kernel, kwargs, tma_descriptor_metadata + ) + + # extract functions from TTIR using MLIR bindings exposed by Triton code + functions = ttir_to_functions(ttir_module) + + if functions is None: + raise AssertionError("ttir_to_functions returned None") + kernel_name = next(iter(functions.keys())) + # Triton codegen modifies the name + # pyrefly: ignore [missing-attribute] + kernel_fn_name = kernel.fn.__name__ + if kernel_fn_name not in kernel_name: + raise AssertionError( + f"Kernel name {kernel_fn_name} not found in TTIR kernel name {kernel_name}" + ) + # Reset the cache between top level invocations + # The cache for analyze kernel access is mainly used for cycle + # detection, so each top level invocation needs a clean cache + analyze_kernel_access.reset() + get_tma_stores.reset() + + # Build frozenset of indices corresponding to tensor args only. + # Used to filter out scalars which are transitively captured as mutated + # during traversal. + tensor_arg_indices = frozenset( + i + for i, name in enumerate(ordered_arg_names) + if isinstance(kwargs.get(name), (Tensor, TensorBox)) + ) + + return analyze_kernel_access( + functions, + kernel_name, + len(ordered_arg_names), + tuple(ordered_arg_names), + tensor_arg_indices, + ) + except Exception: + log.warning( + "Encountered an exception in identify_accessed_tensors, assuming every input is mutated", + exc_info=True, + ) + if ttir_module is not None: + log.debug("TTIR:\n%s", ttir_module) + if functions is not None: + log.debug("functions:") + for name, fn in functions.items(): + log.debug("===\t%s\t===", name) + for ret, ops in fn.items(): + log.debug("%s\t=>\t%s", ret, ops) + + all_tensor_names = [ + key + for key, value in kwargs.items() + if isinstance(value, (Tensor, TensorBox)) + ] + all_deps = OrderedSet(StarDep(name) for name in all_tensor_names) + all_deps = typing.cast(OrderedSet[Dep], all_deps) + return TensorAccesses( + ReadWrites( + reads=all_deps, + writes=all_deps, + index_exprs=OrderedSet(), + ), + can_fuse_epilogue=False, + ) + + +@dataclasses.dataclass +class TritonStore: + store_node: ast.Call + store_pointer_node: ast.Expr + store_value_node: ast.Expr + + +@dataclasses.dataclass +class TritonStores: + stores: list[TritonStore] + + +@functools.cache +def identify_triton_stores(source_code: str) -> TritonStores: + """ + Parse Python source code of triton kernel and find all tl.store calls. + Returns a TritonStores object containing information about pointer, value, and mask. + + tl.store signature: store(pointer, value, mask=None, boundary_check=(), ...) + """ + return identify_triton_stores_from_ast(ast.parse(source_code)) + + +def identify_triton_stores_from_ast(tree: ast.Module) -> TritonStores: + stores = [] + + def _extract_arg(node, arg_name, positional_index): + """ + Extract an argument from a Call node, checking both positional and keyword args. + Returns the AST node for the argument, or None if not found. + """ + # Check positional args first + if len(node.args) > positional_index: + return node.args[positional_index] + + # Check keyword args + for keyword in node.keywords: + if keyword.arg == arg_name: + return keyword.value + + return None + + for node in ast.walk(tree): + if isinstance(node, ast.Call): + # Check if this is a tl.store call + if ( + isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) + and node.func.value.id == "tl" + and node.func.attr == "store" + ): + # Extract required arguments + pointer_node = _extract_arg(node, "pointer", 0) + value_node = _extract_arg(node, "value", 1) + + if pointer_node is None or value_node is None: + continue + + stores.append(TritonStore(node, pointer_node, value_node)) + + return TritonStores(stores=stores) + + +############################################################################### +# Triton Kernel Wrappers + + +class _TritonKernelWrapper(HigherOrderOperator): + def _get_overloaded_args( + self, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> tuple[Tensor, ...]: + overloaded_args = list(super()._get_overloaded_args(args, kwargs)) + triton_kwargs = kwargs.get("kwargs") + if isinstance(triton_kwargs, dict): + overloaded_args.extend( + arg + for arg in triton_kwargs.values() + if isinstance(arg, Tensor) and _dispatch_keys(arg).has("Python") + ) + return tuple(overloaded_args) + + +# Used for wrapping a Triton Kernel +class TritonKernelWrapperMutation(_TritonKernelWrapper): + def __init__(self) -> None: + super().__init__("triton_kernel_wrapper_mutation", cacheable=True) + + def __call__( + self, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, + ) -> Any: + hop_kwargs: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": kwargs, + } + if launch_kwargs: + hop_kwargs["launch_kwargs"] = launch_kwargs + + # pyrefly: ignore [missing-attribute] + return super().__call__(**hop_kwargs) + + +triton_kernel_wrapper_mutation = TritonKernelWrapperMutation() + + +# Used for wrapping a Triton Kernel in a functional manner +class TritonKernelWrapperFunctional(_TritonKernelWrapper): + def __init__(self) -> None: + super().__init__("triton_kernel_wrapper_functional", cacheable=True) + + def __call__( + self, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + tensors_to_clone: list[str], + launch_kwargs: tuple[str, ...] | None = None, + ) -> dict[str, Any]: + hop_kwargs: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": kwargs, + "tensors_to_clone": tensors_to_clone, + } + if launch_kwargs: + hop_kwargs["launch_kwargs"] = launch_kwargs + + # pyrefly: ignore [missing-attribute] + return super().__call__(**hop_kwargs) + + +triton_kernel_wrapper_functional = TritonKernelWrapperFunctional() + + +def get_kernel(kernel_idx: int) -> "TritonKernelType": + return kernel_side_table.get_kernel(kernel_idx) + + +@triton_kernel_wrapper_mutation.py_impl(DispatchKey.CompositeExplicitAutograd) +def triton_kernel_wrapper_mutation_dense( + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, +) -> None: + from torch._inductor.codegen.wrapper import user_defined_kernel_grid_fn_code + + kernel = kernel_side_table.get_kernel(kernel_idx) + constant_args = kernel_side_table.get_constant_args(constant_args_idx) + + if len(grid) == 1: + grid_fn = grid[0] + else: + fn_name, code = user_defined_kernel_grid_fn_code( + # pyrefly: ignore [missing-attribute] + kernel.fn.__name__, + # pyrefly: ignore [missing-attribute] + kernel.configs, + grid, + ) + namespace: dict[str, Any] = {} + exec(code, namespace) + grid_fn = namespace[fn_name] + + if tma_descriptor_metadata: + # as we need to launch the kernel here, we "unwrap" the + # tma_descriptor_metadata, create the TMA descriptors + # from it, and replace the tensors in the kwargs by the + # corresponding TMA descriptors before launching + kwargs = kwargs.copy() + for k, v in tma_descriptor_metadata.items(): + tensor = kwargs[k] + if (exp_meta := maybe_unpack_tma_experimental_metadata(v)) is not None: + from triton.tools.experimental_descriptor import ( + create_1d_tma_descriptor, + create_2d_tma_descriptor, + ) + + dims, block_dims, element_size = exp_meta + create_tma_descriptor = ( + create_1d_tma_descriptor + if len(dims) == 1 + else create_2d_tma_descriptor + ) + kwargs[k] = create_tma_descriptor( + tensor.data_ptr(), + *dims, + *block_dims, + element_size, + ) + else: + stable_meta = maybe_unpack_tma_stable_metadata(v) + if stable_meta is None: + raise AssertionError( + f"Failed to unpack stable TMA metadata for key {k}" + ) + from triton.tools.tensor_descriptor import TensorDescriptor + + block_shape = stable_meta[0] + + kwargs[k] = TensorDescriptor.from_tensor(tensor, block_shape) + + # move as many positional arguments from dicts to args as we + # can to circumvent the bug with the kwargs and pre_/post_hook: + # https://github.com/triton-lang/triton/issues/5082 + # TODO: remove this when the Triton issue above is fixed + args = [] + # copy kwargs and constant_args here to + # avoid mutating the original inputs + kwargs = kwargs.copy() + constant_args = constant_args.copy() + launch_kwargs = () if launch_kwargs is None else launch_kwargs + # pyrefly: ignore [missing-attribute] + for name in kernel.arg_names: + if name in launch_kwargs: + # Preserve the original kwarg form for launch kwargs. Triton's + # binder uses the kwarg to bind the kernel parameter, and + # _pack_args still exposes launch kwargs to backend.parse_options() + # so the same name may also be parsed as a compiler option. + # + # Stop positional packing entirely at this point. A later kernel + # parameter cannot be safely packed positionally after an earlier + # parameter is intentionally left in kwargs/constant_args; doing so + # would shift it into the wrong argument slot. Triton accepts the + # remaining parameters by keyword, so the only trade-off is that + # the triton#5082 workaround no longer applies after this first + # backend-option/kernel-parameter overlap. + break + if name in kwargs: + args.append(kwargs.pop(name)) + elif name in constant_args: + args.append(constant_args.pop(name)) + else: + break + + # pyrefly: ignore [bad-index, index-error] + kernel[grid_fn](*args, **kwargs, **constant_args) + + +@register_fake(triton_kernel_wrapper_mutation, skip_cache=True) +def triton_kernel_wrapper_mutation_fake_tensor_mode( + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, +) -> None: + return None + + +@triton_kernel_wrapper_mutation.py_impl(DispatchKey.Meta) +def _( + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, +) -> None: + return None + + +def trace_triton_kernel_wrapper( + proxy_mode: ProxyTorchDispatchMode, + func_overload: Callable[..., Any], + node_args: dict[str, Any], +) -> dict[str, Any] | None: + with disable_proxy_modes_tracing(): + out = func_overload(**node_args) + + proxy_args = pytree.tree_map( + proxy_mode.tracer.unwrap_proxy, # type: ignore[union-attr] + node_args, + ) + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", + func_overload, + (), + proxy_args, + name=func_overload.__name__ + "_proxy", + ) + + ret = track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer) + return ret + + +@triton_kernel_wrapper_mutation.py_impl(ProxyTorchDispatchMode) +def triton_kernel_wrapper_mutation_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, +) -> None: + node_args: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": kwargs, + } + if launch_kwargs: + node_args["launch_kwargs"] = launch_kwargs + + trace_triton_kernel_wrapper( + mode, + triton_kernel_wrapper_mutation, + node_args, + ) + + return None + + +def get_mutated_tensors( + kernel_idx: int, + constant_args_idx: int, + kwargs: dict[str, Any], + tma_descriptor_metadata: TMADescriptorMetadata, +) -> list[str]: + kernel = kernel_side_table.get_kernel(kernel_idx) + constant_args = kernel_side_table.get_constant_args(constant_args_idx) + tensor_accesses = identify_accessed_tensors( + kernel, {**kwargs, **constant_args}, tma_descriptor_metadata + ) + # Filter to only tensor kwargs: with Triton 3.7+, ordered_arg_names + # includes scalars, so writes may reference non-tensor args like SymInts. + return [ + dep.name + for dep in tensor_accesses.read_writes.writes + if isinstance(kwargs.get(dep.name), Tensor) + ] + + +@triton_kernel_wrapper_mutation.py_functionalize_impl +def triton_kernel_wrapper_mutation_functionalize( + ctx: "BaseFunctionalizeAPI", + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + launch_kwargs: tuple[str, ...] | None = None, +) -> None: + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) # type: ignore[arg-type] + # TODO(oulgen): Preexisting bug, if two kernel inputs are views of each + # other, and one gets mutated in kernel, and later another gets mutated, + # they are no longer equal. Fix this by graph breaking on this condition + # earlier in dynamo. + tensors_to_clone = get_mutated_tensors( + kernel_idx, constant_args_idx, unwrapped_kwargs, tma_descriptor_metadata + ) + with ctx.redispatch_to_next(): + functional_kwargs: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": unwrapped_kwargs, + "tensors_to_clone": tensors_to_clone, + } + if launch_kwargs: + functional_kwargs["launch_kwargs"] = launch_kwargs + unwrapped_outputs = triton_kernel_wrapper_functional(**functional_kwargs) + + if not set(unwrapped_outputs.keys()).issubset(set(kwargs.keys())): + raise AssertionError( + f"Output keys {set(unwrapped_outputs.keys())} not subset of input keys {set(kwargs.keys())}" + ) + for key, output_arg in unwrapped_outputs.items(): + if not isinstance(output_arg, Tensor): + continue + input_arg = kwargs[key] + if not isinstance(input_arg, Tensor): + raise AssertionError( + f"Expected input_arg for key {key} to be a Tensor, got {type(input_arg)}" + ) + + ctx.replace(input_arg, output_arg) + # indicate that above replace is hidden from autograd + ctx.mark_mutation_hidden_from_autograd(input_arg) + ctx.commit_update(input_arg) + ctx.sync(input_arg) + return None + + +@triton_kernel_wrapper_functional.py_impl(DispatchKey.CompositeExplicitAutograd) +def triton_kernel_wrapper_functional_dense( + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + tensors_to_clone: list[str], + launch_kwargs: tuple[str, ...] | None = None, +) -> dict[str, Any]: + # TODO(oulgen): For performance reasons, we want to ensure that these + # `clone_preserve_strides` calls are never executed at runtime + # (inductor should always optimize them away). + # Requires https://github.com/pytorch/pytorch/issues/109240 + kwargs = { + key: (clone_preserve_strides(val) if key in tensors_to_clone else val) + for key, val in kwargs.items() + } + mutation_kwargs: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": kwargs, + } + if launch_kwargs: + mutation_kwargs["launch_kwargs"] = launch_kwargs + triton_kernel_wrapper_mutation(**mutation_kwargs) + return {key: val for key, val in kwargs.items() if key in tensors_to_clone} + + +@register_fake(triton_kernel_wrapper_functional, skip_cache=True) +def triton_kernel_wrapper_functional_fake_tensor_mode( + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + tensors_to_clone: list[str], + launch_kwargs: tuple[str, ...] | None = None, +) -> dict[str, Any]: + # TODO(oulgen): For performance reasons, we want to ensure that these + # `clone_preserve_strides` calls are never executed at runtime + # (inductor should always optimize them away). + # Requires https://github.com/pytorch/pytorch/issues/109240 + return { + key: clone_preserve_strides(val) + for key, val in kwargs.items() + if key in tensors_to_clone + } + + +@triton_kernel_wrapper_functional.py_impl(ProxyTorchDispatchMode) +def triton_kernel_wrapper_functional_proxy_torch_dispatch_mode( + mode: ProxyTorchDispatchMode, + *, + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + tensors_to_clone: list[str], + launch_kwargs: tuple[str, ...] | None = None, +) -> dict[str, Any]: + node_args: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": kwargs, + "tensors_to_clone": tensors_to_clone, + } + if launch_kwargs: + node_args["launch_kwargs"] = launch_kwargs + + ret = trace_triton_kernel_wrapper( + mode, + triton_kernel_wrapper_functional, + node_args, + ) + if ret is None: + raise AssertionError("trace_triton_kernel_wrapper returned None") + return ret + + +@triton_kernel_wrapper_functional.py_functionalize_impl +def triton_kernel_wrapper_functional_functionalize( + ctx: "BaseFunctionalizeAPI", + kernel_idx: int, + constant_args_idx: int, + grid: list["TritonGridType"], + tma_descriptor_metadata: TMADescriptorMetadata, + kwargs: dict[str, Any], + tensors_to_clone: list[str], + launch_kwargs: tuple[str, ...] | None = None, +) -> dict[str, Any]: + unwrapped_kwargs = ctx.unwrap_tensors(kwargs) # type: ignore[arg-type] + with ctx.redispatch_to_next(): + functional_kwargs: dict[str, Any] = { + "kernel_idx": kernel_idx, + "constant_args_idx": constant_args_idx, + "grid": grid, + "tma_descriptor_metadata": tma_descriptor_metadata, + "kwargs": unwrapped_kwargs, + "tensors_to_clone": tensors_to_clone, + } + if launch_kwargs: + functional_kwargs["launch_kwargs"] = launch_kwargs + outputs = triton_kernel_wrapper_functional(**functional_kwargs) + return ctx.wrap_tensors(outputs) # type: ignore[return-value,arg-type] + + +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.PythonDispatcher) # type: ignore[attr-defined] +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.PythonTLSSnapshot) # type: ignore[attr-defined] +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.ADInplaceOrView) +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.BackendSelect) +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutocastCPU) # type: ignore[attr-defined] +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutocastCUDA) # type: ignore[attr-defined] +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutogradCUDA) +triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutogradCPU) + +triton_kernel_wrapper_functional.fallthrough(DispatchKey.PythonDispatcher) # type: ignore[attr-defined] +triton_kernel_wrapper_functional.fallthrough(DispatchKey.PythonTLSSnapshot) # type: ignore[attr-defined] +triton_kernel_wrapper_functional.fallthrough(DispatchKey.ADInplaceOrView) +triton_kernel_wrapper_functional.fallthrough(DispatchKey.BackendSelect) +triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutocastCPU) # type: ignore[attr-defined] +triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutocastCUDA) # type: ignore[attr-defined] +triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutogradCUDA) +triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutogradCUDA) +triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutogradCPU) + +# Adds SAC support for triton ops +redirect_to_mode(triton_kernel_wrapper_mutation, _CachingTorchDispatchMode) +redirect_to_mode(triton_kernel_wrapper_mutation, _CachedTorchDispatchMode) + +############################################################################### +# The "TritonHOPifier": a class that transforms a call to a triton kernel into +# a call to the triton_kernel_wrapper_mutation HOP. + + +class TritonHOPifier: + """Orchestrator for converting a user-defined triton kernel into a call + to the triton_kernel_wrapper_mutation HOP. + + It has two main use cases. + + 1. When Dynamo sees a triton kernel, it wraps it into a TritonKernelVariable + and uses the TritonHOPifier to convert calls to the TritonKernelVariable + into a call to the HOP. + + 2. In order to capture a user-defined triton kernel while performing + tracing (via make_fx or non-strict export), a user must annotate their + triton kernel with the `wrap_triton` decorator. The decorator uses + TritonHOPifier to convert calls to the triton kernel into a call + to the HOP (which can then be traced). + + Because Dynamo has its own calling conventions for e.g. invoking a user-defined function + TritonHOPifier is an abstract class that can be overridden by its subclasses. + """ + + def raise_unsupported(self, msg: str) -> Never: + raise NotImplementedError("abstract method") + + def is_callable(self, maybe_callable: Any) -> bool: + raise NotImplementedError("abstract method") + + def get_value(self, val: Any) -> Any: + raise NotImplementedError("abstract method") + + def call_grid( # type: ignore[no-untyped-def] + self, + grid, + meta, + tx, + ) -> tuple[int | sympy.Expr | SymInt, ...] | tuple["Proxy", ...]: + raise NotImplementedError("abstract method") + + def wrap_user_defined_obj( + self, + user_obj: Any, + tx: Optional["InstructionTranslatorBase"], + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"] | None, + name: str, + ) -> Any: + raise NotImplementedError("abstract method") + + def call_user_defined_fn( + self, + user_fn: Callable[..., Any], + args: list, + kwargs: dict, + tx: Optional["InstructionTranslatorBase"], + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"] | None, + ) -> Any: + raise NotImplementedError("abstract method") + + def maybe_unpack_configs( + self, configs: list["TritonConfig"], tx: Optional["InstructionTranslatorBase"] + ) -> list["TritonConfig"]: + raise NotImplementedError("abstract method") + + def maybe_unpack_heuristic_result(self, result: Any) -> Any: + raise NotImplementedError("abstract method") + + @staticmethod + def do_prune_configs( # type: ignore[no-untyped-def] + autotuner: "TritonAutotunerType", + early_config_prune: Callable | None, + perf_model: Callable | None, + top_k: float, + configs: list, + named_args: dict, + kwargs: dict, + ) -> list["TritonConfig"]: + # Reimplement autotuner.prune_configs(...) here + # see: https://github.com/triton-lang/triton/blob/e57b46897191b3b3061c78d0d60e58e94be565b6/python/triton/runtime/autotuner.py + # We do this to avoid calling prune_configs, which in turn calls early_config_prune and perf_model + # These are both user-defined functions which can contain side effects, so we want to sandbox them in Dynamo + + if early_config_prune: + configs = early_config_prune(configs, named_args, **kwargs) + + if perf_model: + # we assert top_k is a float before calling this + if isinstance(top_k, float) and top_k <= 1.0: + top_k = int(len(configs) * top_k) + elif not isinstance(top_k, int): + """ + Slice index must be an integer, SupportsIndex or None + """ + raise TypeError( + "Error while pruning configs, top_k must be either 1) a float <= 1.0 or 2) an int" + ) + if len(configs) > top_k: + est_timing = [ + ( + config, + float( + perf_model(**named_args, **kwargs, **config.all_kwargs()) + ), + ) + for config in configs + ] + configs = [ + config[0] + for config in sorted(est_timing, key=operator.itemgetter(1))[:top_k] + ] + return configs + + def call_HOP( # type: ignore[no-untyped-def] + self, + variable, + grids, + combined_args: dict[str, Any], + launch_kwargs: tuple[str, ...], + kernel_arg_names: set[str], + tx, + ) -> Optional["ConstantVariable"]: + raise NotImplementedError("abstract method") + + def check_grid( # type: ignore[no-untyped-def] + self, grid + ) -> tuple[int | sympy.Expr | SymInt, ...] | tuple["Proxy", ...]: + raise NotImplementedError("abstract method") + + def init_variable( + self, + variable: Union["TraceableTritonKernelWrapper", "TritonKernelVariable"], + kernel: "TritonKernelType", + kernel_idx: int | None, + grid: Optional["TritonGridType"], + ) -> None: + from triton.runtime.autotuner import Autotuner + + if kernel is None: + raise AssertionError("kernel cannot be None") + + variable.kernel = kernel + variable.kernel_idx = kernel_side_table.add_kernel(kernel) + + if kernel_idx is not None and variable.kernel_idx != kernel_idx: + raise AssertionError( + f"kernel_idx mismatch: expected {kernel_idx}, got {variable.kernel_idx}" + ) + + # pyrefly: ignore [bad-assignment] + variable.grid = grid + + if isinstance(kernel, Autotuner): + import torch + import torch._dynamo + + # We only support configs, keys, and restore_value arguments + # of triton.autotune. Make sure other arguments are defaulted. + defaults = inspect.signature(Autotuner.__init__).parameters + # Newer version of triton change attribute name from warmup to num_warmup and rep to num_rep. + # The call to get_first_attr is to maintain backward-compatibility. + + def defaults_ok( + attr: str, alternates: tuple[str, ...], values: tuple[Any, ...] + ) -> bool: + if attr not in defaults: + return True + value = torch._dynamo.utils.get_first_attr(kernel, attr, *alternates) + if value == defaults[attr].default: + return True + return value in values + + if ( + not torch._inductor.config.unsafe_ignore_unsupported_triton_autotune_args + and ( + not defaults_ok("num_warmups", ("warmup",), (25, None)) + or not defaults_ok("num_reps", ("rep",), (100, None)) + or not defaults_ok("use_cuda_graph", (), (False,)) + ) + ): + self.raise_unsupported( + "Only configs, keys, restore_value, and reset_to_zero are supported for triton.autotune" + ) + if ( + not torch._inductor.config.unsafe_ignore_unsupported_triton_autotune_args + and ( + # pre_hook requires running arbitrary code at runtime, which we cannot handle at this time + # https://github.com/pytorch/pytorch/issues/139059 + # we can't support pre_hook or post_hook in user defined triton kernels at the moment, + # as they require the ability to execute code at runtime (AOTI can't support this) + ( + hasattr(kernel, "user_defined_pre_hook") + and kernel.user_defined_pre_hook is not False + ) + or ( + hasattr(kernel, "user_defined_post_hook") + and kernel.user_defined_post_hook is not False + ) + or ( + # Check Config passed to autotuner in configs + any(cfg.pre_hook is not None for cfg in kernel.configs) + ) + ) + ): + self.raise_unsupported( + "pre_hook and post_hook are not supported in triton.Autotune or triton.Config" + ) + + @staticmethod + def get_kernel_source( + variable: "TritonKernelVariable | TraceableTritonKernelWrapper", + ) -> "Source | None": + kernel_source = getattr(variable, "kernel_source", None) + if kernel_source is None: + kernel_source = getattr(variable, "source", None) + return kernel_source + + def recreate_variable( + self, + variable: "TritonKernelVariable | TraceableTritonKernelWrapper", + *, + kernel: "TritonKernelType", + kernel_idx: int | None, + grid: "TritonGridType | None", + ) -> "TritonKernelVariable | TraceableTritonKernelWrapper": + return type(variable)( + kernel=kernel, + kernel_idx=kernel_idx, + grid=grid, + kernel_source=self.get_kernel_source(variable), + ) + + def call_getitem( + self, + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"], + args: Sequence[Any], + ) -> Union["TritonKernelVariable", "TraceableTritonKernelWrapper"]: + # __getitem__ should only be called if we don't already have a grid + # Only grid needs to be passed + if variable.grid is not None or len(args) != 1: + self.raise_unsupported( + "Triton kernels should be called with only a single grid" + ) + + return self.recreate_variable( + variable, + kernel=variable.kernel, + kernel_idx=variable.kernel_idx, + grid=args[0], + ) + + def call_run( + self, + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"], + args: Sequence[Any], + kwargs: dict[str, Any], + tx: Optional["InstructionTranslatorBase"], + ) -> Optional["ConstantVariable"]: + if "grid" not in kwargs: + self.raise_unsupported("Triton kernel requires to be called with a grid") + grid = kwargs.pop("grid") + kwargs.pop("warmup", None) + # rewrite kernel.run(*args, grid=grid) to kernel[grid](*args) + return self.call_triton_kernel( + self.recreate_variable( + variable, + kernel=variable.kernel, + kernel_idx=variable.kernel_idx, + grid=grid, + ), + args, + kwargs, + tx, + ) + + def call_triton_kernel( + self, + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"], + args: Sequence[Any], + kwargs: dict[str, Any], + tx: Optional["InstructionTranslatorBase"], + ) -> Optional["ConstantVariable"]: + from triton import JITFunction + from triton.runtime.autotuner import autotune, Autotuner, Config, Heuristics + + # Check if num_ctas is in kwargs + if "num_ctas" in kwargs: + self.raise_unsupported( + "Passing num_ctas directly to the Triton kernel is not supported. " + "Please use a Config in @triton.autotune instead." + ) + + # Make sure the kernel has a grid + if variable.grid is None: + self.raise_unsupported("Triton kernels should always be called with a grid") + + # raise an exception if there are multiple @triton.autotune decorators + iter_kernel = variable.kernel + autotuner_count = 0 + while not isinstance(iter_kernel, JITFunction): + if isinstance(iter_kernel, Autotuner): + autotuner_count += 1 + if autotuner_count > 1: + self.raise_unsupported( + "Passing multiple @triton.autotune decorators is not supported. " + "Please use a single @triton.autotune decorator instead." + ) + + iter_kernel = iter_kernel.fn + + jit_arg_names = set(iter_kernel.arg_names) + + # Process the @triton.heuristics decorator: + # - We know there is only 1 autotuner decorator here + # - We can apply the heuristic to all triton.Configs in the order that the decorators appear + # This way, when the config is selected, the heuristics have already been applied. + # - Decorators that appear *before* the autotuner are already processed correctly + if isinstance(variable.kernel, Autotuner) and isinstance( + variable.kernel.fn, Heuristics + ): + # unwrap the heuristics decorator, we don't need it anymore + # variable.kernel ==> Autotuner + # variable.kernel.fn ==> Heuristics + # ... + # There can be arbitrarily many heuristics wrappers here! + # ... + # variable.kernel.fn ==> JITFunction + + # Copy the configs, we are going to be modifying them + new_configs = copy.deepcopy(variable.kernel.configs) + + named_args = dict(zip(variable.kernel.arg_names, args)) + + # Iterate through all of the heuristics wrappers that come after the autotune wrapper + iter_kernel = variable.kernel.fn + while isinstance(iter_kernel, Heuristics): + # For each config, apply the heuristic fn(s) + for config_idx in range(len(new_configs)): + for kwarg_key, heuristic_fn in iter_kernel.values.items(): + # Run heuristics on the combined configs + kwargs + heuristic_result = self.call_user_defined_fn( + heuristic_fn, + [ + { + **named_args, + **kwargs, + **new_configs[config_idx].__dict__["kwargs"], + }, + ], + {}, + tx, + variable, + ) + + # Update the kwargs in each config + # maybe_unpack_heuristic_result raises unsupported if the value is non-constant + new_configs[config_idx].__dict__["kwargs"][kwarg_key] = ( + self.maybe_unpack_heuristic_result(heuristic_result) + ) + + iter_kernel = iter_kernel.fn + if not isinstance(iter_kernel, JITFunction): + raise AssertionError( + f"Expected iter_kernel to be a JITFunction, got {type(iter_kernel)}" + ) + prune_configs_by = { + "perf_model": variable.kernel.perf_model, + "early_config_prune": variable.kernel.early_config_prune, + "configs_top_k": variable.kernel.configs_top_k, + } + new_kernel = autotune( + configs=new_configs, key=[], prune_configs_by=prune_configs_by + )(iter_kernel) + # create a new variable to contain the new (wrapped) kernel; + # skip kernel_idx to get a new record in the kernel side table + new_var = self.recreate_variable( + variable, + kernel=new_kernel, + kernel_idx=None, + grid=variable.grid, + ) + return self.call_triton_kernel(new_var, args, kwargs, tx) + + SPECIAL_CONFIG_NAMES = { + "num_warps", + "num_stages", + "num_ctas", + "num_consumer_groups", + "num_buffers_warp_spec", + "num_cpu_threads", + } + + # move special config names to configs out of kwargs + special_kwargs = {} + for name in SPECIAL_CONFIG_NAMES: + if name in kwargs: + # remove special kwargs from `kwargs` + val = kwargs.pop(name) + special_kwargs[name] = self.get_value(val) + + if special_kwargs: + if isinstance(variable.kernel, Autotuner): + # if there is Autotuner already, set + # special kwargs to each of its configs + new_configs = copy.deepcopy(variable.kernel.configs) + for config in new_configs: + config.__dict__.update(special_kwargs) + prune_configs_by = { + "perf_model": variable.kernel.perf_model, + "early_config_prune": variable.kernel.early_config_prune, + "configs_top_k": variable.kernel.configs_top_k, + } + + new_kernel = autotune( + configs=new_configs, key=[], prune_configs_by=prune_configs_by + )(variable.kernel.fn) + else: + # if there is no Autotuner, wrap the kernel into a + # new one with a single config with special kwargs + new_config = Config(kwargs={}, **special_kwargs) + + new_kernel = autotune(configs=[new_config], key=[])(variable.kernel) + + # create a new variable to contain the new (wrapped) kernel; + # skip kernel_idx to get a new record in the kernel side table + new_var = self.recreate_variable( + variable, + kernel=new_kernel, + kernel_idx=None, + grid=variable.grid, + ) + return self.call_triton_kernel(new_var, args, kwargs, tx) + + if isinstance(variable.kernel, Autotuner): + special_param_names = [] + for name in SPECIAL_CONFIG_NAMES: + if name in jit_arg_names: + special_param_names.append(name) + + if special_param_names: + # If the Triton kernel has SPECIAL_CONFIG_NAMES in parameters, those should + # be passed from the kernel configs: the behavior of Triton runtime is that + # those values get folded into the kernel arguments iff there are parameters + # with the same name. Normally the values of those parameters are defined + # outside the `kwargs` part of the autotuning configs. Here we move them to + # the `kwargs` part (if they're absent there) to facilitate passing them as + # arguments to the kernel downstream. + updated = False + new_configs = copy.deepcopy(variable.kernel.configs) + for config in new_configs: + for name in special_param_names: + if name not in config.__dict__["kwargs"]: + if name not in config.__dict__: + raise AssertionError( + f"{name} must be in autotuning configs to be used " + "as a kernel parameter" + ) + config.__dict__["kwargs"][name] = config.__dict__[name] + updated = True + + if updated: + prune_configs_by = { + "perf_model": variable.kernel.perf_model, + "early_config_prune": variable.kernel.early_config_prune, + "configs_top_k": variable.kernel.configs_top_k, + } + + new_kernel = autotune( + configs=new_configs, prune_configs_by=prune_configs_by, key=[] + )(variable.kernel.fn) + new_var = self.recreate_variable( + variable, + kernel=new_kernel, + kernel_idx=None, + grid=variable.grid, + ) + return self.call_triton_kernel(new_var, args, kwargs, tx) + + # These are the default values in upstream Triton + # see: https://github.com/triton-lang/triton/blob/e57b46897191b3b3061c78d0d60e58e94be565b6/python/triton/runtime/autotuner.py + default_perf_model = None + default_early_config_prune = None + + # run prune_configs_by + if isinstance(variable.kernel, Autotuner) and ( + variable.kernel.perf_model != default_perf_model + or variable.kernel.early_config_prune != default_early_config_prune + ): + # Prune the configs + named_args = dict(zip(variable.kernel.arg_names, args)) + + # The source information is important here so the guards are installed correctly + + wrapped_early_configs_prune = self.wrap_user_defined_obj( + variable.kernel.early_config_prune, + tx, + variable, + "early_config_prune", + ) + + wrapped_perf_model = self.wrap_user_defined_obj( + variable.kernel.perf_model, tx, variable, "perf_model" + ) + + wrapped_configs_top_k = self.wrap_user_defined_obj( + variable.kernel.configs_top_k, tx, variable, "configs_top_k" + ) + + wrapped_configs = self.wrap_user_defined_obj( + variable.kernel.configs, tx, variable, "configs" + ) + + pruned_configs = self.call_user_defined_fn( + self.do_prune_configs, + [ + variable, + wrapped_early_configs_prune, + wrapped_perf_model, + wrapped_configs_top_k, + wrapped_configs, + named_args, + kwargs, + ], + {}, + tx, + variable, + ) + + pruned_configs = self.maybe_unpack_configs(pruned_configs, tx) + + # after pruning the configs, create a new autotuner object with + # these configs and recurse. + new_kernel = autotune(configs=pruned_configs, key=[])(variable.kernel.fn) + # create a new variable to contain the new (wrapped) kernel; + # skip kernel_idx to get a new record in the kernel side table + new_var = self.recreate_variable( + variable, + kernel=new_kernel, + kernel_idx=None, + grid=variable.grid, + ) + return self.call_triton_kernel(new_var, args, kwargs, tx) + + # Triton passes launch kwargs to backend.parse_options(), even when a + # kwarg also binds a kernel parameter. Preserve the launch-site names; + # values stay in combined_args_raw so Inductor materializes backend + # options only after the target backend is known. + launch_kwargs = tuple(kwargs) + + if isinstance(variable.kernel, Autotuner): + config_kwarg_names = set().union( + *(set(config.kwargs) for config in variable.kernel.configs) + ) + config_conflicts = sorted(set(launch_kwargs) & config_kwarg_names) + if config_conflicts: + self.raise_unsupported( + "Triton launch kwargs conflict with autotune config kwargs: " + f"{config_conflicts!r}." + ) + + positional_arg_names = iter_kernel.arg_names[: len(args)] + if len(args) > len(iter_kernel.arg_names): + self.raise_unsupported( + f"{iter_kernel.__name__}() takes {len(iter_kernel.arg_names)} " + f"positional arguments but {len(args)} were given" + ) + + duplicate_kwargs = sorted(set(positional_arg_names) & set(kwargs)) + if duplicate_kwargs: + self.raise_unsupported( + f"{iter_kernel.__name__}() got multiple values for argument " + f"{duplicate_kwargs[0]!r}" + ) + + # Both for grid's meta as well as for the kernel, we need combined + # args and launch kwargs combined and normalized. Non-signature launch + # kwargs are included here so Inductor can later recover their values + # when materializing target-specific backend options. + + combined_args_raw = {**dict(zip(iter_kernel.arg_names, args)), **kwargs} + + # precompute the grid for the kernel + configs = ( + [config.kwargs for config in variable.kernel.configs] + if isinstance(variable.kernel, Autotuner) + else [{}] + ) + grids = [] + for config_args in configs: + # If the grid is a function, then lets execute it and convert it to + # a list + grid = variable.grid + if grid is None: + raise AssertionError("grid cannot be None at this point") + if self.is_callable(grid): + # Populate the special "meta" argument to call the grid function + meta = {**combined_args_raw, **config_args} + grid = self.call_grid(grid, meta, tx) # type: ignore[arg-type] + grids.append(self.check_grid(grid)) + + for i in range(len(grids)): + if not isinstance(grids[i], tuple): + self.raise_unsupported("Only tuple grids are supported") + # inductor expects all grids to be 3-tuple so lets make it + if len(grids[i]) == 1: + grids[i] = (grids[i][0], 1, 1) + elif len(grids[i]) == 2: + grids[i] = (grids[i][0], grids[i][1], 1) + elif len(grids[i]) > 3: + self.raise_unsupported("Grid can have at most rank 3") + + if len(grids) == 0: + raise AssertionError("grids cannot be empty") + if isinstance(variable.kernel, JITFunction): + constexprs = [p.num for p in variable.kernel.params if p.is_constexpr] + arg_names = [p.name for p in variable.kernel.params] + else: + # If we are looking at an @triton.autotune decorator, the nested function should be a JITFunction + # This is because we don't support @triton.heuristics or nested @triton.autotune decorators yet + if not isinstance(variable.kernel, Autotuner): + raise AssertionError( + f"Expected variable.kernel to be an Autotuner, got {type(variable.kernel)}" + ) + constexprs = [p.num for p in variable.kernel.fn.params if p.is_constexpr] + arg_names = [p.name for p in variable.kernel.fn.params] + + for idx, arg_name in enumerate(arg_names): + if idx in constexprs: + if arg_name in combined_args_raw: + # [Note: Specialize tl.constexpr args in user-defined triton kernels] + # This arg is marked as tl.constexpr. That means that triton will recompile every time + # this value changes. + # https://github.com/pytorch/pytorch/issues/136504 + # One option is to correctly pass the symints in so that the symbolic expressions are defined + # when the triton code is being executed. + # But since triton will have to recompile either way, we instead just specialize on the value. + # + # Depending on the type of `variable` we might expect different types for the symbolic args: + # either SymNodeVariables (for TritonKernelVariables) or SymInts (TracingTritonKernelWrapper) + combined_args_raw[arg_name] = variable.specialize_symbolic( + combined_args_raw[arg_name] + ) + return self.call_HOP( + variable, grids, combined_args_raw, launch_kwargs, jit_arg_names, tx + ) + + +############################################################################### +# Helpers for wrap_triton API that makes a user-defined triton kernel traceable into +# a graph via make_fx or non-strict export (coming soon) + + +class TracingTritonHOPifier(TritonHOPifier): + def raise_unsupported(self, msg: str) -> Never: + raise RuntimeError(msg) + + def is_callable(self, maybe_callable: Any) -> bool: + return callable(maybe_callable) + + def get_value(self, val: Any) -> Any: + return val + + def call_grid( + self, + grid: "TritonGridCallableType", + meta: "TritonMetaParamsType", + tx: None, + ) -> tuple[int | sympy.Expr | SymInt, ...]: + if tx is not None: + raise AssertionError("tx must be None for TracingTritonHOPifier") + if not isinstance(meta, dict): + raise AssertionError(f"meta must be a dict, got {type(meta)}") + if not callable(grid): + raise AssertionError(f"grid must be callable, got {type(grid)}") + return grid(meta) + + def wrap_user_defined_obj( + self, + user_obj: Any, + tx: Optional["InstructionTranslatorBase"], + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"] | None, + name: str, + ) -> Any: + if tx is not None: + raise AssertionError("tx must be None for TracingTritonHOPifier") + return user_obj + + def call_user_defined_fn( + self, + user_fn: Callable[..., Any], + args: list, + kwargs: dict, + tx: Optional["InstructionTranslatorBase"], + variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"] | None, + ) -> Any: + if not isinstance(args, list): + raise AssertionError(f"args must be a list, got {type(args)}") + if not isinstance(kwargs, dict): + raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}") + if not callable(user_fn): + raise AssertionError(f"user_fn must be callable, got {type(user_fn)}") + return user_fn(*args, **kwargs) + + def maybe_unpack_configs( + self, configs: list["TritonConfig"], tx: Optional["InstructionTranslatorBase"] + ) -> list["TritonConfig"]: + if not isinstance(configs, list): + raise AssertionError(f"configs must be a list, got {type(configs)}") + return configs + + def maybe_unpack_heuristic_result(self, result: Any) -> Any: + return result + + def check_grid( + self, + grid: "TritonGridType", + ) -> tuple[int | sympy.Expr | SymInt, ...]: + if not isinstance(grid, collections.abc.Sequence): + raise RuntimeError( + "wrap_triton can only handle grids that resolve to Sequence[int]." + ) + # normalize to tuple + return tuple(grid) + + def store_non_graphable_args( + self, + combined_args: dict[str, Any], + ) -> tuple[dict, int]: + """ + Some args cannot be stored in the FX graph. + Put them in the side table. + """ + + def is_graphable(val: Any) -> bool: + return isinstance(val, (fx.node.base_types, fx.Node)) + + non_graphable_args = { + k: v for k, v in combined_args.items() if not is_graphable(v) + } + graphable_args = {k: v for k, v in combined_args.items() if is_graphable(v)} + + constant_args_idx = kernel_side_table.add_constant_args(non_graphable_args) + + return graphable_args, constant_args_idx + + def is_dynamic_backend_option(self, value: Any) -> bool: + # Backend options are compile-time values. In proxy tracing, a value can + # be a Proxy/Node directly or be nested inside a tuple/list option such + # as backend_option=(sym_size,). Reject those unless the name is later + # identified as a real kernel parameter. + leaves, _ = pytree.tree_flatten(value) + return any( + isinstance( + leaf, + ( + fx.Node, + fx.Proxy, + Tensor, + SymInt, + SymBool, + SymFloat, + ), + ) + for leaf in leaves + ) + + def call_HOP( + self, + variable: "TraceableTritonKernelWrapper", + grids: list["TritonGridTupleType"], + combined_args: dict[str, Any], + launch_kwargs: tuple[str, ...], + kernel_arg_names: set[str], + tx: None, + ) -> None: + if tx is not None: + raise AssertionError("tx must be None for TracingTritonHOPifier") + if not isinstance(variable, TraceableTritonKernelWrapper): + raise AssertionError( + f"Expected TraceableTritonKernelWrapper, got {type(variable)}" + ) + + graphable_args, constant_args_idx = self.store_non_graphable_args(combined_args) + # launch_kwargs records the names passed as kwargs at the Triton launch + # site. A non-kernel launch kwarg can only be a compiler option, so it + # must be concrete before entering the graph. Kernel launch kwargs may + # also be compiler options, but that target-specific check happens in + # Inductor after backend.parse_options(). + non_const_options = [ + k + for k in launch_kwargs + if k not in kernel_arg_names + and self.is_dynamic_backend_option(combined_args[k]) + ] + if non_const_options: + self.raise_unsupported( + "Triton backend options must be concrete values: " + f"{sorted(non_const_options)!r}." + ) + + if not isinstance(variable.kernel_idx, int): + raise AssertionError( + f"kernel_idx must be an int, got {type(variable.kernel_idx)}" + ) + return triton_kernel_wrapper_mutation( + kernel_idx=variable.kernel_idx, + constant_args_idx=constant_args_idx, + grid=grids, # type: ignore[arg-type] + # TMA descriptor capturing not yet + # supported in non-dynamo tracing + tma_descriptor_metadata={}, + kwargs=graphable_args, + launch_kwargs=launch_kwargs, + ) + + +tracing_triton_hopifier_singleton = TracingTritonHOPifier() + + +class TraceableTritonKernelWrapper: + kernel: "TritonKernelType" + kernel_idx: int | None + grid: Optional["TritonGridType"] + kernel_source: "Source | None" + + def __init__( + self, + kernel: "TritonKernelType", + kernel_idx: int | None, + grid: Optional["TritonGridType"], + kernel_source: "Source | None" = None, + ) -> None: + self.kernel = None + self.grid = None + self.kernel_source = kernel_source + tracing_triton_hopifier_singleton.init_variable(self, kernel, kernel_idx, grid) + if self.kernel is None: + raise AssertionError("kernel was not initialized properly") + + def __getitem__(self, *args: Sequence[Any]) -> "TraceableTritonKernelWrapper": + return tracing_triton_hopifier_singleton.call_getitem(self, args) # type: ignore[return-value] + + def run(self, *args: Sequence[Any], **kwargs: dict[str, Any]) -> Any: + from torch._library.triton import is_wrap_triton_enabled + + if is_wrap_triton_enabled(): + return tracing_triton_hopifier_singleton.call_run(self, args, kwargs, None) + else: + if self.kernel is None: + raise AssertionError("kernel cannot be None") + # pyrefly: ignore [missing-attribute] + return self.kernel.run(*args, **kwargs) + + def __call__(self, *args: Sequence[Any], **kwargs: dict[str, Any]) -> Any: + from torch._library.triton import is_wrap_triton_enabled + + if is_wrap_triton_enabled(): + return tracing_triton_hopifier_singleton.call_triton_kernel( + self, args, kwargs, None + ) + else: + if self.kernel is None: + raise AssertionError("kernel cannot be None") + # pyrefly: ignore [bad-index, index-error] + return self.kernel[self.grid](*args, **kwargs) + + def specialize_symbolic(self, arg: Sequence[Any]) -> Any: + import torch + + # See [Note: Specialize tl.constexpr args in user-defined triton kernels] + if isinstance(arg, (torch.SymInt, torch.SymBool, torch.SymFloat)): + return guard_scalar(arg) + return arg diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/utils.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..57dc8115395e2e76cb62dd9210afd551a2d5497c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/utils.py @@ -0,0 +1,1498 @@ +# mypy: allow-untyped-defs +import contextlib +import functools +from collections.abc import Callable, Iterable, Mapping, Sequence +from contextlib import AbstractContextManager, contextmanager, ExitStack, nullcontext +from dataclasses import dataclass +from typing import Any, overload, TypeVar +from typing_extensions import ParamSpec + +import torch +import torch.fx.traceback as fx_traceback +import torch.utils._pytree as pytree +from torch._dispatch.python import suspend_functionalization +from torch._guards import detect_fake_mode +from torch._higher_order_ops.schema import HopSchema +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_custom_class +from torch._ops import HigherOrderOperator, OperatorBase, OpOverload +from torch._subclasses.fake_tensor import ( + FakeTensor, + is_fake_tensor, + maybe_get_fake_mode, +) +from torch._subclasses.functional_tensor import ( + disable_functional_mode, + FunctionalTensor, +) +from torch.fx.experimental.proxy_tensor import ( + _temp_remove_metadata_torch_function_mode, + disable_proxy_modes_tracing, + make_fx, +) +from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts +from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata +from torch.multiprocessing.reductions import StorageWeakRef +from torch.utils._python_dispatch import is_traceable_wrapper_subclass + + +@dataclass +class UnsupportedAliasMutationException(RuntimeError): + reason: str + + +def autograd_not_implemented_inner( + operator: OperatorBase, delayed_error: bool, *args: Any, **kwargs: Any +) -> Any: + """If autograd is enabled and any of the arguments require grad this will either + raise an error or return a DelayedError depending on the value of delayed. + + Args: + operator: The Operator to call with the *args and **kwargs with + op_name: The name of the Operator + delayed_error: If True, return a DelayedError instead of raising an error + args: The flattened operands to the Operator + kwargs: The keyword arguments to the Operator + + Raises: + RuntimeError: If autograd is enabled and any of the arguments to the Operator + """ + with torch._C._AutoDispatchBelowAutograd(): + result = operator(*args, **kwargs) + flat_operands = pytree.arg_tree_leaves(*args) + if torch.is_grad_enabled() and any( + f.requires_grad for f in flat_operands if isinstance(f, torch.Tensor) + ): + if delayed_error: + err_fn = torch._C._functions.DelayedError( + f"Autograd not implemented for {str(operator)}", + 1, + ) + + def fake_requires_grad(tensor): + if torch.is_floating_point(tensor) or torch.is_complex(tensor): + tensor = tensor.detach() + tensor.requires_grad = True + return tensor + + return pytree.tree_map_only( + torch.Tensor, lambda x: err_fn(fake_requires_grad(x)), result + ) + else: + raise RuntimeError(f"Autograd not implemented for {str(operator)}") + return result + + +def autograd_not_implemented(op: OperatorBase, deferred_error: bool) -> Callable: + def inner(*args, **kwargs): + return autograd_not_implemented_inner(op, deferred_error, *args, **kwargs) + + return inner + + +def _maybe_run_with_interpreter(fn): + maybe_interpreted_fn = fn + if isinstance(fn, torch.fx.GraphModule) and fx_traceback.has_preserved_node_meta(): + # Running graph with interpreter is needed for propagating the stack_trace + def graph_with_interpreter(*args): + with fx_traceback.preserve_node_meta(): + return torch.fx.Interpreter(fn).run(*args) + + maybe_interpreted_fn = graph_with_interpreter + return maybe_interpreted_fn + + +def _hop_compile_and_call(fn, args, kwargs=None): + """Compile and call fn with fullgraph=True for HOP eager execution. + + Pre-activates the fullgraph counter so that compile_wrapper treats this as + a nested compile. This avoids erroring when a non-infra dispatch mode + causes the frame to be skipped — the function still executes eagerly within + compile_wrapper and returns normally. + """ + from torch._dynamo.eval_frame import set_fullgraph_compiled_frame_count + + with setup_compilation_env() as backend: + old_count = set_fullgraph_compiled_frame_count(0) + try: + return torch.compile(fn, backend=backend, fullgraph=True)( + *args, **(kwargs or {}) + ) + finally: + set_fullgraph_compiled_frame_count(old_count) + + +def _maybe_compile_and_run_fn(fn, *args): + if not torch.compiler.is_dynamo_compiling(): + return _hop_compile_and_call(fn, args) + else: + return fn(*args) + + +def reenter_make_fx(fn, subgraph_decomp_table=None): + from torch.fx.experimental.proxy_tensor import _CURRENT_MAKE_FX_TRACER + + @functools.wraps(fn) + def wrapped(*args): + if _CURRENT_MAKE_FX_TRACER is None: + raise AssertionError( + "Cannot reenter make_fx when we're not under a make_fx tracing session" + ) + if subgraph_decomp_table is None: + gm = _CURRENT_MAKE_FX_TRACER.trace_subgraph( + _maybe_run_with_interpreter(fn), *args + ) + else: + gm = _CURRENT_MAKE_FX_TRACER.trace_subgraph_custom_decomp( + _maybe_run_with_interpreter(fn), subgraph_decomp_table, *args + ) + + return gm + + return wrapped + + +def _maybe_reenter_make_fx(fn, subgraph_decomp_table=None): + from torch.fx.experimental.proxy_tensor import _CURRENT_MAKE_FX_TRACER + + if _CURRENT_MAKE_FX_TRACER is not None: + return reenter_make_fx(fn, subgraph_decomp_table=subgraph_decomp_table) + else: + + def _maybe_make_fx_with_fake_mode(fn): + @functools.wraps(fn) + def wrapped(*args): + from torch._guards import detect_fake_mode + + fake_mode = detect_fake_mode(args) + if fake_mode is None: + # we creaeta a fake_mode here to make sure we could + # trace the graph with data-dependent calls e.g. .item() + return make_fx( + fn, + tracing_mode="fake", + decomposition_table=subgraph_decomp_table, + )(*args) + # Tracing with real if all inputs have been fakfied + return make_fx(fn, decomposition_table=subgraph_decomp_table)(*args) + + return wrapped + + return _maybe_make_fx_with_fake_mode(fn) + + +def check_meta_consistency( + lhs_list: list[torch.Tensor | torch.SymInt | int], + rhs_list: list[torch.Tensor | torch.SymInt | int], + lhs_name: str, + rhs_name: str, + include_contiguity: bool = True, +) -> None: + def diff_meta_pairs( + lhs_list: list[torch.Tensor | torch.SymInt | int], + rhs_list: list[torch.Tensor | torch.SymInt | int], + ) -> list[str]: + def diff_meta( + lhs: torch.Tensor | torch.SymInt | int, + rhs: torch.Tensor | torch.SymInt | int, + ) -> str: + if isinstance(lhs, torch.Tensor) and isinstance(rhs, torch.Tensor): + return ", ".join( + diff_tensor_meta( + _extract_tensor_metadata( + lhs, include_contiguity=include_contiguity + ), + _extract_tensor_metadata( + rhs, include_contiguity=include_contiguity + ), + check_grad=False, + ) + ) + else: + + def _both_int_types(lhs, rhs): + return isinstance(lhs, (int, torch.SymInt)) and isinstance( + rhs, (int, torch.SymInt) + ) + + def _both_tensor(lhs, rhs): + return isinstance(lhs, torch.Tensor) and isinstance( + rhs, torch.Tensor + ) + + if not _both_int_types(lhs, rhs) and not _both_tensor(lhs, rhs): + return f"type: {lhs} vs {rhs}" + + return "" + + # Manually check the device of lhs and rhs as this field is currently not part of TensorMetadata + def diff_device( + lhs: torch.Tensor | torch.SymInt | int, + rhs: torch.Tensor | torch.SymInt | int, + ) -> str: + if isinstance(lhs, torch.Tensor) and isinstance(rhs, torch.Tensor): + if ( + rhs.device.type == lhs.device.type + and rhs.device.index == lhs.device.index + ): + return "" + else: + return "device" + return "" + + if len(lhs_list) != len(rhs_list): + raise torch._dynamo.exc.UncapturedHigherOrderOpError( + f"Expected {lhs_name} and {rhs_name} to have same number of outputs but got lhs:{lhs_list} and rhs:{rhs_list}" + ) + all_diffs = [] + for i, (lhs, rhs) in enumerate(zip(lhs_list, rhs_list)): + if diff := diff_meta(lhs, rhs): + all_diffs.append( + f"pair[{i}] differ in {diff}, where lhs is {lhs} and rhs is {rhs}" + ) + if diff := diff_device(lhs, rhs): + all_diffs.append( + f"pair[{i}] differ in {diff}, where lhs is {lhs} and rhs is {rhs}" + ) + return all_diffs + + if all_diffs := diff_meta_pairs(lhs_list, rhs_list): + diff_str = "\n".join(all_diffs) + raise torch._dynamo.exc.UncapturedHigherOrderOpError( + f"Expected {lhs_name} and {rhs_name} to have same metadata but found:\n{diff_str}" + ) + + +# Thread-local flag to indicate we're inside HOP internal compilation +import threading + + +_hop_compile_tls = threading.local() + + +def _in_hop_compile() -> bool: + return getattr(_hop_compile_tls, "in_hop_compile", False) + + +@contextmanager +def setup_compilation_env(): + """ + Context manager that sets up proper environment and backend when invoking torch.compile + inside torch.export region or inside HOP. + """ + from torch._dynamo.backends.debugging import ( + make_eager_backend_with_torch_function_modes, + ) + from torch._dynamo.backends.registry import lookup_backend + from torch.fx.experimental.proxy_tensor import ( + _temp_remove_pre_dispatch_torch_function_mode, + ) + + old_in_hop_compile = getattr(_hop_compile_tls, "in_hop_compile", False) + _hop_compile_tls.in_hop_compile = True + try: + with ( + _set_compilation_env(), + torch._dynamo.utils.disable_cache_limit(), + _temp_remove_pre_dispatch_torch_function_mode() as pre_dispatch_mode, + _temp_remove_metadata_torch_function_mode() as metadata_mode, + ): + modes = [ + mode for mode in (pre_dispatch_mode, metadata_mode) if mode is not None + ] + if modes: + yield make_eager_backend_with_torch_function_modes(modes) + else: + yield lookup_backend("eager") + finally: + _hop_compile_tls.in_hop_compile = old_in_hop_compile + + +@contextmanager +def _set_compilation_env(): + _old_is_tracing = torch.fx._symbolic_trace._get_is_fx_tracing() + _old_allow_empty_graphs = torch._dynamo.config.allow_empty_graphs + _old_capture_scalar_outputs = torch._dynamo.config.capture_scalar_outputs + # The issue is tracked in https://github.com/pytorch/pytorch/issues/144360: when dynamo finds + # the top-level frame produces no graph, the default behavior is to fallback to eager. + # Then when it encounters an inner function, it will try to trace that function again, which is unnecessary. + # For while_loop, during inspecting the inner call, we trace into the python dispatcher + # logic, which is not tracable as of today. So the proper fix can be either 1. allow dispatch + # logic to be dynamo tracable or 2. fixing https://github.com/pytorch/pytorch/issues/144360. + # but it exposes some bugs in existing tests so we have to have a temporary flag to control + # the behavior, which allows dynamo to store an empty graph for a frame without falling back to eager + try: + # We need to turn off the is_fx_tracing_flag. Remove this flag check from dynamo + # once we are confident fx tracing works with dynamo. + torch.fx._symbolic_trace._set_is_fx_tracing(False) + # pyrefly: ignore [bad-assignment] + torch._dynamo.config.allow_empty_graphs = True + torch._dynamo.config.capture_scalar_outputs = True + yield + finally: + torch.fx._symbolic_trace._set_is_fx_tracing(_old_is_tracing) + torch._dynamo.config.allow_empty_graphs = _old_allow_empty_graphs + torch._dynamo.config.capture_scalar_outputs = _old_capture_scalar_outputs + + +# The invariant here is that we always trace the branch with fake tensor +def _maybe_fake_tracing(fn, inputs: list[Any], pre_dispatch): + fake_mode_det = None + for inp in pytree.tree_leaves(inputs): + if is_fake_tensor(inp): + fake_mode_det = maybe_get_fake_mode(inp) + break + + fake_mode: AbstractContextManager = nullcontext() + tracing_mode = "fake" + if fake_mode_det is not None: + fake_mode = fake_mode_det + tracing_mode = "real" + + # Note: we need to turn off proxy tensor mode to avoid tracing infra + # code that happens in make_fx e.g. we now call as_strided when wrapping tensor + # as fake tensor. + with fake_mode, disable_proxy_modes_tracing(): + gm = make_fx( + fn, + tracing_mode=tracing_mode, + pre_dispatch=pre_dispatch, + _error_on_data_dependent_ops=False, + )(*inputs) + if not isinstance(fake_mode, nullcontext) and fake_mode.shape_env is not None: # type: ignore[attr-defined] + insert_deferred_runtime_asserts( + gm, + fake_mode.shape_env, # type: ignore[attr-defined] + "hoo_maybe_fake_tracing", + export=True, # type: ignore[attr-defined] + ) + return gm + + +def potential_input_alias_or_mutation(gm, inputs, pre_dispatch=False): + try: + gm = _maybe_fake_tracing(gm, inputs, pre_dispatch) + except UnsupportedAliasMutationException: + # this can happen when nested cond_op is + # functionalized + return True + except Exception as e: + raise e + + example_inputs = [ + ph.meta.get("val", None) for ph in gm.graph.find_nodes(op="placeholder") + ] + ( + inp_inp_alias_map, + inp_out_alias_map, + out_out_alias_map, + inp_mutation, + ) = check_input_alias_and_mutation(gm, example_inputs) + return (inp_inp_alias_map, inp_out_alias_map, out_out_alias_map), inp_mutation + + +def analyze_potential_input_alias_or_mutation(name, aliases, input_mutations): + if any(len(a) > 0 for a in aliases): + # TODO: Investigate here further which node is exactly aliasing + raise RuntimeError( + f"{name} where aliases appear. " + + f"In particular, these inputs \ + {set(el for el_map in aliases if len(el_map.keys()) > 0 for el in el_map)} " # noqa: C401 + + "get aliased. Please ensure that this doesn't happen." + ) + if len(input_mutations): + # TODO: Investigate here further which node is exactly mutating the inputs + raise RuntimeError( + f"{name} where the inputs are mutated. " + + f"In particular, these nodes are mutating the inputs \ + {set(el for el in input_mutations)}." # noqa: C401 + + "Please ensure that this doesn't happen." + ) + + +def _has_potential_branch_input_mutation(gm, inputs, pre_dispatch=False): + ( + (_, _, _), + inp_mutation, + ) = potential_input_alias_or_mutation(gm, inputs, pre_dispatch) + + return len(inp_mutation) > 0 + + +def has_potential_input_alias_or_mutation(gm, inputs, pre_dispatch=False): + ( + ( + inp_inp_alias_map, + inp_out_alias_map, + out_out_alias_map, + ), + inp_mutation, + ) = potential_input_alias_or_mutation(gm, inputs, pre_dispatch) + return ( + any( + ( + len(inp_inp_alias_map) > 0, + len(inp_out_alias_map) > 0, + len(out_out_alias_map) > 0, + ) + ), + len(inp_mutation) > 0, + ) + + +def _collect_fake_inputs(inputs): + from torch._subclasses.fake_tensor import FakeTensor + + # Get the example values of the inputs. + inputs_fake: list[FakeTensor | torch.Tensor | int] = [] + for inp in inputs: + if isinstance(inp, (torch.fx.proxy.Proxy, torch.fx.node.Node)): + inp = inp.node if isinstance(inp, torch.fx.proxy.Proxy) else inp + if hasattr(inp, "meta"): + val = inp.meta["example_value"] + if isinstance(val, torch.Tensor): + if torch._C._functorch.is_batchedtensor( + val + ) or torch._C._functorch.is_functionaltensor(val): + # This case is for batched or functional tensors + # Unwrap the tensors + while torch._C._functorch.is_batchedtensor( + val + ) or torch._C._functorch.is_functionaltensor(val): + val = torch._C._functorch.get_unwrapped(val) + if not is_fake_tensor(val): + raise AssertionError( + f"Expected FakeTensor after unwrapping, got {type(val)}" + ) + inputs_fake.append(val) + elif is_traceable_wrapper_subclass(val): + for attr_name in val.__tensor_flatten__()[0]: + unwrapped_input = getattr(val, attr_name) + if not isinstance(unwrapped_input, torch.Tensor): + continue + if not is_fake_tensor(unwrapped_input): + raise AssertionError( + f"Expected FakeTensor after unwrapping, got {type(unwrapped_input)}" + ) + inputs_fake.append(unwrapped_input) + else: + # This is the standard case of a TensorVariable + if not is_fake_tensor(val): + raise AssertionError( + f"Expected FakeTensor, got {type(val)}" + ) + inputs_fake.append(val) + else: + # This case is for SymInts and other non-Tensor elements + if isinstance(val, torch.Tensor): + raise AssertionError(f"Expected non-Tensor, got {type(val)}") + inputs_fake.append(val) + else: + # This case is for ints + if not isinstance(inp, int): + raise AssertionError(f"Expected int, got {type(inp)}") + inputs_fake.append(inp) + + return inputs_fake + + +def _check_alias_and_mutation(graph_module, inputs_fake, name, pre_dispatch): + aliases, inp_mutation = has_potential_input_alias_or_mutation( + graph_module, inputs_fake, pre_dispatch=pre_dispatch + ) + if aliases: + raise RuntimeError(f"{name} might be aliasing the input or the output!") + if inp_mutation: + raise RuntimeError(f"{name} might be modifying the input!") + + +def unique_graph_id(proxy_mode, prefix): + """Returns a unique name and id for a graph to be added to a proxy_mode tracer""" + # There are probably better ways - I know that create_arg has some self incrementing name + # magic to it, but since we explicitly have to get the name for register_module, + # I was not sure how to do that. This kinda simulates it. + return unique_graph_name_with_root(proxy_mode.tracer.root, prefix) + + +def unique_graph_name_with_root( + root: torch.fx.GraphModule, prefix: str +) -> tuple[int, str]: + next_name = None + i = 0 + # pyrefly: ignore [bad-assignment] + while not next_name: + candidate = f"{prefix}_{i}" + if hasattr(root, candidate): + i += 1 + else: + next_name = candidate + return i, next_name + + +def _from_fun(t): + from torch._functorch.aot_autograd import from_fun + + if isinstance(t, torch.Tensor): + if t.dtype != torch.bool: + return torch.empty_strided( + t.size(), + t.stride(), + dtype=t.dtype, + requires_grad=t.requires_grad, + device=t.device, + ) + else: + # clone of a functional tensor produces a functional tensor + # but we want to avoid it so we clone a non-functional version + maybe_unfunc_t = t + if isinstance(t, FunctionalTensor): + torch._sync(t) + maybe_unfunc_t = from_fun(t) + elif torch._is_functional_tensor(t): + # need to handle both types of functionalization here: + # these are the tensors that came from the user, + # which could be either FunctionalTensorWrapper or FunctionalTensor + torch._sync(t) + maybe_unfunc_t = torch._from_functional_tensor(t) + # pyrefly: ignore[missing-attribute] + return maybe_unfunc_t.clone() + return t + + +def clone_outputs_aliasing_inputs(args): + input_storage = { + StorageWeakRef(arg._typed_storage()) + for arg in args + if isinstance(arg, torch.Tensor) + } + + def maybe_clone(t): + if ( + isinstance(t, torch.Tensor) + and StorageWeakRef(t._typed_storage()) in input_storage + ): + return t.clone() + return t + + return maybe_clone + + +def query_requires_grad(t: torch.Tensor) -> bool: + """requires_grad of ``t``, looking through a functional wrapper. + + A FunctionalTensor does not carry the autograd metadata of the tensor it + wraps, so asking it directly reports False for something that does require + grad. This matters when the joint is traced with functionalization active. + """ + if torch._is_functional_tensor(t): + t = torch._from_functional_tensor(t) + return t.requires_grad + + +def prepare_fw_with_masks(fn): + def fw_with_masks(*args): + fw_out = fn(*args) + return fw_out, [ + bool(isinstance(ret, torch.Tensor) and query_requires_grad(ret)) + for ret in fw_out + ] + + return fw_with_masks + + +def prepare_fw_with_masks_all_requires_grad(fn): + def fw_with_masks(*args): + fw_out = fn(*args) + # Note [force all outputs to be require grad] + # Instead of using the original fn, we set the output of original + # fn to all require grad. This is consistent with the behavior + # of autograd.Function, where if any one of the inputs requires grad + # all output will be require grad. This also makes the downstream + # require_gradness reasoning much easier. + if pytree.tree_any_only(torch.Tensor, lambda t: t.requires_grad, args): + fw_out = pytree.tree_map_only( + torch.Tensor, + lambda x: x.requires_grad_(True) if x.dtype.is_floating_point else x, + fw_out, + ) + + return fw_out, pytree.tree_map_only(torch.Tensor, query_requires_grad, fw_out) + + return fw_with_masks + + +# This function replaces None gradients with all-zero gradients. +# `None` gradients are problematic for CUDA graphs. Those gradients are +# replaced with an all-zero tensor for better optimization +def unmask_none_gradients(grads, operands): + allowed_types = (torch.Tensor, int, torch.SymInt) + if not all(isinstance(o, allowed_types) for o in operands): + raise AssertionError( + f"operands can only be of {allowed_types} but got {[type(o) for o in operands]}" + ) + + unmasked_grads = [] + for g, o in zip(grads, operands): + if g is not None: + unmasked_grads.append(g) + else: + # In case the operand is an int or a torch.SymInt, return None + # This can happen for lifted_arguments. E.g., the shapes of a dynamic tensor are lifted and passed + # as additional arguments + unmasked_grads.append( + torch.zeros_like(o) if isinstance(o, torch.Tensor) else None + ) + + return unmasked_grads + + +def _maybe_fake_prop_ignore_unbacked(fn, args): + with suspend_functionalization(), disable_functional_mode(): + with disable_proxy_modes_tracing(): + unfunc_args = [_from_fun(arg) for arg in args] + with ExitStack() as ctx_stack: + ctx_stack.enter_context( + torch.utils._python_dispatch._disable_current_modes() + ) + if (fake_mode := detect_fake_mode(unfunc_args)) is not None: + ctx_stack.enter_context(fake_mode) + if fake_mode.shape_env is not None: + ctx_stack.enter_context( + fake_mode.shape_env.ignore_fresh_unbacked_symbols() + ) + return fn(*unfunc_args) + + +def redirect_to_mode(hop: OperatorBase, mode): + """Utility for redispatching HOP to underlying mode + + Args: + hop: The HOP to redispatch + mode: The mode to redispatch to + + Returns: + A decorated function that implements the HOP for the given mode + """ + + @hop.py_impl(mode) + def impl(mode, *args, **kwargs): + return mode.__torch_dispatch__(hop, [], args, kwargs) + + return impl + + +# TODO: The parameter use_output_and_grad_bw is required because some operations +# that utilize this function, such as the while_loop, may require (grad, fwd_outputs) +def create_fw_bw_graph(fn, use_output_and_grad_bw, fw_inputs, fw_outputs): + from torch._functorch.aot_autograd import AOTConfig, create_joint + + # Note:[HOP create fw_bw graph] We create "clean" environments for make_fx by suspending all dispatch keys + # between Autograd and Python key. Currently, we only suspend functionalization but more can be + # added when required. Will encounter two problems if we don't suspend functionalization: + # + # 1. make_fx fails to capture operations on input: the inputs are wrapped as _to_functional_tensor_wrapper, + # but they will be unwrapped before entering ProxyTorchDispatchMode as part of the dispatching. + # However, it's the outside wrapper that tracer creates proxies for. This casuses tracer fail to + # fetch the proxy for the inputs and fail to capture any operations on them. + # + # 2. make_fx fails to capture output: the outputs after ProxyTorchDispatchMode are further + # wrapped as FunctionalTensorWrapper in Functionalize key after return. However, the tracer + # only associates the inner tensor with proxy in ProxyTorchDispatchMode. Therefore, + # when creating the output node, it fails to associate the wrapped tensor with its proxy. + # Instead, it will create _tensor_constant as output. + + dummy_aot_config = AOTConfig( + fw_compiler=None, # type: ignore[arg-type] + bw_compiler=None, # type: ignore[arg-type] + partition_fn=None, # type: ignore[arg-type] + decompositions={}, + num_params_buffers=0, + aot_id=0, + keep_inference_input_mutations=False, + ) + + example_grad = [_from_fun(out) for out in fw_outputs] + num_grads = len(example_grad) + fw_graph = _maybe_reenter_make_fx(fn)(*fw_inputs) + + def joint_fn(*joint_operands_grads): + if use_output_and_grad_bw: + grads = joint_operands_grads[0] + inputs = joint_operands_grads[1][-1:] + else: + grads = joint_operands_grads[:num_grads] + inputs = joint_operands_grads[num_grads:] + + joint = create_joint(prepare_fw_with_masks(fn), aot_config=dummy_aot_config) + _, grads = joint( + list(inputs), + [grad for grad in grads if grad is not None and grad.requires_grad], + ) + + # Unmask None gradients to all-zero gradients + unmasked_grads = unmask_none_gradients(grads, inputs) + + # In order to keep map functional for backward graph, + # we clone outputs that are aliasing inputs + maybe_clone = clone_outputs_aliasing_inputs(joint_operands_grads) + + return pytree.tree_map(maybe_clone, unmasked_grads) + + if use_output_and_grad_bw: + example_xs_out = list(fw_inputs) + list(fw_outputs) + joint_graph = _maybe_reenter_make_fx(joint_fn)( + (list(example_grad), list(example_xs_out)) + ) + else: + example_xs_out = list(fw_inputs) + joint_graph = _maybe_reenter_make_fx(joint_fn)( + *(list(example_grad) + list(example_xs_out)) + ) + + return fw_graph, joint_graph + + +def _unstack_pytree(xs): + flat_xs, inspec = pytree.tree_flatten(xs) + if not all(isinstance(xs, torch.Tensor) for xs in flat_xs): + raise RuntimeError(f"Leaves of xs must be Tensor {flat_xs}") + + if not all(xs.shape[0] == flat_xs[0].shape[0] for xs in flat_xs): + raise RuntimeError( + f"Leaves of xs must have same leading dimension size {[xs.shape for xs in flat_xs]}" + ) + + a = zip(*flat_xs) + + pytrees = [pytree.tree_unflatten(tuple, inspec) for tuple in a] + return pytrees + + +def _stack_pytree(pytrees): + flat_out = [] + out_spec = None + for pt in pytrees: + flat_pt, out_spec = pytree.tree_flatten(pt) + flat_out.append(flat_pt) + if out_spec is None: + raise AssertionError("out_spec cannot be None") + b = zip(*flat_out) + stacked_out = [] + for leaves in b: + if all(isinstance(leaf, torch.Tensor) for leaf in leaves): + stacked_out.append(torch.stack(leaves)) + elif all(leaf is None for leaf in leaves): + # Backward graph can return None output when forward inputs doesn't require grad. + # When we eagerly execute backward graph, we need to call _stack_pytree on its output, + # therefore we need to deal with None output. + stacked_out.append(None) # type: ignore[arg-type] + else: + raise RuntimeError(f"Cannot stack {leaves}.") + return pytree.tree_unflatten(stacked_out, out_spec) + + +# We cannot call save_for_backward for symints. This helper function +# can be used to save symints as direct attributes of ctx in autograd.Function. +# +# For example, if args = (x, y, s0, z, s1), +# save_values_for_backward will partition the args into two lists, and a bookkeeping list pos: +# partitioned_args[0] = (x, y, z) +# partitioned_args[1] = (s0, s1) +# pos = (0, 0, 1, 0, 1) +# pos list keeps track of which partition the args +# is partitioned into in order to recover it in saved_values. +# +# In saved_values, we can recover the original args by: +# iterating over the pos list and pop one item from the front of partitioned_args[pos[i]]. +# We use t_idx and s_idx to keep track of the next index of the item we are going to pop for the two lists. +def save_values_for_backward(ctx, args): + if not all( + isinstance(arg, (torch.Tensor, torch.SymInt, int, type(None), FakeScriptObject)) + or is_custom_class(type(arg)) + for arg in args + ): + raise AssertionError(f"Invalid arg types in {args}") + partitioned_args: list[Any] = [[], []] + pos = [] + for arg in args: + idx = 0 if isinstance(arg, torch.Tensor) else 1 + partitioned_args[idx].append(arg) + pos.append(idx) + + if hasattr(ctx, "non_tensor_args"): + raise AssertionError("ctx already has non_tensor_args attribute.") + if hasattr(ctx, "pos"): + raise AssertionError("ctx already has pos attribute.") + ctx.save_for_backward(*partitioned_args[0]) + ctx.non_tensor_args = partitioned_args[1] + ctx.pos = pos + + +def saved_values(ctx): + args = [] + t_idx = 0 + s_idx = 0 + saved_tensors = ctx.saved_tensors + for p in ctx.pos: + if p == 0: + args.append(saved_tensors[t_idx]) + t_idx += 1 + else: + args.append(ctx.non_tensor_args[s_idx]) + s_idx += 1 + if t_idx + s_idx != len(ctx.pos): + raise AssertionError( + f"t_idx ({t_idx}) + s_idx ({s_idx}) != len(ctx.pos) ({len(ctx.pos)})" + ) + return tuple(args) + + +def split_into_chunks(iterable: Sequence[Any], chunk_sizes: list[int]) -> list[Any]: + if sum(chunk_sizes) != len(iterable): + raise AssertionError( + f"the sum of all chunks ({sum(chunk_sizes)}) needs to match the length of the iterable ({len(iterable)})." + ) + elements = [] + idx = 0 + for size in chunk_sizes: + elements.append(iterable[idx : idx + size]) + idx += size + return elements + + +def _clone_aliasing_output(inputs: Sequence[Any], outputs: Sequence[Any]): + # For tensors whose grad is None, create zero tensors as gradients + # This invariant is useful for cudagraph. + + # Elimitate input-output, output-output aliasing + seen_input_storages = { + StorageWeakRef(t._typed_storage()) + for t in inputs + if isinstance(t, torch.Tensor) + } + seen_output_storages = set() + final_outputs = [] + for out in outputs: + if isinstance(out, torch.Tensor): + out_storage = StorageWeakRef(out._typed_storage()) + if ( + out_storage in seen_input_storages + or out_storage in seen_output_storages + ): + out = out.clone() + seen_output_storages.add(StorageWeakRef(out._typed_storage())) + final_outputs.append(out) + return final_outputs + + +def create_bw_fn( + fn: Callable, args: tuple[Any, ...], return_fw_outputs: bool = False +) -> Callable: + """ + For a fn that accepts flat inputs and returns flat outputs: + fw_out = fn(*args), + this function returns: + grad_args = bw_fn(*args_and_grad_output) + with the following invariants: + 1. args + fw_out has an 1-1 correspondence to args_and_grad_output + 2. grad_args has an 1-1 corresponsence to args + 3. for tensor arg whose requires_grad is False, its corresponding grad in + grad_args will be a zero tensor with the same shape. + """ + + from torch._functorch.aot_autograd import AOTConfig, create_joint + + # pyrefly: ignore [missing-module-attribute] + from torch._higher_order_ops.utils import prepare_fw_with_masks_all_requires_grad + + dummy_aot_config = AOTConfig( + fw_compiler=None, # type: ignore[arg-type] + bw_compiler=None, # type: ignore[arg-type] + partition_fn=None, # type: ignore[arg-type] + decompositions={}, + num_params_buffers=0, + aot_id=0, + keep_inference_input_mutations=False, + ) + n_primals = len(args) + + bw_fn = create_joint( + prepare_fw_with_masks_all_requires_grad(fn), aot_config=dummy_aot_config + ) + + def flat_fn(*args_and_grad_outs): + primals = args_and_grad_outs[:n_primals] + tangents = args_and_grad_outs[n_primals:] + fw_outs, grad_args = bw_fn(primals, tangents) + if len(args) != len(grad_args): + raise AssertionError( + f"Expected {len(args)} grad_args, got {len(grad_args)}" + ) + + # For tensors whose grad is None, create zero tensors as gradients + # This invariant is useful for cudagraph. + grad_args = [ + torch.zeros_like(arg) + if isinstance(arg, torch.Tensor) and grad is None + else grad + for grad, arg in zip(grad_args, primals) + ] + + final_grads = _clone_aliasing_output(args_and_grad_outs, grad_args) + if return_fw_outputs: + return *fw_outs, *final_grads + return final_grads + + return flat_fn + + +def get_dummy_aot_autograd_config(): + from torch._functorch.aot_autograd import AOTConfig + + return AOTConfig( + fw_compiler=None, # type: ignore[arg-type] + bw_compiler=None, # type: ignore[arg-type] + partition_fn=None, # type: ignore[arg-type] + decompositions={}, + num_params_buffers=0, + aot_id=0, + keep_inference_input_mutations=False, + ) + + +# Slices off the first element of a given dimension. Used to build a +# representative single slice for subgraph tracing of control-flow ops. +# When `dim` has size 0 (e.g. a zero-length scan) there is no real slice to +# take, so return an uninitialized tensor with `dim` removed. +def first_slice_copy(t: torch.Tensor, dim: int = 0) -> torch.Tensor: + if t.shape[dim] == 0: + shape = list(t.shape) + del shape[dim] + return t.new_zeros(shape) + return torch.select_copy(t, dim, 0) + + +# Returns a mask whether a list element is a tensor or not +def get_tensor_mask(tensor_list: Iterable[Any]) -> list[bool]: + return [bool(isinstance(v, torch.Tensor)) for v in tensor_list] + + +def mask_list( + mask: list[bool], inp: list[Any], other: list[Any] | None = None +) -> list[Any]: + # Masks elements on an `inp` list. + # If other is None, then the elements of the `inp` list where the mask is False are removed + # If other is not None, then the elements of the `inp` list where the mask is False are + # replaced with the elements of the `other` list + if len(mask) != len(inp): + raise AssertionError( + f"The length of the mask ({len(mask)}) needs to be identical to the length of the input ({len(inp)})" + ) + if other is not None: + if len(inp) != len(other): + raise AssertionError( + f"If an input and an other list is provided, they need to have the same length ({len(inp)} != {len(other)})" + ) + return [i if m else o for m, i, o in zip(mask, inp, other)] + else: + return [i for m, i in zip(mask, inp) if m] + + +def first_slice_copy_with_grad(li: Iterable[Any]) -> list[Any]: + # First_slice_copy does not keep the original requires_grad flag, + # but we need it for materialize_as_graph + # in order to compute the correct gradients + # The reason why first_slice_copy doesn't keep requires_grad flag is + # because it's called in torch.autograd.Function.backward/forward. + slc = [first_slice_copy(x).requires_grad_(x.requires_grad) for x in li] + return slc + + +# Reports the difference between meta of two tensors in a string +def diff_tensor_meta( + meta1: TensorMetadata, meta2: TensorMetadata, check_grad=True +) -> list[str]: + from torch.fx.experimental.symbolic_shapes import GuardOnDataDependentSymNode + + pair_diffs = [] + for meta_name in TensorMetadata._fields: + if not check_grad and meta_name == "requires_grad": + continue + val1 = getattr(meta1, meta_name) + val2 = getattr(meta2, meta_name) + try: + if val1 != val2: + pair_diffs.append(f"'{meta_name}: {val1} vs {val2}'") + except GuardOnDataDependentSymNode: + pair_diffs.append(f"'{meta_name}: {val1} vs {val2}'") + continue + return pair_diffs + + +# Note [lifted arg types in hop] +# For dynamoed hops, we automatically lift the free symbols in tensors as arguments. +# This has implications for the types of lifted args for different dispatch keys: +# 1. functionalization, FakeTensorMode, ProxyTorchDispatchMode, Autograd need to support torch.Symint +# lifted args because it's on the path of torch.compile(dynamic=True). +# 2. functionalization, FakeTensorMode, ProxyTorchDispatchMode, Autograd, CompositeExplicitAutograd need +# to support int arguments. In the eager run case, we re-trace the subgraph in AutogradKey, so inner +# hops may receive int inputs from the shape of outer tensor inputs. +# However, CompositeExplicitAutograd won't receive SymInt inputs because it only accepts real tensor inputs. +def validate_subgraph_args_types(lifted_args: tuple[Any, ...] | list[Any]): + allowed_types = (torch.Tensor, int, torch.SymInt) + if not all( + isinstance(arg, (torch.Tensor, int, torch.SymInt)) for arg in lifted_args + ): + raise AssertionError( + f"{lifted_args} can only be of {allowed_types} but got {tuple(type(arg) for arg in lifted_args)}" + ) + + +# TODO: Return a more detailed information as to which node +# causes a mutation or an alias. This may requires a per operator tensor version checking +def check_input_alias_and_mutation( + gm: torch.fx.GraphModule, + fake_args: list[FakeTensor], +) -> tuple[dict[int, int], dict[int, int], dict[int, int], list[int]]: + ( + inp_inp_alias_map, + inp_out_alias_map, + out_out_alias_map, + mutated_inputs, + ) = check_input_alias_and_mutation_return_outputs(gm)[:-1] + # pyrefly: ignore [bad-return] + return inp_inp_alias_map, inp_out_alias_map, out_out_alias_map, mutated_inputs + + +def _tensor_storage(t) -> StorageWeakRef: + return StorageWeakRef(t._typed_storage()) + + +def _get_example_value(n): + if not isinstance(n, torch.fx.Node): + return n + if "val" in n.meta: + return n.meta["val"] + if "example_value" in n.meta: + return n.meta["example_value"] + return None + + +def get_graph_output_example_values(gm: torch.fx.GraphModule) -> list[Any]: + output_node = gm.graph.find_nodes(op="output")[0] + return [_get_example_value(n) for n in pytree.tree_flatten(output_node.args[0])[0]] + + +def check_input_alias_and_mutation_return_outputs( + gm: torch.fx.GraphModule, +) -> tuple[ + dict[int, int], + dict[int, int], + dict[int, int], + list[int], + tuple[Any, ...] | list[Any], +]: + fake_args = [ + _get_example_value(n) + for n in gm.graph.find_nodes(op="placeholder") + if isinstance(n, torch.fx.Node) and "val" in n.meta + ] + outputs = get_graph_output_example_values(gm) + + # We need to analyze the original fake_args to detect + # inp-inp alias. + inp_storage_map = { + _tensor_storage(inp): i + for i, inp in enumerate(fake_args) + if isinstance(inp, torch.Tensor) + } + out_storage_map = { + _tensor_storage(out): i + for i, out in enumerate(outputs) + if isinstance(out, torch.Tensor) + } + inp_inp_alias_map = { + i: inp_storage_map[_tensor_storage(inp)] + for i, inp in enumerate(fake_args) + if isinstance(inp, torch.Tensor) and inp_storage_map[_tensor_storage(inp)] != i + } + out_out_alias_map = { + i: out_storage_map[_tensor_storage(out)] + for i, out in enumerate(outputs) + if isinstance(out, torch.Tensor) and out_storage_map[_tensor_storage(out)] != i + } + inp_out_alias_map = { + i: out_storage_map[_tensor_storage(inp)] + for i, inp in enumerate(fake_args) + if isinstance(inp, torch.Tensor) and _tensor_storage(inp) in out_storage_map + } + mutated_inputs = [] + for node in gm.graph.nodes: + if node.op == "call_function" and isinstance( + node.target, torch._ops.OpOverload + ): + for arg_node, arg_schema in zip(node.args, node.target._schema.arguments): + if arg_schema.is_write: + arg_val = _get_example_value(arg_node) + if not isinstance(arg_val, torch.Tensor): + raise AssertionError( + f"Expected arg_val to be a Tensor, got {type(arg_val)}" + ) + if _tensor_storage(arg_val) in inp_storage_map: + mutated_inputs.append(inp_storage_map[_tensor_storage(arg_val)]) + + return ( + inp_inp_alias_map, + inp_out_alias_map, + out_out_alias_map, + mutated_inputs, + outputs, + ) + + +registered_hop_fake_fns: dict[torch._ops.OpOverload, Callable] = {} + +# Set skip_cache=True for HOPs that should not be cached in FakeTensorMode +# (previously these ops were registered with .py_impl(FakeTensorMode)) and +# were never cached so we are just preserving original behaviour +hops_that_skip_faketensor_cache: set[torch._ops.OpOverload] = set() + + +F = TypeVar("F", bound=Callable) +_P = ParamSpec("_P") + + +@overload +def register_fake( + hop, fn: None = None, *, skip_cache: bool = ... +) -> Callable[[F], F]: ... + + +@overload +def register_fake(hop, fn: F, *, skip_cache: bool = ...) -> F: ... + + +def register_fake(hop, fn=None, *, skip_cache=False): + """ + Register a fake function for a HOP. This is conceptually equivalent of the + register_fake utility for the custom ops. The registered function is called + inside the fake_tensor _dispatch_impl. + + Set skip_cache=True to keep a HOP's fake output out of the FakeTensorMode + cache -- either to preserve the historical uncached behavior of + py_impl(FakeTensorMode), or because its outputs alias in ways the cache + cannot reconstruct (e.g. auto_functionalized). + """ + if hop in registered_hop_fake_fns: + raise AssertionError(f"hop {hop} already registered in registered_hop_fake_fns") + + def register(func: F) -> F: + from torch._subclasses.fake_tensor import FakeTensorMode + + redirect_to_mode(hop, FakeTensorMode) + + registered_hop_fake_fns[hop] = func + if skip_cache: + hops_that_skip_faketensor_cache.add(hop) + return func + + if fn is None: + return register + return register(fn) + + +class SubgraphCallableWrapper: + """ + Wraps a callable while preserving the original subgraph identity for + fake tensor caching. Without this, passing a plain closure to + invoke_subgraph would bypass the dispatch cache entirely. + """ + + def __init__(self, fn, subgraph): + self.fn = fn + self.subgraph = subgraph + self._boxed_call = getattr(subgraph, "_boxed_call", False) + + def __hash__(self): + return id(self.subgraph) + + def __call__(self, *args, **kwargs): + return self.fn(*args, **kwargs) + + +class FunctionalizeCtxWrapper(SubgraphCallableWrapper): + """Functionalizes a subgraph and optionally returns selected input updates. + + Each update is a new tensor; the original input is not mutated. + """ + + # Prevents PYTORCH_TEST_WITH_DYNAMO=1 test failures + @torch._disable_dynamo + def __init__(self, ctx, subgraph, mutated_input_indices=()): + super().__init__(subgraph, subgraph) + self.ctx = ctx + self.mutated_input_indices = mutated_input_indices + + def __repr__(self): + return f"FunctionalizeCtxWrapper on subgraph {self.subgraph})" + + def __call__(self, *args, **kwargs): + def append_mutated_inputs(fn): + if not self.mutated_input_indices: + return fn + + def wrapped(*args, **kwargs): + inputs = args[0] if self._boxed_call else args + # Snapshot before a boxed GraphModule clears its input list. + mutated_inputs = tuple(inputs[i] for i in self.mutated_input_indices) + # Dynamo normalizes invoke_subgraph outputs to tuples. + return (*fn(*args, **kwargs), *mutated_inputs) + + return wrapped + + if isinstance(self.subgraph, torch.fx.GraphModule): + if self._boxed_call: + # Not all callers respect _boxed_call (e.g. reenter_make_fx). + functionalized = self.ctx.functionalize( + append_mutated_inputs(self.subgraph) + ) + if len(args) == 1 and isinstance(args[0], list): + return functionalized(args[0]) + return functionalized(list(args)) + else: + # Running graph with interpreter is needed for propagating the stack_trace + with fx_traceback.preserve_node_meta(): + return self.ctx.functionalize( + append_mutated_inputs(torch.fx.Interpreter(self.subgraph).run) + )(*args, **kwargs) + functionalized = self.ctx.functionalize(append_mutated_inputs(self.subgraph)) + if self._boxed_call: + if len(args) == 1 and isinstance(args[0], list): + return functionalized(args[0]) + return functionalized(list(args)) + return functionalized(*args, **kwargs) + + +# A wrapper over HigherOrderOperator that also carries its schema +class HopInstance: + def __init__(self, op: HigherOrderOperator, schema: HopSchema): + if not isinstance(op, HigherOrderOperator): + raise AssertionError(f"Expected HigherOrderOperator, got {type(op)}") + self._op = op + # Using "_" to be consistent with how we access _schema of OpOverload + self._schema = schema + + def __call__(self, *args, **kwargs): + return self._op(*args, **kwargs) + + @staticmethod + def create(hop: HigherOrderOperator, *args, **kwargs): + return HopInstance(hop, hop.gen_schema(*args, **kwargs)) + + +# This call_op can be used to call a HopInstance with +# flat args and kwargs. We need to make use of the hop's schema's tree_spec +# to unflatten the args and kwargs before calling the hop. +def call_op(op: OpOverload | HopInstance, args, kwargs): + if isinstance(op, OpOverload): + return op(*args, **kwargs) + + if not isinstance(op, HopInstance): + raise AssertionError(f"Expected HopInstance, got {type(op)}") + schema = op._schema + bound_args = list(args) + bound_kwargs = {} + for arg in schema.arguments[len(bound_args) :]: + if arg.name not in kwargs: + raise AssertionError(f"arg {arg.name} not in kwargs: {kwargs}") + val = kwargs[arg.name] + if not arg.kwarg_only: + bound_args.append(val) + else: + bound_kwargs[arg.name] = val + + if schema.tree_spec is not None: + if len(bound_args) != len(schema.arguments) or len(bound_kwargs) != 0: + raise AssertionError( + f"Expected {len(schema.arguments)} bound_args and 0 bound_kwargs, " + f"got {len(bound_args)} and {len(bound_kwargs)}" + ) + args, kwargs = pytree.tree_unflatten(bound_args, schema.tree_spec) + return op(*args, **kwargs) + else: + if len(bound_args) + len(bound_kwargs) != len(schema.arguments): + raise AssertionError( + f"Expected {len(schema.arguments)} total args, " + f"got {len(bound_args)} + {len(bound_kwargs)}" + ) + return op(*bound_args, **bound_kwargs) + + +def materialize_as_graph( + fn: Callable, + args: tuple[Any, ...], + include_key_set: torch._C.DispatchKeySet | None = None, + exclude_key_set: torch._C.DispatchKeySet | None = None, + force_enable_grad=False, + subgraph_decomp_table: Mapping[OpOverload, Callable] | None = None, +) -> torch.fx.GraphModule: + if include_key_set is None: + include_key_set = torch._C._dispatch_tls_local_include_set() + if exclude_key_set is None: + exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + + @torch._dynamo.disable(recursive=True, reason=None) + def _materialize_as_graph_inner(): + from torch._guards import active_fake_mode + from torch.fx.experimental.proxy_tensor import _CURRENT_MAKE_FX_TRACER + + with suspend_functionalization(), disable_functional_mode(): + fake_mode = None + if _CURRENT_MAKE_FX_TRACER is not None: + fake_mode = _CURRENT_MAKE_FX_TRACER.fake_tensor_mode + if fake_mode is None: + fake_mode = active_fake_mode() + + with contextlib.ExitStack() as stack: + stack.enter_context( + torch.utils._python_dispatch._disable_current_modes() + ) + if fake_mode is not None: + stack.enter_context(fake_mode) + + with disable_proxy_modes_tracing(): + unfunc_t = [_from_fun(arg) for arg in args] + + stack.enter_context( + torch._C._ForceDispatchKeyGuard(include_key_set, exclude_key_set), + ) + if force_enable_grad: + stack.enter_context(torch.enable_grad()) + return _maybe_reenter_make_fx( + fn, subgraph_decomp_table=subgraph_decomp_table + )(*unfunc_t) + + gm = _materialize_as_graph_inner() + if gm is None: + raise AssertionError("materialize_as_graph returned None") + return gm + + +def materialize_callable_in_args(op: HopInstance, args, kwargs): + schema = op._schema + hop = op._op + flat_args, flat_spec = pytree.tree_flatten((args, kwargs)) + + def wrapped_fn(*flat_args): + return call_op(op, args, kwargs) + + # We need to trace the higher order op in order to materilaize the callable inputs that + # are a callable (e.g. after functionalization key) + gm = reenter_make_fx(wrapped_fn)(*flat_args) + hop_node = gm.graph.find_nodes(op="call_function", target=hop)[0] + arg_proxies = pytree.tree_leaves((hop_node.args, hop_node.kwargs)) + if not isinstance(schema, torch._C.FunctionSchema) or len(arg_proxies) != len( + schema.arguments + ): + raise AssertionError( + f"Expected FunctionSchema with {len(arg_proxies)} arguments" + ) + + # call_op preserves ordering of proxies via schema + materialized_args = [] + for i, proxy in enumerate(arg_proxies): + if ( + isinstance(proxy, torch.fx.Node) + and proxy.op == "get_attr" + and isinstance(getattr(gm, proxy.target), torch.fx.GraphModule) # type: ignore[arg-type] + ): + if not callable(flat_args[i]): + raise AssertionError( + f"Expected flat_args[{i}] to be callable for {schema}" + ) + materialized_args.append(getattr(gm, proxy.target)) # type: ignore[arg-type] + else: + materialized_args.append(flat_args[i]) + + return pytree.tree_unflatten(materialized_args, flat_spec) + + +def has_user_subclass(args, allowed_subclasses): + """Check if any tensor arguments are user subclasses. + + This is used to determine if tensor subclasses should get a chance to run + their own implementation first before falling back to the default implementation. + + Args: + args: Arguments to check (will be flattened with pytree) + allowed_subclasses: Tuple of allowed subclass types + + Returns: + True if user tensor subclasses are found, False otherwise + """ + flat_args, _ = pytree.tree_flatten(args) + + val = any( + isinstance(a, torch.Tensor) + and type(a) is not torch.Tensor + and not isinstance(a, allowed_subclasses) + for a in flat_args + ) + return val + + +def _has_gen_schema(op: HigherOrderOperator): + # There is an InvokeQuant argument we cannot gen_schema. + if op is torch.ops.higher_order.invoke_quant_packed: + return False + method = "gen_schema" + return hasattr(type(op), method) and getattr(type(op), method) is not getattr( + HigherOrderOperator, method + ) + + +def filter_with_masks(data: list[torch.Tensor | None], masks: list[bool]): + if len(data) != len(masks): + raise AssertionError( + f"data length ({len(data)}) != masks length ({len(masks)})" + ) + return [item for item, keep in zip(data, masks) if keep] + + +def fill_none_with_masks(data: list[torch.Tensor | None], masks: list[bool]): + data_iter = iter(data) + return [next(data_iter) if kept else None for kept in masks] + + +def create_fn_remove_none( + fn: Callable[_P, Any], +) -> tuple[Callable[_P, list[torch.Tensor]], list[bool]]: + """Wrap ``fn`` so its non-Tensor output leaves are dropped, and expose the + mask of which leaves survived. + + Returns ``(wrapped, mask)``: + - ``wrapped(*args)`` calls ``fn(*args)``, flattens the pytree result and + returns only its Tensor leaves as a list. + - ``mask`` is a list populated whenever ``wrapped`` runs -- one bool per + leaf, ``True`` where the leaf is a Tensor. Callers should read it + AFTER invoking ``wrapped`` (typically indirectly via + ``materialize_as_graph``), then pass it to ``fill_none_with_masks`` + to reconstruct the full output with ``None`` at the dropped slots. + + Used in HOP autograd impls in two places: + - Around a forward branch that may return non-Tensor leaves (None, + int/SymInt), so ``create_bw_fn``'s joint sees a tensor-only signature. + - Around the resulting backward joint whose grad list contains ``None`` + at non-differentiable input slots, so the materialized ``GraphModule`` + returns a uniform Tensor list. + """ + mask: list[bool] = [] + + @functools.wraps(fn) + def wrapped(*args, **kwargs): + leaves = pytree.tree_leaves(fn(*args, **kwargs)) + mask.clear() + mask.extend(isinstance(o, torch.Tensor) for o in leaves) + return filter_with_masks(leaves, mask) + + return wrapped, mask diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/while_loop.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/while_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..9805c91ec15e7252dd359ea8e48688ee787541c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/while_loop.py @@ -0,0 +1,1020 @@ +# mypy: allow-untyped-defs +import contextlib +import functools +from collections.abc import Callable + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.auto_functionalize import ( + can_auto_functionalize, + do_auto_functionalize_v2, +) +from torch._higher_order_ops.utils import ( + _check_alias_and_mutation, + _maybe_run_with_interpreter, + autograd_not_implemented, + check_meta_consistency, + fill_none_with_masks, + filter_with_masks, + get_graph_output_example_values, + HopInstance, + materialize_as_graph, + reenter_make_fx, + validate_subgraph_args_types, +) +from torch._ops import HigherOrderOperator +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.fx.experimental.proxy_tensor import ( + disable_proxy_modes_tracing, + ProxyTorchDispatchMode, + track_tensor_tree, +) + + +class WhileLoopOp(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("while_loop") + + def __call__( + self, + cond_fn: Callable, + body_fn: Callable, + carried_inputs: tuple[torch.Tensor | int | float | bool], + additional_inputs: tuple[torch.Tensor | torch.SymInt | int, ...], + /, + *, + mutated_arg_indices: str = "", + ): + if not isinstance(carried_inputs, (tuple, list)): + raise RuntimeError( + f"carried_inputs must be a tuple or list, got {type(carried_inputs)}" + ) + if not isinstance(additional_inputs, (tuple, list)): + raise RuntimeError( + f"additional_inputs must be a tuple or list, got {type(additional_inputs)}" + ) + + validate_subgraph_args_types(carried_inputs) + validate_subgraph_args_types(additional_inputs) + kwargs = {} + if mutated_arg_indices: + kwargs["mutated_arg_indices"] = mutated_arg_indices + # pyrefly: ignore [missing-attribute] + return super().__call__( + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + **kwargs, + ) + + # pyrefly: ignore [bad-override] + def gen_schema( + self, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + mutated_arg_indices="", + ): + from torch._higher_order_ops.schema import HopSchemaGenerator + from torch._higher_order_ops.utils import materialize_as_graph + + all_inputs = carried_inputs + additional_inputs + + cond_gm: torch.fx.GraphModule = ( + cond_fn + if isinstance(cond_fn, torch.fx.GraphModule) + else materialize_as_graph(cond_fn, all_inputs) + ) + body_gm: torch.fx.GraphModule = ( + body_fn + if isinstance(body_fn, torch.fx.GraphModule) + else materialize_as_graph(body_fn, all_inputs) + ) + + body_outputs = get_graph_output_example_values(body_gm) + mutated_inputs = ( + {int(i) for i in mutated_arg_indices.split(",") if i} + if mutated_arg_indices + else set() + ) + + schema_gen = HopSchemaGenerator(self) + schema_gen.add_arg("cond_fn", cond_gm) + schema_gen.add_arg("body_fn", body_gm) + + for idx, arg in enumerate(carried_inputs): + schema_gen.add_arg( + f"carried_input{idx}", arg, is_mutated=idx in mutated_inputs + ) + + for idx, arg in enumerate(additional_inputs): + additional_idx = len(carried_inputs) + idx + schema_gen.add_arg( + f"additional_input{idx}", + arg, + is_mutated=additional_idx in mutated_inputs, + ) + + for out in body_outputs: + schema_gen.add_output(out) + + schema_gen.add_schema_tree_spec( + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + ) + return schema_gen.gen_schema() + + +while_loop_op = WhileLoopOp() + + +def while_loop(cond_fn, body_fn, carried_inputs): + r""" + Run ``body_fn(*carried_inputs)`` while ``cond_fn(*carried_inputs)`` returns + a True scalar tensor. Returns the output of body_fn or initial + carried_inputs. + + .. warning:: + + `torch.while_loop` is a prototype feature in PyTorch. It has limited support for input and output types and + doesn't support training currently. Please look forward to a more stable implementation in a future version of PyTorch. + Read more about feature classification at: https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype + + `while_loop` is a structured control flow operator. It preserves the loop semantic across the torch.compile and torch.export. + + `while_loop` is equivalent to the following:: + + def while_loop(cond_fn, body_fn, carried_inputs): + val = carried_inputs + while cond_fn(*val): + val = body_fn(*val) + return val + + Args: + cond_fn (Callable): A callable function that returns a boolean Scalar tensor or a python boolean. + + body_fn (Callable): A callable function that takes the same inputs as `cond_fn` and returns a tuple of tensors or ints + + carried_inputs (Tuple of possibly nested dict/list/tuple of tensors or ints): A tuple of inputs to cond_fn and body_fn. + It's also the initial value of states that are carried across iterations. Note that when pass an integer as carry, + the corresponding return of while_loop will be another int with unknown values because we don't know how many + iterations while_loop will run. + + Example 1:: + + def cond_fn(iter, x): + return iter.sum() < 10 + + + def body_fn(iter, x): + return iter + 1, x.sin() + + + while_loop(cond_fn, body_fn, (torch.zeros(1), torch.randn(3, 4))) + + Example 2:: + + def cond_fn(int_iter, x): + return 2 * int_iter < x.shape[0] + + + def body_fn(int_iter, x): + return int_iter + 1, x + int_iter + + + while_loop(cond_fn, body_fn, (0, torch.randn(3, 4))) + + Restrictions: + + - body_fn must return tensors or int with the same metadata (e.g.shape, dtype) as inputs. + + - body_fn and cond_fn must not in-place mutate the carried_inputs. A clone before the mutation is required. + + - body_fn and cond_fn must not mutate python variables (e.g. list/dict) created outside of the body_fn. + + - body_fn and cond_fn's output cannot alias any of the inputs. A clone is required. + + - During inference, body_fn and cond_fn can in-place mutate tensors that are not + carried_inputs, such as module buffers and captured tensors from the enclosing scope. + + """ + + # Currently, additional_inputs is not a user-facing input. It will be automatically set in dynamo. + # parameters and buffers accessed in cond_fn or body_fn or tensor closures will become additional_inputs. + additional_inputs: tuple = () + + # The reason we flatten the output before calling into dynamo is that + # we want to create a consistent input ordering for cond_fn and body_fn. + # and we also want to the input ordering matches the output ordering. + # Also see NOTE: [why we cannot use "automatic" for while_loop] + # Construct flat cond_fn and flat_body_fn, which takes flattened inputs + flat_inputs, in_spec = pytree.tree_flatten((carried_inputs, additional_inputs)) + + def flat_cond_fn(*flat_args): + carried, additional = pytree.tree_unflatten(flat_args, in_spec) + return cond_fn(*carried, *additional) + + def flat_body_fn(*flat_args): + carried, additional = pytree.tree_unflatten(flat_args, in_spec) + return body_fn(*carried, *additional) + + if torch.compiler.is_dynamo_compiling(): + return while_loop_op(flat_cond_fn, flat_body_fn, tuple(flat_inputs), tuple()) + + def _validate_input(cond_fn, body_fn, carried_inputs): + from torch._higher_order_ops.utils import validate_subgraph_args_types + + if not callable(cond_fn) or not callable(body_fn): + raise RuntimeError("Expect cond_fn and body_fn to be callable.") + + validate_subgraph_args_types(flat_inputs) + + if not pytree.tree_all( + lambda t: isinstance(t, (torch.Tensor, torch.SymInt, int)), carried_inputs + ): + raise RuntimeError( + "Expect carried_inputs to be a tuple of possibly nested dict/list/tuple that only" + f"consists of tensor or int leaves, but got {carried_inputs}." + ) + + _validate_input(cond_fn, body_fn, carried_inputs) + + # Dynamo is expecting a callable with "__code__" attribute. + # We cannot directly pass cond_op to it. So we wrap it in a dummy function. + def _while_loop_op_wrapper(*args, **kwargs): + return while_loop_op(*args, **kwargs) + + from torch._higher_order_ops.utils import _hop_compile_and_call + + return _hop_compile_and_call( + _while_loop_op_wrapper, + (flat_cond_fn, flat_body_fn, tuple(flat_inputs), tuple()), + ) + + +@while_loop_op.py_impl(DispatchKey.CompositeExplicitAutograd) +def while_loop_dense( + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + stack_output=False, + mutated_arg_indices="", +): + carried_vals = carried_inputs + + def _validate_cond_output(pred): + if ( + isinstance(pred, torch.Tensor) + and pred.size() == torch.Size([]) + and pred.dtype == torch.bool + ) or isinstance(pred, bool): + return + else: + raise RuntimeError( + f"cond_fn must return a boolean scalar tensor or a boolean but got {pred}" + ) + + if not isinstance(carried_inputs, (tuple, list)): + raise RuntimeError( + f"carried_inputs must be a tuple or list but got {type(carried_inputs)}" + ) + + # Check condition and set up flag + should_loop = cond_fn(*carried_vals, *additional_inputs) + _validate_cond_output(should_loop) + + if not should_loop: + if stack_output: + return tuple( + val.unsqueeze(0).clone() if isinstance(val, torch.Tensor) else val + for val in carried_vals + ) + else: + return tuple( + val.clone() if isinstance(val, torch.Tensor) else val + for val in carried_vals + ) + + outputs: list[list[torch.Tensor]] = [[] for _ in carried_vals] + + while should_loop: + out = body_fn(*carried_vals, *additional_inputs) + if stack_output: + for i, o in enumerate(out): + outputs[i].append(o) + + if not isinstance(out, tuple): + raise AssertionError(f"body_fn should return a tuple but got {type(out)}") + if len(out) != len(carried_inputs): + raise AssertionError( + f"body_fn should return the same number of elements as carried_inputs, got {len(out)} vs {len(carried_inputs)}" + ) + carried_vals = out + + should_loop = cond_fn(*carried_vals, *additional_inputs) + + if stack_output: + outs: list[torch.Tensor] = [] + for out in outputs: + outs.append(torch.stack(out, dim=0)) + return tuple(outs) + + return carried_vals + + +@while_loop_op.py_autograd_impl +def while_loop_autograd( + cond_fn, body_fn, operands, additional_inputs, mutated_arg_indices="" +): + return WhileLoopAutogradOp.apply( + cond_fn, + body_fn, + len(operands), + len(additional_inputs), + *operands, + *additional_inputs, + ) + + +def _find_or_create_fake_mode() -> FakeTensorMode: + from torch.fx.experimental.symbolic_shapes import ShapeEnv + + fake_mode = torch._guards.detect_fake_mode() + if fake_mode is None: + fake_mode = FakeTensorMode(shape_env=ShapeEnv()) + + return fake_mode + + +def _create_unbacked_symint( + fake_mode: FakeTensorMode, ignore_fresh_unbacked_symbols: bool +) -> torch.SymInt: + if fake_mode is None or fake_mode.shape_env is None: + raise AssertionError("Must provide a fake_mode with shape_env.") + ctx = ( + contextlib.nullcontext() + if not ignore_fresh_unbacked_symbols + else fake_mode.shape_env.ignore_fresh_unbacked_symbols() + ) + with ctx: + return fake_mode.shape_env.create_unbacked_symint() + + +@while_loop_op.py_impl(ProxyTorchDispatchMode) +def while_loop_tracing( + mode, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + stack_output=False, + mutated_arg_indices="", +): + op = while_loop_stack_output_op if stack_output else while_loop_op + + def _trace_while_loop( + proxy_mode, + op, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + mutated_arg_indices, + ): + # NOTE [unspecialize int carry with unbacked symints] + # When we support int carry, we'll also need to support int output of body_fn because. + # previous iteration's output is next iteration's input and they must match. + # For carries, when we start tracing while_loop, they can be + # - constants e.g. (0, [1, 3]) + # - backed symints (x.shape[0], [x.shape[1] + x.stride[1], x.shape[2]]) + # - unbacked symints e.g. (u0, [u0 + u1, u2]) + # We choose the most conservative design: in all cases, we create new unbacked symints to trace the + # subgraph. It's possible to do some analysis on initial carry and the output of first + # iteration to determine a better range for the output unbacked symbol e.g. when input is an unbacked + # symint >= 0 before the while_loop but in general this is difficult because we don't know + # the number of iterations. Users would have to re-constrain the unbacked symint in subgraph if needed. + # + # For output of fake cond_fn, it could be constant bool or SymBool (e.g. return x.shape[0] < 4, + # where x.shape[0] can be either static of dynamic). In the case of constant bool, we should do a + # specialization (NYI). + + # For output of fake body_fn, it could be all three types though from user's point of view, + # they're all integers e.g. + + # init_carry = (0, s0, u1, t) + # def body_fn(u0, s0, u1, t): + # ... + # return (t.shape[0], t.shape[1], t.shape[2], y + 1) + # + # It may seem that a constant output isn't possible: users shouldn't write a while_loop + # that always return 0. But it could be that a shape is not set as dynamic properly (e.g. + # automatic dynamic hasn't been triggered). + # + # For this reason, we treat int, symint outputs in the same way: + # - they can match against any of int, symint carry + # - we unspecialize them with new unbacked symints in fake while_loop + # Similarly, we could do some analysis to refine the output ranges but it's easier to start with + # fresh unbacked symints. One surprising case can be: an input unbacked symint is constrained by + # users to be >= 0 (either before while_loop or inside body_fn) and it increments by 1 in each + # iteration. Ideally, we should know that the final output is >= 0 but we didn't constrain the + # unbacked symint output of subgraph as of today because this requires a smart range analysis. + fake_mode: FakeTensorMode = _find_or_create_fake_mode() + + def _unspecialize_carried_inputs(x): + if isinstance(x, (int, torch.SymInt)): + return _create_unbacked_symint( + fake_mode, ignore_fresh_unbacked_symbols=True + ) + # Note: [unspecialize constant tensor carry] + # We need to disable constant specialization for tensor inputs that become loop carries. + # Here's the problem: when a user creates a constant tensor e.g. torch.tensor(0), PyTorch calls aten.lift_fresh_copy + # to create a safe copy (avoiding aliasing issues), which creates a FakeTensor with constant=True. + # But when this FakeTensor becomes a loop carry, we have a problem: + # - Operations like .item() will read the constant value and bake it into the traced code + # - This is incorrect because carry variables change between loop iterations + # - The traced code would use the wrong constant value for all iterations + # Solution: We clone the constant tensors and mark the cloned tensor as non-constant so they won't + # be specialized to fixed values during tracing body_fn or cond_fn. + elif isinstance(x, torch.Tensor): + x = x.clone() + if hasattr(x, "constant") and x.constant is not None: + # pyrefly: ignore [missing-attribute] + x.constant = None + return x + + with disable_proxy_modes_tracing(): + unspecialized_carried_inputs = pytree.tree_map_only( + (int, torch.SymInt, torch.Tensor), + # For temporarily created unbacked symints, we don't need to bind them to any proxy + lambda x: _unspecialize_carried_inputs(x), + carried_inputs, + ) + + def produce_graph(fn): + cloned_carried_inputs = pytree.tree_map_only( + torch.Tensor, lambda x: x.clone(), unspecialized_carried_inputs + ) + return reenter_make_fx(fn)(*cloned_carried_inputs, *additional_inputs) + + cond_graph = produce_graph(cond_fn) + body_graph = produce_graph(body_fn) + + next_name = None + i = 0 + # pyrefly: ignore [bad-assignment] + while not next_name: + candidate = f"while_loop_cond_graph_{i}" + if hasattr(proxy_mode.tracer.root, candidate): + i += 1 + else: + next_name = candidate + cond_graph_name = next_name + body_graph_name = f"while_loop_body_graph_{i}" + if hasattr(proxy_mode.tracer.root, body_graph_name): + raise AssertionError( + f"proxy_mode.tracer.root already has attribute {body_graph_name}" + ) + + proxy_mode.tracer.root.register_module(cond_graph_name, cond_graph) + proxy_mode.tracer.root.register_module(body_graph_name, body_graph) + + args = (cond_graph, body_graph, carried_inputs, additional_inputs) + kwargs = {} + if not stack_output and mutated_arg_indices: + kwargs["mutated_arg_indices"] = mutated_arg_indices + + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) + + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", op, proxy_args, kwargs, name=op._name + ) + + out = op( + cond_graph, + body_graph, + unspecialized_carried_inputs, + additional_inputs, + **kwargs, + ) + return track_tensor_tree( + out, out_proxy, constant=None, tracer=proxy_mode.tracer + ) + + return _trace_while_loop( + mode, + op, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + mutated_arg_indices, + ) + + +@while_loop_op.py_impl(FakeTensorMode) +def while_loop_fake_tensor_mode( + mode, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + stack_output=False, + mutated_arg_indices="", +): + with mode: + # NOTE: [Handling unback symints in subgraph of while_loop] + # The idea is that the scope of unbacked symints are limited to the subgraph. + # + # We're implementing the fake tensor mode of while_loop operator. + # and we run body_fn once to get an fake output. + # Let's first consider the case that unbacked symints are tensor shapes: + # + # Case 1: + # if the unbacked symints is local to the subgraph e.g. + # def body_fn(it, x): + # nz = x.nonzero() + # return it+1. nz.sum() + # we can just ignore the newly created unbacked symints because it has + # no effect on the output of while_loop and it's tracked when we tracing. + # the subgraph. + # + # Case 2: + # if the unbacked symints are shape of output of while_loop e.g. + # def body_fn(it, x): + # nz = x.nonzero() + # return it+1, nz + # This will fail the shape check because in each iteration, the carried_input's shape + # must match the output shape as nz.shape contains newly allocated unbacked symint, this + # won't match the carried_input's shape. + # + # Case 3: + # if the unbacked symints are shape of carried_inputs e.g. + # nz = a.nonzero() + # body_fn(it, nz): + # return it+1. nz.sin() + 1, + # There's no new unbacked symints allocated in subgraph, so we're safe. + with mode.shape_env.ignore_fresh_unbacked_symbols(): + # body_fn return output with the same pytree and tensor meta data as carried_inputs + # so we could just return the output after one iteration. + body_outs = body_fn(*carried_inputs, *additional_inputs) + check_meta_consistency( + carried_inputs, + body_outs, + "carried_inputs", + "body_output", + include_contiguity=False, + ) + + if stack_output: + n_iter = _create_unbacked_symint(mode, ignore_fresh_unbacked_symbols=False) + if not all(isinstance(x, torch.Tensor) for x in carried_inputs): + raise AssertionError( + f"all carried_inputs must be tensors for stack_output, got {[type(x) for x in carried_inputs]}" + ) + fake_outputs = tuple( + out.clone() + .unsqueeze(0) + .repeat((n_iter,) + tuple(1 for _ in range(out.dim()))) + for out in body_outs + ) + return pytree.tree_map_only( + (int, torch.SymInt), + # For while_loop's unbacked symint output, we want them to be bound + # to the proxy of while_loop's output. + lambda _: _create_unbacked_symint( + mode, ignore_fresh_unbacked_symbols=False + ), + fake_outputs, + ) + + # See NOTE [unspecialize int carry with unbacked symints] + return pytree.tree_map_only( + (int, torch.SymInt), + # For while_loop's unbacked symint output, we want them to be bound + # to the proxy of while_loop's output. + lambda _: _create_unbacked_symint( + mode, ignore_fresh_unbacked_symbols=False + ), + body_outs, + ) + + +@while_loop_op.py_functionalize_impl +def while_loop_func( + ctx, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + stack_output=False, + mutated_arg_indices="", +): + op = while_loop_stack_output_op if stack_output else while_loop_op + # For now, we only support auto-functionalization for while_loop when using python + # functionalization mode + if not stack_output and hasattr(ctx, "mode"): + hop_instance = HopInstance.create( + op, + cond_fn, + body_fn, + carried_inputs, + additional_inputs, + mutated_arg_indices=mutated_arg_indices, + ) + if can_auto_functionalize(hop_instance): + return do_auto_functionalize_v2( + ctx.mode, + hop_instance, + tuple( + pytree.tree_flatten( + (cond_fn, body_fn, carried_inputs, additional_inputs) + )[0] + ), + {}, + ) + + unwrapped_carried_inputs = ctx.unwrap_tensors(carried_inputs) + unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs) + unwrapped_inputs = unwrapped_carried_inputs + unwrapped_additional_inputs + with ctx.redispatch_to_next(): + functional_cond_fn = ctx.functionalize(_maybe_run_with_interpreter(cond_fn)) + functional_body_fn = ctx.functionalize(_maybe_run_with_interpreter(body_fn)) + pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch + for fn, fn_name in [ + (cond_fn, "cond_fn"), + (body_fn, "body_fn"), + ]: + _check_alias_and_mutation(fn, unwrapped_inputs, fn_name, pre_dispatch) + op_kwargs = {} + if not stack_output and mutated_arg_indices: + op_kwargs["mutated_arg_indices"] = mutated_arg_indices + ret = op( + functional_cond_fn, + functional_body_fn, + unwrapped_carried_inputs, + unwrapped_additional_inputs, + **op_kwargs, + ) + return ctx.wrap_tensors(ret) + + +class WhileLoopStackOutputOp(HigherOrderOperator): + """ + while_loop_stack_output is a variant of while_loop that returns a stack of outputs. + Its semantic can be illurated using python code as: + def while_loop_stack_output(cond_fn, body_fn, carried_inputs, additional_inputs): + outs = [] + while cond_fn(*carried_inputs, *additional_inputs): + out = body_fn(*carried_inputs, *additional_inputs) + outs.append(out) + return torch.stack(outs) + + It's useful for supporting autograd of while_loop. + """ + + def __init__(self) -> None: + super().__init__("while_loop_stack_output") + + def __call__( + self, + cond_fn: Callable, + body_fn: Callable, + carried_inputs: tuple[torch.Tensor | int | float | bool], + additional_inputs: tuple[torch.Tensor | torch.SymInt | int, ...], + /, + ): + if not isinstance(carried_inputs, (tuple, list)): + raise RuntimeError( + f"carried_inputs must be a tuple or list, got {type(carried_inputs)}" + ) + if not isinstance(additional_inputs, (tuple, list)): + raise RuntimeError( + f"additional_inputs must be a tuple or list, got {type(additional_inputs)}" + ) + + validate_subgraph_args_types(carried_inputs) + validate_subgraph_args_types(additional_inputs) + # pyrefly: ignore [missing-attribute] + return super().__call__(cond_fn, body_fn, carried_inputs, additional_inputs) + + +# Note [while_loop autograd] +# Consider wthe following while_loop that can be visualized as: +# additional_inputs +# ┌─────┬─────┼─────┬─────┐ +# | | | | | +# ↓ ↓ ↓ ↓ ↓ +# x ──→ y0 ─→ y1 ─→ y2 ─→ y3 ─→ y4 +# +# The backward can be visualized as follows: +# +# g_additional_inputs +# ┌──────┬──────┼──────┬──────┐ +# | | | | | +# | | | | | +# gx <── gy0 <─ gy1 <─ gy2 <─ gy3 <─ gy4 +# +# We can compute gx using chain rule: +# +# gx = gy0 * bw(y0, x), +# +# where gy0 denotes the gradient of loss with respect to y0, and bw(y0, x) denotes the gradient of y0 with +# respect to x. Note that bw can be computed from forward body_fn easily using torch.autograd.grad. +# We could substitute the unknowns gy0, gy1, ..., with chain rule until gy4: +# +# gx = gy1 * bw(y1, y0) * bw(y0, x) +# = gy2 * bw(y2, y1) * bw(y1, y0) * bw(y0, x) +# = ... +# = gy4 * bw(y4, y3) * bw(y3, y2) * bw(y2, y1) * bw(y1, y0) * bw(y0, x) +# +# since gy4 is the gradient of the final output, which is given as the backward input, we've got a formula +# to compute gx. A abbr for the formula is: gy4 * bw43210x +# +# In a similar way, we can compute g_additional_inputs using chain rule: +# +# g_additional_inputs = gy0 * bw(y0, addi) + gy1 * bw(y1, addi) + gy2 * bw(y2, addi) + ... + gy4 * bw(y4, addi) +# +# Notice that gy0 = gy4 * bw43210, gy1 = gy4 * bw4321 etc, we now also get a formula for g_additional_inputs. +# +# Implementation: +# The idea of implementation is to construct a while_loop to calculate both gx and g_additional_inputs. +# Specifically, we can implement the backward of while_loop with as follows: +# +# def cond_fn(idx, grad_carries, grad_additional_inputs, fw_additional_inputs, fw_inps): +# return idx < fw_inps.size(0) +# +# def body_fn(idx, grad_carries, grad_additional_inputs, fw_additional_inputs, fw_inps): +# reversed_idx = fw_inps.size(0) - 1 - idx +# next_grad_carry, next_grad_additional_inputs = bw(fw_inps[reversed_idx], fw_additional_inputs, grad_carries) +# return idx + 1, next_grad_carry, next_grad_additional_inputs + grad_additional_inputs +# +# idx = 0 +# init_grad_carries = grads +# init_grad_additional_inputs = torch.zeros_like(g_additional_inputs) +# fw_inps = torch.cat([ctx.fw_carried_inputs, fw_outputs[:-1]]) +# while_loop(cond_fn, body_fn, (idx, init_grad_carries, init_grad_additional_inputs,), (fw_additional_inputs, fw_inps)) + + +class WhileLoopAutogradOp(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward( + ctx, + cond_fn, + body_fn, + num_carried_inputs, + num_additional_inputs, + *carries_and_inputs, + ): + from torch._higher_order_ops.scan import split_into_chunks + + carries, additional_inputs = split_into_chunks( + carries_and_inputs, [num_carried_inputs, num_additional_inputs] + ) + with torch._C._AutoDispatchBelowAutograd(): + fw_outputs = while_loop_stack_output_op( + cond_fn, body_fn, carries, additional_inputs + ) + + if hasattr(ctx, "fw_cond_fn"): + raise AssertionError("ctx already has fw_cond_fn attribute") + if hasattr(ctx, "fw_body_fn"): + raise AssertionError("ctx already has fw_body_fn attribute") + if hasattr(ctx, "carries"): + raise AssertionError("ctx already has carries attribute") + if hasattr(ctx, "additional_inputs"): + raise AssertionError("ctx already has additional_inputs attribute") + if hasattr(ctx, "fw_outputs"): + raise AssertionError("ctx already has fw_outputs attribute") + ctx.fw_cond_fn = cond_fn + ctx.fw_body_fn = body_fn + ctx.carries = carries + ctx.additional_inputs = additional_inputs + ctx.fw_outputs = fw_outputs + loop_count = None + # pyrefly: ignore [bad-assignment] + for out in fw_outputs: + if isinstance(out, torch.Tensor): + if loop_count is not None: + if out.size(0) != loop_count: + raise AssertionError( + f"inconsistent loop_count: expected {loop_count}, got {out.size(0)}" + ) + else: + loop_count = out.size(0) + if loop_count is None: + raise AssertionError( + "loop_count must not be None after processing fw_outputs" + ) + + # Remove the loop_count from pending_fresh_unbacked_symbols + # because it's not part of forward output and it's impossible + # to bind it to a proxy in forward graph anyways. + if ( + isinstance(loop_count, torch.SymInt) + and (shape_env := loop_count.node.shape_env) + and loop_count in shape_env.pending_fresh_unbacked_symbols + ): + shape_env.pending_fresh_unbacked_symbols.remove(loop_count) + + # Even when body function is not executed, we clone and unsqueeze the input + # to avoid the aliasing, therefore loop_count is always >= 1 + torch._check(loop_count >= 1) + # We snapshot the dispatch keys in forward for materializing the + # the bw_graph in backward. + ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set() + ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set() + if len(fw_outputs) <= 0: + raise AssertionError("fw_outputs shouldn't be empty") + # Only the last of the output fw_outputs need to be returned + return tuple(ckp[-1] for ckp in fw_outputs) + + @staticmethod + def backward(ctx, *grads): + from torch._higher_order_ops.cond import create_bw_fn + from torch._higher_order_ops.scan import split_into_chunks + + # set up single step bw fn + bw_body_fn = create_bw_fn(ctx.fw_body_fn, ctx.carries + ctx.additional_inputs) + # Note [Handle inputs that're not differentiable] + # When a forward input is non-differentiable e.g. a symint or an integer tensor, their gradients + # will be None. However, we don't want to return None in the subgraph because this complicates the + # inductor codegen, where we need to do a non-uniform treatment for None and tensors. + # So we set up masks and filter the None gradients so that only tensors are returned from each step. + carries_tensor_masks = [ + bool(isinstance(t, torch.Tensor) and t.dtype.is_floating_point) + for t in ctx.carries + ] + additional_inputs_tensor_masks = [ + bool(isinstance(t, torch.Tensor) and t.dtype.is_floating_point) + for t in ctx.additional_inputs + ] + + init_idx = torch.zeros((), dtype=torch.int64) + # Autograd can pass view gradients. The generated backward while_loop + # needs stable carry metadata across iterations, so canonicalize tensor + # gradients before they become carries. + init_grad_carries = tuple( + grad.clone(memory_format=torch.contiguous_format) + if isinstance(grad, torch.Tensor) + else grad + for grad in filter_with_masks(grads, carries_tensor_masks) # type: ignore[arg-type] + ) + init_grad_additional_inputs = tuple( + torch.zeros_like(t) + for need_keep, t in zip( + additional_inputs_tensor_masks, ctx.additional_inputs + ) + if need_keep + ) + # We need to the forward inputs to each iteration to compute the backward + # which is the concatenation of first iteration input i.e. ctx.carries and all iterations' + # output except the last iteration. + fw_carries = [ + torch.cat([carry.unsqueeze(0), carries[:-1]]) + for carry, carries in zip(ctx.carries, ctx.fw_outputs) + ] + for fw_carry, carry in zip(fw_carries, ctx.carries): + fw_carry.requires_grad_(carry.requires_grad) + + _, spec = pytree.tree_flatten( + ( + init_idx, + init_grad_carries, + init_grad_additional_inputs, + ctx.fw_outputs, + ctx.additional_inputs, + ) + ) + + def cond_fn(*flat_args): + ( + idx, + grad_carries, + grad_additional_inputs, + fw_carries, + additional_inputs, + ) = pytree.tree_unflatten(flat_args, spec) + if not isinstance(fw_carries[0], torch.Tensor): + raise AssertionError( + f"expected fw_carries[0] to be torch.Tensor, got {type(fw_carries[0])}" + ) + # excluding the last iteration's output + return idx < fw_carries[0].size(0) + + def body_fn(*flat_args): + ( + idx, + grad_carries, + grad_additional_inputs, + fw_carries, + additional_inputs, + ) = pytree.tree_unflatten(flat_args, spec) + reversed_idx = fw_carries[0].size(0) - idx - 1 + selected_fw_carries = [ + ckp.select(0, reversed_idx.item()) for ckp in fw_carries + ] + cur_grad_carries, cur_grad_additional_inputs = split_into_chunks( + bw_body_fn(*selected_fw_carries, *additional_inputs, *grad_carries), + [len(ctx.carries), len(ctx.additional_inputs)], + ) + if not all(isinstance(t, torch.Tensor) for t in cur_grad_carries): + raise AssertionError( + f"all cur_grad_carries must be tensors, got {[type(t) for t in cur_grad_carries]}" + ) + cur_grad_carries_tensors = filter_with_masks( + cur_grad_carries, carries_tensor_masks + ) + cur_grad_additional_inputs_tensors = filter_with_masks( + cur_grad_additional_inputs, additional_inputs_tensor_masks + ) + return ( + idx + 1, + *cur_grad_carries_tensors, + *( + cur_grad + grad + for cur_grad, grad in zip( + cur_grad_additional_inputs_tensors, grad_additional_inputs + ) + ), + ) + + args_single_step_bw = ( + init_idx, + *init_grad_carries, + *init_grad_additional_inputs, + *fw_carries, + *ctx.additional_inputs, + ) + + cond_gm = materialize_as_graph( + cond_fn, + args_single_step_bw, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + + body_gm = materialize_as_graph( + body_fn, + args_single_step_bw, + ctx._fw_include_key_set, + ctx._fw_exclude_key_set, + force_enable_grad=True, + ) + + _, final_grad_carries, final_grad_additional_inputs = split_into_chunks( + while_loop_op( + # pyrefly: ignore [bad-argument-type] + cond_gm, + # pyrefly: ignore [bad-argument-type] + body_gm, + # pyrefly: ignore [bad-argument-type] + ( + init_idx, + *init_grad_carries, + *init_grad_additional_inputs, + ), + (*fw_carries, *ctx.additional_inputs), + ), + [1, len(init_grad_carries), len(init_grad_additional_inputs)], + ) + return ( + None, + None, + None, + None, + *fill_none_with_masks(final_grad_carries, carries_tensor_masks), + *fill_none_with_masks( + final_grad_additional_inputs, additional_inputs_tensor_masks + ), + ) + + +while_loop_stack_output_op = WhileLoopStackOutputOp() + +while_loop_stack_output_op.py_impl(DispatchKey.CompositeExplicitAutograd)( + functools.partial(while_loop_dense, stack_output=True) +) + +while_loop_stack_output_op.py_impl(ProxyTorchDispatchMode)( + functools.partial(while_loop_tracing, stack_output=True) +) + +while_loop_stack_output_op.py_impl(FakeTensorMode)( + functools.partial(while_loop_fake_tensor_mode, stack_output=True) +) + +while_loop_stack_output_op.py_functionalize_impl( + functools.partial(while_loop_func, stack_output=True) +) + +while_loop_stack_output_op.py_autograd_impl( + autograd_not_implemented(while_loop_stack_output_op, deferred_error=True) +) diff --git a/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/wrap.py b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/wrap.py new file mode 100644 index 0000000000000000000000000000000000000000..cf3711ffecf6042c092364c04c921eb155890dd3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_higher_order_ops/wrap.py @@ -0,0 +1,547 @@ +# mypy: allow-untyped-defs +import inspect +import itertools +import logging +import weakref +from collections.abc import Callable +from typing import Any +from typing_extensions import ParamSpec, TypeVar + +import torch +import torch.utils._pytree as pytree +from torch._C import DispatchKey +from torch._higher_order_ops.utils import ( + redirect_to_mode, + reenter_make_fx, + register_fake, +) +from torch._logging import warning_once +from torch._ops import HigherOrderOperator +from torch.fx import GraphModule +from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree +from torch.types import _dtype +from torch.utils._debug_mode import DebugMode +from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +log = logging.getLogger(__name__) + + +uid = itertools.count(1) + + +# Used for testing the HigherOrderOperator mechanism +class Wrap(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("wrap") + + def __call__( + self, func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs + ) -> _R: + # Dynamo already traces the body of HigherOrderOp beforehand when it + # so no need to trace into it. + import torch._dynamo # noqa: F401 + from torch._dynamo import disable + + @disable + def wrapper(): + result = func(*args, **kwargs) + return result + + return wrapper() + + +wrap = Wrap() + + +class InductorCompiledCode(HigherOrderOperator): + """ + Defines a HOP for wrapping inductor compiled functions as a callable. + When used with torch.compile via "wrap_inductor_compiled_regions", + this HOP will automatically be wrapped and redirect various torch dispatch modes. + """ + + def __init__(self) -> None: + super().__init__("inductor_compiled_code") + self._boxed_arg_indices = (1,) + + def __call__(self, func, inputs, *, name: str | None = None): + # pyrefly: ignore [missing-attribute] + return super().__call__(func, inputs, name=name) + + +inductor_compiled_code = InductorCompiledCode() +inductor_compiled_code.fallthrough(DispatchKey.AutogradCPU) +inductor_compiled_code.fallthrough(DispatchKey.AutogradCUDA) + + +_inductor_compiled_callable_id = itertools.count() + + +class InductorCompiledCallable: + """ + A wrapper class that holds both the Inductor-compiled callable and the + original FX graph for fake tensor propagation. + Each instance gets a globally unique idx at creation (via atomic itertools.count). + """ + + def __init__( + self, + compiled_callable, + original_gm=None, + compile_region_name: str | None = None, + ): + self.idx = next(_inductor_compiled_callable_id) + self.compiled_callable = compiled_callable + self.original_gm = original_gm + self.compile_region_name = compile_region_name + # AOT autograd needs this to know inputs are passed as a list + self._boxed_call = True + + def __call__(self, inputs): + return self.compiled_callable(inputs) + + +class InductorCodeSideTable: + """ + Side table for storing InductorCompiledCallable objects. + + We cannot put InductorCompiledCallable objects directly into the FX graph + as graph nodes do not support arbitrary objects. We use this side table + and pass callable.idx instead. + + Uses WeakValueDictionary so entries are automatically removed when + the InductorCompiledCallable is no longer referenced elsewhere + (e.g. after dynamo.reset() drops the compiled code cache). + """ + + def __init__(self): + self.id_to_callable: weakref.WeakValueDictionary[ + int, InductorCompiledCallable + ] = weakref.WeakValueDictionary() + + def add_callable(self, callable_obj: InductorCompiledCallable) -> int: + """Register a callable and return its idx.""" + self.id_to_callable[callable_obj.idx] = callable_obj + return callable_obj.idx + + def get_callable(self, idx: int) -> InductorCompiledCallable: + """Get the callable at the given index.""" + if idx not in self.id_to_callable: + raise AssertionError(f"Invalid inductor code index: {idx}") + return self.id_to_callable[idx] + + def __getstate__(self): + # Convert WeakValueDictionary to regular dict for pickling + return {"id_to_callable": dict(self.id_to_callable)} + + def __setstate__(self, state): + self.id_to_callable = weakref.WeakValueDictionary(state["id_to_callable"]) + + def reset_table(self) -> None: + """Reset the table.""" + self.id_to_callable = weakref.WeakValueDictionary() + + +inductor_code_side_table = InductorCodeSideTable() + + +def _resolve_inductor_callable( + func: int | InductorCompiledCallable, +) -> InductorCompiledCallable: + """ + Resolve func to an InductorCompiledCallable. + + func is either an InductorCompiledCallable directly (from post_compile) + or an int index into the side table (from a traced FX graph node). + """ + if isinstance(func, int): + return inductor_code_side_table.get_callable(func) + if not isinstance(func, InductorCompiledCallable): + raise AssertionError(f"Unexpected func type: {type(func)}") + return func + + +@inductor_compiled_code.py_impl(DispatchKey.CompositeExplicitAutograd) +def inductor_compiled_code_impl(func, inputs, *, name=None): + resolved = _resolve_inductor_callable(func) + return resolved.compiled_callable(inputs) + + +redirect_to_mode(inductor_compiled_code, DebugMode) +redirect_to_mode(inductor_compiled_code, _CachingTorchDispatchMode) +redirect_to_mode(inductor_compiled_code, _CachedTorchDispatchMode) + + +@register_fake(inductor_compiled_code) +def inductor_compiled_code_fake(func, inputs, *, name=None): + resolved = _resolve_inductor_callable(func) + if resolved.original_gm is None: + raise RuntimeError( + "inductor_compiled_code original_gm is None — the compiled graph may " + "have been serialized without it. Recompile to restore." + ) + # Run the original FX graph under FakeTensorMode to re-derive output + # shapes, dtypes, and aliasing from the input fake tensors. + return tuple(resolved.original_gm(*inputs)) + + +@inductor_compiled_code.py_functionalize_impl +def inductor_compiled_code_functionalize(ctx, func, inputs, *, name=None): + # Unwrap the functional tensors to get the underlying tensors + unwrapped_inputs = ctx.unwrap_tensors(inputs) + + # Redispatch to the next handler in the dispatch chain + with ctx.redispatch_to_next(): + kwargs = {"name": name} if name is not None else {} + result = inductor_compiled_code(func, unwrapped_inputs, **kwargs) + return ctx.wrap_tensors(result) + + +@inductor_compiled_code.py_impl(ProxyTorchDispatchMode) +def inductor_compiled_code_proxy(mode, func, inputs, *, name=None): + resolved = _resolve_inductor_callable(func) + + # Run the fake impl to get example outputs for tracing + kwargs = {"name": name} if name is not None else {} + example_out = inductor_compiled_code(func, inputs, **kwargs) + + # Register in side table so the FX node stores a serializable int + callable_idx = inductor_code_side_table.add_callable(resolved) + + proxy_inputs = pytree.tree_map(mode.tracer.unwrap_proxy, inputs) + + out_proxy = mode.tracer.create_proxy( + "call_function", + inductor_compiled_code, + (callable_idx, proxy_inputs), + kwargs, + ) + + return track_tensor_tree(example_out, out_proxy, constant=None, tracer=mode.tracer) + + +class WrapWithSetGradEnabled(HigherOrderOperator): + def __init__(self) -> None: + super().__init__("wrap_with_set_grad_enabled") + + def __call__( + self, + enable_grad: bool, + wrapped_func: Callable[_P, _R], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> _R: + # Dynamo already traces the body of HigherOrderOp beforehand when it + # so no need to trace into it. + import torch._dynamo + from torch._dynamo import disable + + @disable + def wrapper(): + prev = torch.is_grad_enabled() + torch.set_grad_enabled(enable_grad) + res = wrapped_func(*args, **kwargs) + torch.set_grad_enabled(prev) + return res + + return wrapper() + + +wrap_with_set_grad_enabled = WrapWithSetGradEnabled() + + +class WrapWithAutocast(HigherOrderOperator): + def __init__(self): + super().__init__("wrap_with_autocast") + + def __call__( + self, + device_type: str, + dtype: _dtype | None, + enabled: bool, + cache_enabled: bool | None, + wrapped_func: Callable[_P, _R], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> _R: + # Dynamo already traces the body of HigherOrderOp beforehand when it + # so no need to trace into it. + import torch._dynamo + from torch._dynamo import disable + + @disable + def wrapper(): + with torch.autocast(device_type, dtype, enabled, cache_enabled): + return wrapped_func(*args, **kwargs) + + return wrapper() + + +wrap_with_autocast = WrapWithAutocast() + + +# This HOP allows you to bypass dynamo tracing of the wrapper function while +# still tracing the inner function. +# Takes two callables: The first, `wrapper_fn`, accepts `inner_fn` and returns a +# callable with the same signature. The second is the `inner_fn` itself. Any +# extra *args and **kwargs are forwarded to `wrapper_fn(inner_fn)` when it is +# executed. +class DynamoBypassingWrapper(HigherOrderOperator): + def __init__(self): + super().__init__("dynamo_bypassing_wrapper") + + def __call__( + self, + wrapper_fn_or_key, + inner_fn, + *args, + **kwargs, + ): + # Dynamo already traces the body of HigherOrderOp beforehand when it + # so no need to trace into it. + import torch._dynamo + from torch._dynamo import disable + + is_compiling = isinstance(wrapper_fn_or_key, str) + if is_compiling: + if not isinstance(inner_fn, torch.fx.GraphModule): + raise AssertionError( + f"expected inner_fn to be torch.fx.GraphModule, got {type(inner_fn)}" + ) + wrapper_fn = inner_fn.meta[wrapper_fn_or_key] + else: + wrapper_fn = wrapper_fn_or_key + + @disable + def wrapper(): + return wrapper_fn(inner_fn)(*args, **kwargs) + + return wrapper() + + +dynamo_bypassing_wrapper = DynamoBypassingWrapper() + + +class WrapActivationCheckpoint(HigherOrderOperator): + """ + This operator is used to wrap torch.utils.checkpoint. This avoids + TorchDynamo to look into saved tensor hooks and directly passes the control + to AOT Autograd, which is ok with tracing saved tensor hooks. As a result of + AOT tracing torch.utils.checkpoint code, we have a backward graph with + recomputed forward nodes. + + However, we might deprecate this operator soon. The difficulty arises in the + functionalization of rng ops. Today, there are two different + functionalization of rng ops - one at AOT autograd and other at Inductor. + And they are difficult to map to each other. The rng states also complicate + pattern matching in Inductor. Due to the ease of implementation, we are + currently inclined towards functionalization at Inductor level, which means + that duplication/recomputation is done as a compiler pass in the + partitioners. See TagActivationCheckpoint for more information. + """ + + def __init__(self) -> None: + super().__init__("wrap_activation_checkpoint", cacheable=False) + + def __call__(self, function: GraphModule, *args: Any, **kwargs: Any) -> Any: + # use_reentrant is set to False because this op is going to be traced. + # And we ensure that AOT Autograd traces through the non reentrant + # version of checkpointing. + import torch.fx.traceback as fx_traceback + from torch.fx import Interpreter + + kwargs["use_reentrant"] = False + kwargs["preserve_rng_state"] = False + # Using interpreter allows preservation of metadata through torch.compile stack. + with fx_traceback.preserve_node_meta(): + from torch.utils.checkpoint import checkpoint + + return checkpoint(Interpreter(function).run, *args, **kwargs) + + +wrap_activation_checkpoint = WrapActivationCheckpoint() + + +class TagActivationCheckpoint(HigherOrderOperator): + """ + This operator is supposed to be used only with torch.compile stack. This + accepts a Fx graph module which needs to be checkpointed. This operator adds + "recomputable" tag to the nodes of the Fx graph that should be recomputed. + + The goal is to: + 1. Avoid using Dynamo to trace through saved tensor hooks. + 2. For selective checkpointing case, let AOTAutograd trace through + saved tensor hooks but has special logic with TorchDispatchMode to override + the usual saved_tensor_hooks fn logic in order to tag the nodes. + 3. Rely on the partitioners to actually duplicate the nodes. + This sits well in the torch.compile stack, because by the time graph + reaches partitioner, inductor has already run its functionalization of rng + ops (by setting fixed seed for each random op, see `replace_random_passes`). + Therefore, the duplication of nodes, by design, respects the rng states in + the forward and recomputed forward in backward. + """ + + def __init__(self) -> None: + super().__init__("tag_activation_checkpoint", cacheable=True) + + @staticmethod + def divide_kwargs(kwargs): + """ + checkpoint fn can have mixed kwargs between checkpointed fn and + checkpoint fn itself. For example + >> def gn(x, y, z=None): + >> a = torch.matmul(x, y) + >> if z is not None: + >> return torch.matmul(a, z) + >> return a + >> def fn(x, y, z): + >> return torch.cos(checkpoint(gn, x, y, use_reentrant=False, z=z)) + In the above case, z belongs to checkpointed function gn, but + use_reentrant belongs to the checkpoint function. This function splits + the kwargs into checkpoint_kwargs and gmod_kwargs (or + checkpointed_fn_kwargs). + We do sorting to ensure same graph from run to run for better + debuggability. It is not required for correctness. + """ + from torch.utils.checkpoint import checkpoint + + ckpt_signature = inspect.signature(checkpoint) + checkpoint_keys = set() + for name in ckpt_signature.parameters: + if name in ("function", "args", "kwargs"): + continue + checkpoint_keys.add(name) + + # `preserve_rng_state` is not a regular kwarg + checkpoint_keys.add("preserve_rng_state") + + checkpoint_kwargs = { + name: kwargs[name] for name in kwargs if name in checkpoint_keys + } + gmod_kwargs = { + name: kwargs[name] for name in kwargs if name not in checkpoint_keys + } + return checkpoint_kwargs, gmod_kwargs + + def __call__(self, gmod, *args, **kwargs): + dispatch_key_set = torch._ops._compute_keyset( + args, kwargs, self.non_fallthrough_keys + ) + dispatch_key = dispatch_key_set.highestPriorityTypeId() + if dispatch_key == torch._C.DispatchKey.PreDispatch: + # pyrefly: ignore [missing-attribute] + return super().__call__(gmod, *args, **kwargs) + + return tag_activation_checkpoint_impl(gmod, *args, **kwargs) + + +tag_activation_checkpoint = TagActivationCheckpoint() + + +def _always_prefer_recompute(ctx, op, *args, **kwargs): + from torch.utils.checkpoint import CheckpointPolicy + + return CheckpointPolicy.PREFER_RECOMPUTE + + +def tag_activation_checkpoint_impl(gmod, *args, **kwargs): + import functools + + import torch.fx.traceback as fx_traceback + from torch.fx import Interpreter + from torch.utils.checkpoint import create_selective_checkpoint_contexts + + unique_graph_id = next(uid) + if "_checkpoint_context_fn" in gmod.meta: + context_fn = gmod.meta["_checkpoint_context_fn"] + warning_once( + log, + """ +Detected that context_fn is passed to torch.utils.checkpoint under torch.compile. +Please make sure the checkpointed region does not contain in-place ops (e.g. torch.relu_). +""", + ) + else: + # Vanilla AC: use the SAC path with a policy that always recomputes. + context_fn = functools.partial( + create_selective_checkpoint_contexts, _always_prefer_recompute + ) + + def context_fn_with_graph_id(): + fwd_ctx, recomp_ctx = context_fn() + # Plumb ac_graph_id so _CachingTorchDispatchMode tags all nodes + # (including ops from desugared HOPs like custom autograd.Function). + fwd_ctx.ac_graph_id = unique_graph_id + return fwd_ctx, recomp_ctx + + # use_reentrant is set to False because this op is going to be traced. + # And we ensure that AOT Autograd traces through the non reentrant + # version of checkpointing. + kwargs["use_reentrant"] = False + # preserve_rng_state is set to False because we want to prevent AOTAutograd from tracing through + # `torch.random.fork_rng` op (which is not supported yet under CUDA). + # This doesn't mean that we don't preserve RNG state. Instead, we will always preserve RNG state + # regardless of this flag (by doing RNG functionalization via `replace_random_passes` in Inductor + # instead of in AOTAutograd). + kwargs["preserve_rng_state"] = False + kwargs["context_fn"] = context_fn_with_graph_id + # Disable early stop to prevent _StopRecomputationError from interrupting + # recomputation between _vmap_increment_nesting and _vmap_decrement_nesting, + # which would leak a functorch dynamic layer. + kwargs["early_stop"] = False + # Using interpreter allows preservation of metadata through torch.compile stack. + # We use a wrapper instead of passing Interpreter(gmod).run directly because + # checkpoint's recompute_fn captures the function in a closure. A bound method + # reference would keep the Interpreter alive, whose env dict retains the output + # tensors and prevents the autograd graph from being freed. + + def run_with_interpreter(*args): + return Interpreter(gmod).run(*args) + + with fx_traceback.preserve_node_meta(): + from torch.utils.checkpoint import checkpoint + + return checkpoint(run_with_interpreter, *args, **kwargs) + + +@tag_activation_checkpoint.py_impl(ProxyTorchDispatchMode) +def proxy_mode_key( + proxy_mode: ProxyTorchDispatchMode, + gmod: GraphModule, + *args: Any, + **kwargs: Any, +) -> tuple[torch.Tensor]: + import torch.fx.traceback as fx_traceback + from torch.fx import Interpreter + + if not proxy_mode.pre_dispatch: + raise AssertionError( + "post-dispatch mode should have inlined in the Autograd key" + ) + example_out = tag_activation_checkpoint(gmod, *args, **kwargs) + proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) # type: ignore[union-attr] + proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, kwargs) # type: ignore[union-attr] + qualname = proxy_mode.tracer.get_fresh_qualname("wrap_body") # type: ignore[union-attr] + + # TODO (tmanlaibaatar) don't we need flat_apply here?? + # Dynamo already traced the gmod body without kwargs + flat_args, _ = pytree.tree_flatten(args) + with fx_traceback.preserve_node_meta(): + gmod_aten = reenter_make_fx(Interpreter(gmod).run)(*flat_args) + gmod_aten.meta["_checkpoint_context_fn"] = gmod.meta["_checkpoint_context_fn"] + proxy_mode.tracer.root.register_module(qualname, gmod_aten) # type: ignore[union-attr] + proxy_gmod = proxy_mode.tracer.unwrap_proxy(gmod_aten) # type: ignore[union-attr, call-overload] + out_proxy = proxy_mode.tracer.create_proxy( + "call_function", + tag_activation_checkpoint, + (proxy_gmod, *proxy_args), + proxy_kwargs, + ) + return track_tensor_tree( + example_out, out_proxy, constant=None, tracer=proxy_mode.tracer + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__autotune_main__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/__autotune_main__.py new file mode 100644 index 0000000000000000000000000000000000000000..1eb5ca86e8c185e9c355e6dea152b53a3f181519 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__autotune_main__.py @@ -0,0 +1,33 @@ +import argparse +import logging +import os + +from torch._inductor.autotune_process import TuningProcess +from torch._inductor.compile_worker.utils import _async_compile_initializer + + +log = logging.getLogger(__name__) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--parent", type=int) + parser.add_argument("--read-fd", type=int) + parser.add_argument("--write-fd", type=int) + args = parser.parse_args() + read_pipe = os.fdopen(args.read_fd, "rb") + write_pipe = os.fdopen(args.write_fd, "wb") + + try: + # Ensures the subprocess exits if the parent crashes: + _async_compile_initializer(args.parent) + TuningProcess.process_main(read_pipe, write_pipe) + except Exception: + log.exception("Uncaught exception in autotune subprocess") + finally: + read_pipe.close() + write_pipe.close() + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..812f79dda45a2c91695eb2b27171dd46e04236b8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__init__.py @@ -0,0 +1,482 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import dataclasses +import io +import logging +import os +from typing import Any, IO, Literal, Optional, TYPE_CHECKING, Union + +import torch.fx + +from .standalone_compile import ( + compile_to_python, + CompiledArtifact, + DynamicShapesType, + load_from_python, +) + + +if TYPE_CHECKING: + from torch._inductor.utils import InputType + from torch._subclasses import FakeTensorMode + from torch.export import ExportedProgram + from torch.export.pt2_archive._package import AOTICompiledModel + from torch.export.pt2_archive._package_weights import Weights + from torch.types import FileLike + +__all__ = [ + "compile", + "compile_to_python", + "load_from_python", + "list_mode_options", + "list_options", + "cudagraph_mark_step_begin", + "standalone_compile", +] + + +log = logging.getLogger(__name__) + + +def compile( + gm: torch.fx.GraphModule, + example_inputs: list[InputType], + options: dict[str, Any] | None = None, +): + """ + Compile a given FX graph with TorchInductor. This allows compiling + FX graphs captured without using TorchDynamo. + + Args: + gm: The FX graph to compile. + example_inputs: List of tensor inputs. + options: Optional dict of config options. See `torch._inductor.config`. + + Returns: + Callable with same behavior as gm but faster. + """ + from .compile_fx import compile_fx + + return compile_fx(gm, example_inputs, config_patches=options) + + +def aoti_compile_and_package( + exported_program: ExportedProgram, + _deprecated_unused_args=None, + _deprecated_unused_kwargs=None, + *, + package_path: FileLike | None = None, + inductor_configs: dict[str, Any] | None = None, +) -> str: + """ + Compiles the exported program with AOTInductor, and packages it into a .pt2 + artifact specified by the input package_path. To load the package, you can + call ``torch._inductor.aoti_load_package(package_path)``. + + An example usage is as follows: + + .. code-block:: python + + ep = torch.export.export(M(), ...) + aoti_file = torch._inductor.aoti_compile_and_package( + ep, package_path="my_package.pt2" + ) + compiled_model = torch._inductor.aoti_load_package("my_package.pt2") + + To compile and save multiple models into a single ``.pt2`` artifact, you can do + the following: + + .. code-block:: python + + ep1 = torch.export.export(M1(), ...) + aoti_file1 = torch._inductor.aot_compile( + ep1, ..., options={"aot_inductor.package": True} + ) + ep2 = torch.export.export(M2(), ...) + aoti_file2 = torch._inductor.aot_compile( + ep2, ..., options={"aot_inductor.package": True} + ) + + from torch._inductor.package import package_aoti, load_package + + package_aoti("my_package.pt2", {"model1": aoti_file1, "model2": aoti_file2}) + + compiled_model1 = load_package("my_package.pt2", "model1") + compiled_model2 = load_package("my_package.pt2", "model2") + + Args: + exported_program: An exported program created through a call from torch.export + package_path: Optional specified path to the generated .pt2 artifact. + inductor_configs: Optional dictionary of configs to control inductor. + + Returns: + Path to the generated artifact + """ + from torch.export import ExportedProgram + + from .debug import aot_inductor_minifier_wrapper + + if not isinstance(exported_program, ExportedProgram): + raise ValueError("Only ExportedProgram is supported") + + if exported_program.example_inputs is None: + raise RuntimeError( + "exported_program.example_inputs is required to be set in order " + "for AOTInductor compilation." + ) + + if _deprecated_unused_args is not None or _deprecated_unused_kwargs is not None: + log.warning( + "You no longer need to specify args/kwargs to aoti_compile_and_package " + "as we can get this information from exported_program.example_inputs." + ) + + if not ( + package_path is None + or ( + isinstance(package_path, (io.IOBase, IO)) + and package_path.writable() + and package_path.seekable() + ) + or ( + isinstance(package_path, (str, os.PathLike)) + and os.fspath(package_path).endswith(".pt2") + ) + ): + raise AssertionError( + f"Expect package path to be a file ending in .pt2, is None, or is a buffer. Instead got {package_path}" + ) + + inductor_configs = inductor_configs or {} + inductor_configs["aot_inductor.package"] = True + + if inductor_configs.get("aot_inductor.output_path"): + raise RuntimeError( + "Please pass in a package path to aot_inductor_compile() instead " + "of setting the aot_inductor.output_path config." + ) + + # a wrapper around aoti_compile_and_package_inner. + return aot_inductor_minifier_wrapper( + _aoti_compile_and_package_inner, + exported_program, + package_path=package_path, + inductor_configs=inductor_configs, + ) + + +def _aoti_compile_and_package_inner( + gm: torch.nn.Module, + # flat_example_inputs: List[Any], + args: tuple[Any], + kwargs: dict[str, Any] | None = None, + *, + load_and_run: bool = False, + check_accuracy: str | None = None, + package_path: str | io.BytesIO | None = None, + inductor_configs: dict[str, Any] | None = None, +): + """ + See docstring for aoti_compile_and_package. + + If `load_and_run` is True, this function will load the compiled model and run it. + This is for the minifier to check the correctness of the compiled model. + + If `check_accuracy` is set, this function will check the accuracy of the compiled + model against gm. kwargs must be None if check_accuracy is set. + "strict_accuracy" means "we will minify any time we see anything that + diverges", whereas "accuracy" is more conservative, and will only minify if there + is a meaningful fp64 divergence + """ + + if check_accuracy: + if not (kwargs is None or len(kwargs) == 0): + raise AssertionError( + "when checking for accuracy, the inputs must have been flattened and kwargs is None" + ) + + from .package import package_aoti + + if not isinstance(gm, torch.fx.GraphModule): + raise AssertionError(f"expected torch.fx.GraphModule, got {type(gm)}") + + kwargs = kwargs or {} + + aoti_files = aot_compile(gm, args, kwargs, options=inductor_configs) + if not isinstance(aoti_files, list): + raise AssertionError( + f"expected aoti_files to be a list, got {type(aoti_files)}" + ) + + if package_path is None: + path = [ + os.path.splitext(file)[0] + for file in aoti_files + if isinstance(file, str) and os.path.splitext(file)[1] == ".so" + ] + if len(path) == 0: + path = [ + os.path.splitext(file)[0] + for file in aoti_files + if isinstance(file, str) and os.path.splitext(file)[1] == ".cpp" + ] + package_path = path[0] + ".pt2" + + res = package_aoti(package_path, aoti_files) + if res != package_path: + raise AssertionError( + f"expected res == package_path, got {res} != {package_path}" + ) + + if load_and_run or check_accuracy: + compiled_model = aoti_load_package(package_path) + if check_accuracy: + from torch._dynamo.debug_utils import AccuracyError, same_two_models + + # This might look inverted but it's not. strict_accuracy means "we will + # minify any time we see anything that diverges", whereas accuracy is more + # conservative, and will only minify if there is a meaningful fp64 + # divergence + not_strict_accuracy = check_accuracy == "accuracy" + if not same_two_models( + gm, + compiled_model, # type: ignore[arg-type] + args, + only_fwd=True, + require_fp64=not_strict_accuracy, + ignore_non_fp=not_strict_accuracy, + ): + raise AccuracyError("Bad accuracy detected") + else: + compiled_model(*args, **kwargs) + + return package_path + + +def aoti_load_package( + path: FileLike, run_single_threaded: bool = False, device_index: int = -1 +) -> AOTICompiledModel: + """ + Loads the model from the PT2 package. + + If multiple models were packaged into the PT2, this will load the default + model. To load a specific model, you can directly call the load API + + .. code-block:: python + + from torch._inductor.package import load_package + + compiled_model1 = load_package("my_package.pt2", "model1") + compiled_model2 = load_package("my_package.pt2", "model2") + + Args: + path: Path to the .pt2 package + run_single_threaded (bool): Whether the model should be run without + thread synchronization logic. This is useful to avoid conflicts with + CUDAGraphs. + device_index (int): The index of the device to which the PT2 package is + to be loaded. By default, `device_index=-1` is used, which corresponds + to the device `cuda` when using CUDA. Passing `device_index=1` would + load the package to `cuda:1`, for example. + """ + from torch._inductor.package import load_package + + return load_package( + path, run_single_threaded=run_single_threaded, device_index=device_index + ) + + +def aot_compile( + gm: torch.fx.GraphModule, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + *, + options: dict[str, Any] | None = None, +) -> str | list[str | Weights] | torch.fx.GraphModule: + """ + Ahead-of-time compile a given FX graph with TorchInductor into a shared library. + + Args: + gm: The FX graph to compile. + args: Example arguments + kwargs: Example keyword arguments + options: Optional dict of config options. See `torch._inductor.config`. + + Returns: + Path to the generated shared library, or a list of files generated by + AOTI if aot_inductor.package=True. + TODO: make it return a list by default + """ + from .compile_fx import _aoti_flatten_inputs, compile_fx_aot + + if hasattr(gm, "_guards_fn"): + # Do not compile the guards function, since it may contain checks + # that are not currently supported by AOTI. In particular, non-Tensor + # arguments are converted to None and will fail specialization checks. + node = next(iter(gm.graph.find_nodes(op="call_module", target="_guards_fn"))) + gm.graph.erase_node(node) + delattr(gm, "_guards_fn") + gm.recompile() + + flat_example_inputs, options = _aoti_flatten_inputs( + gm, args, kwargs, options=options + ) + from torch._export.utils import _compiling_state_context + + with _compiling_state_context(): + return compile_fx_aot( + gm, + flat_example_inputs, # type: ignore[arg-type] + config_patches=options, + ) + + +lite_mode_options = { + # Fallback by default unless users explicitly annotated with + # regional inductor compile. + "fallback_by_default": True, + "selective_decompose": True, + # Disable reorder optimizations + "reorder_for_peak_memory": False, + "reorder_for_compute_comm_overlap": False, + "triton.reorder_for_reducing_graph_partitions": False, + # Disable pre-, joint-, post-grad passes + "use_pre_grad_passes": False, + "use_joint_graph_passes": False, + "use_post_grad_passes": False, + # Disable dead code elimination (dce) and buffer reuse + "use_dce": False, + "allow_buffer_reuse": False, +} + + +def list_mode_options( + mode: str | None = None, dynamic: bool | None = None +) -> dict[str, Any]: + r"""Returns a dictionary describing the optimizations that each of the available + modes passed to `torch.compile()` performs. + + Args: + mode (str, optional): The mode to return the optimizations for. + If None, returns optimizations for all modes + dynamic (bool, optional): Whether dynamic shape is enabled. + + Example:: + >>> torch._inductor.list_mode_options() + """ + + mode_options: dict[str, dict[str, bool]] = { + "default": {}, + # lite backend for opt-in optimizations + "lite": lite_mode_options, + # enable cudagraphs + "reduce-overhead": { + "triton.cudagraphs": True, + }, + # enable max-autotune + "max-autotune-no-cudagraphs": { + "max_autotune": True, + "coordinate_descent_tuning": True, + }, + # enable max-autotune + # enable cudagraphs + "max-autotune": { + "max_autotune": True, + "triton.cudagraphs": True, + "coordinate_descent_tuning": True, + }, + } + try: + return mode_options[mode] if mode else mode_options + except KeyError as e: + raise RuntimeError( + f"Unrecognized mode={mode}, should be one of: {', '.join(mode_options.keys())}" + ) from e + + +def list_options() -> list[str]: + r"""Returns a dictionary describing the optimizations and debug configurations + that are available to `torch.compile()`. + + The options are documented in `torch._inductor.config`. + + Example:: + + >>> torch._inductor.list_options() + """ + + from torch._inductor import config + + current_config: dict[str, Any] = config.get_config_copy() + + return list(current_config.keys()) + + +def cudagraph_mark_step_begin(): + "Indicates that a new iteration of inference or training is about to begin." + from .cudagraph_trees import mark_step_begin + + mark_step_begin() + + +def standalone_compile( + gm: torch.fx.GraphModule, + example_inputs: list[InputType], + *, + dynamic_shapes: DynamicShapesType = "from_graph", + options: dict[str, Any] | None = None, + aot: bool = False, # AOT mode, which uses BundledAOTAutogradCache + donate_graph_module: bool = False, + fake_mode: FakeTensorMode | None = None, +) -> CompiledArtifact: + """ + Precompilation API for inductor. + + .. code-block:: python + + compiled_artifact = torch._inductor.standalone_compile(gm, args) + compiled_artifact.save(path=path, format="binary") + + # Later on a new process + loaded = torch._inductor.CompiledArtifact.load(path=path, format="binary") + compiled_out = loaded(*args) + + Args: + gm: Graph Module + example_inputs: Inputs for the graph module + dynamic_shapes: If "from_graph" (default), we will use the dynamic + shapes in the passed-in graph module. + If "from_tracing_context", we use the dynamic shape info in the + ambient tracing context. + If "from_example_inputs", we will specialize the graph on the + example_inputs. + options: Inductor compilation options + donate_graph_module: If True, standalone_compile takes ownership of + the graph module and may mutate it, avoiding an internal deepcopy. + Defaults to False for backwards compatibility. + fake_mode: Optional FakeTensorMode to use when + dynamic_shapes="from_example_inputs". The mode must have a ShapeEnv. + When omitted, a fresh FakeTensorMode is created as before. + + Returns: + CompiledArtifact that can be saved to disk or invoked directly. + """ + from .standalone_compile import standalone_compile + + options = options if options else {} + return standalone_compile( + gm, + example_inputs, + dynamic_shapes=dynamic_shapes, + options=options, + aot=aot, + donate_graph_module=donate_graph_module, + fake_mode=fake_mode, + ) + + +@dataclasses.dataclass +class _CudagraphAnnotation: + fwd: bool | None + bwd: bool | None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__autotune_main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__autotune_main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e0b25cb4a4c3cb30e09614147cada04bc25d9b3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__autotune_main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6836eb4dd23f712e2826ce80d36d6cbaf2239e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/_functionalize_collectives.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/_functionalize_collectives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3e3890d51dd359b97564606a3379759f6e6c870 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/_functionalize_collectives.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/analyze_preserves_zero_mask.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/analyze_preserves_zero_mask.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bda7c4d725c0f68d70eb5a6cde627a42eeb0c701 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/analyze_preserves_zero_mask.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/aoti_eager.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/aoti_eager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adcb0b7842532b7c0fe323e9779ac6baf44841fe Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/aoti_eager.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/async_compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/async_compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e79aa9cebb0e83f815b7f158cfb33cafdb7a037 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/async_compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/augmented_graph_helper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/augmented_graph_helper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73aede45dda0bba6b20d2f75bf44acd16507cdf9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/augmented_graph_helper.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autotune_process.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autotune_process.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f399541c0b8a752b9cc1cb31d43589690a67cccf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autotune_process.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autows_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autows_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e073139bf88b95c7aeea208f2f7470b7a8022181 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/autows_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/await_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/await_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edad66bd25e3b240755e988d1f7eab94bc325597 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/await_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/bounds.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/bounds.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf5024f5e096e6e8ea5d0ff070fed5e3fdae8016 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/bounds.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..194bb8ea1ec6819daf0c77ba71be29756591c4bc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache_key.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache_key.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ad906d9239598d3327a74c221a7bfa172b34153 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cache_key.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/choices.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/choices.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ad0149a08695c75e3856e1bba56c45d4cffe1d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/choices.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/codecache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/codecache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..134c6a8e0e400bd3d7cf6eaed3581dd0e4c04dbb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/codecache.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33f6eca55b4b869b5d71edb06b70b1adcfa4d5ee412991a06da5bd6e2345183d +size 236970 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6706e97b6f8313959e3aff6e5821e4da742083a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_lowering.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_lowering.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04bcaf9a653b845c9373cd7dc84ad1ccfd07db9e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comm_lowering.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..954f333cff3cf8a796138e9f01124ff86898f758 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms_debug.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms_debug.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32e694aff6c2058215ccf26a58aac65fbfe776ed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/comms_debug.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..164831ceb77071b7f81af3a93fac4f4f0ac588c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26bcde47491027cc58aa68bedfe1ebca31539a665c27b602d11271dbb12cd3b2 +size 137781 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_async.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_async.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e30f4c7a308d53b778f46811f2a3222ff33bf9c5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_async.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_ext.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_ext.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9328a229db0b21ae3e8ab3f138786cedf5135e3c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_ext.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_subproc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_subproc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd3049cfae7b217ffa41e606b1445fde4a6f8367 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compile_fx_subproc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compiler_bisector.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compiler_bisector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d8fdd015baf76d4f84373a139084a37362cd1f9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/compiler_bisector.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a3cba1945b5b1b464e5ca15248f15b57bfa0a6e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config_comms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config_comms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90d6465530e746344d18b088c8ad5a89657453cf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/config_comms.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/constant_folding.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/constant_folding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e726c310ff3e622bd6ad65614a555af1cdc3114 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/constant_folding.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpp_builder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpp_builder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b625e2822871579b9542711b40b85d1b465c98f9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpp_builder.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af115f2c901b26586b2d3d59c0df71877fef7d5bf88542a0b89fdc5e5eaff339 +size 121438 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpu_vec_isa.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpu_vec_isa.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c57f6813e82a372878deacb974a19478afc21a8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cpu_vec_isa.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ac38271f814c932a9722cffbdc8bca13b150f1e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_trees.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49e2e49eb436bd4d7001db2152b0904f3197838ade499b2b5e78ca46a769f4cb +size 137043 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d94e0dbfce53c61046b732b52f17d04ca1ed164 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/cudagraph_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/custom_graph_pass.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/custom_graph_pass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b3117489b8fbbd5226ae361e3a1a682b1337796 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/custom_graph_pass.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/debug.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/debug.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57367e6955e0c7991a5e144204a4f223b5efda5a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/debug.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/decomposition.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/decomposition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b522c7e492d01630474084981071497c9738f90 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/decomposition.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dependencies.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dependencies.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ebdc1afd7c988ba9ee085e11193fb296d1762f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dependencies.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/distributed_autotune.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/distributed_autotune.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1df5b7689e4579b476d02b45fcccbae8928d1813 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/distributed_autotune.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dtype_propagation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dtype_propagation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63d0d5d09aac226f2b7d7e5e365550beaf946cab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/dtype_propagation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/exc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/exc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0890310ce15bf95b25e3a7bf3cb55362050185ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/exc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/extern_node_serializer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/extern_node_serializer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f527ae65aec2cd6cc7ee0243c4aa8d322f11f410 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/extern_node_serializer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..866a80177f8de298fe734dd5745b01362c8a5fee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e5d1c608641ccdb329278ef7897583023b932b9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/freezing_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fuzzer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fuzzer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ac9ba61a228f2f85eeab678c309d66d0891297 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fuzzer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fx_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fx_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a3e8f321924eaa1b1159e980845c7d9148313d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/fx_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8df2c362750319f1eef65d52f23a1723b416c0f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/graph.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:160222280b6715040f44eddbfac4b16c6b955bf849377fedad34cf922a85253a +size 139308 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/hooks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/hooks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3cae4f882c8f38a6fb5add748d8f066d0482f7a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/hooks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/index_propagation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/index_propagation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ca95552bb76fd576ba015b2beb83af05f1831ee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/index_propagation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/inductor_prims.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/inductor_prims.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d5f6bf2cbe94d15aa0deb136bb921b26faf4a03 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/inductor_prims.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/invert_expr_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/invert_expr_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad91a7ddae9faaccb1cd2a41868ac5599e1614cb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/invert_expr_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ir.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ir.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30db6ce324782b53ea8ba75d10e6f03631e55337 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ir.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c0618d3762bc8d5750c0f2ef6c80b02ee4d93a6d3a9f2e428e94f9236a5fe79 +size 535082 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/jagged_lowerings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/jagged_lowerings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb2ed01fa1dd1749be642934225053136b2bb4e7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/jagged_lowerings.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_inputs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_inputs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac2066de23fd1a41cfad5c91d0d4d0a05d3b0a58 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_inputs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_template_choice.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_template_choice.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bd2744c618916c5b27d17cf4b2537986f5a2ef6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/kernel_template_choice.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/loop_body.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/loop_body.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85cbdb1ee5dc883d3d9bdb78aec46e5d9010ff22 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/loop_body.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/lowering.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/lowering.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e1e46317de4ed20e2edb31b1d468adbef61043d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/lowering.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b65d1c07128421aeb9d1aa5c3bf90537364e481285347bb6c2aaf7c1a11eb8d +size 430031 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/memory.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..497216134844cfc519638427f2fa9e2cb5ece6c6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/memory.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/metrics.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf33b8d854deed25997b93c16c15a67dbdc30cf2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/metrics.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_ir.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_ir.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bc76047972156fe07de1f86b36208ac2ea1dfaf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_ir.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_lowerings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_lowerings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01fd34b02a42e2203d1c7e6efa4a0e7f815ba1d2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mkldnn_lowerings.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mock_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mock_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a748ae1459e6cb86712f8a5d5f80f8676517da6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/mock_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ops_handler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ops_handler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0198be6f82024d9acc341dad342057e3e16ccbaf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/ops_handler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/optimize_indexing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/optimize_indexing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c10967fe2970d19c5882c1354ac7c486b35af419 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/optimize_indexing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/output_code.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/output_code.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c72dec09e33f61cc6dd538f59982718e3f69bd1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/output_code.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfe89dda8eb977a2cb5e8ccaa4818a4dc000bf6d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/pattern_matcher.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ff8d3ff9ebd219f4ead9ddeb317e86abff83f18f697d2d0ac7f5c010f0636aa +size 142840 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/profiler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/profiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d1ad044ef47b0cfa9566ec23fe6069acbd542b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/profiler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/quantized_lowerings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/quantized_lowerings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..204f618e66ce0c2ea99899fd698a2b01c254ee9c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/quantized_lowerings.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ac088c88c697616daa4b742e58cb80a489cfa7e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_gemm_autotune_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_gemm_autotune_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb454a037a927e8cdeae3663923439b5ebb48dab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/remote_gemm_autotune_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/rocm_multiarch_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/rocm_multiarch_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f949dcde62c770e5a548b45ecf7ed68a222d56b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/rocm_multiarch_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/scheduler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/scheduler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..181b50f5835d49f691c63a7b6f516cb9204bcb6a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/scheduler.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92ff0cf9e3aa868072c79f0b80d0fc3cea314d098276a184c9aa08af35d0e864 +size 484481 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b52ee3f31f6fc915e876f446c3ad47cdabcc14d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/select_algorithm.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94160e09779b7fd68401a088940241eba7c391bbc016816467a98153e828fa06 +size 268738 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/shape_propagation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/shape_propagation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7715ed0072cc06d937d97e57c31ff7484830c747 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/shape_propagation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/sizevars.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/sizevars.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68c907c0d2c74470f4a5aa93c0db74b755c63337 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/sizevars.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/standalone_compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/standalone_compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b327c95c90549812b9d2aba929097e4cac36988 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/standalone_compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_constants.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2b5dd91666b906da979b89ab74535e3d23e8f94 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_constants.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae9c859474cc2daf69e528463dfdb5c56c9675e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/stream_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/subgraph_lowering.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/subgraph_lowering.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c2c6f2c7d3489e4ef521fb77f8d614c354d2191 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/subgraph_lowering.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_case.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_case.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da6b21fccee181933e42cc72669501cded87e21a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_case.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312-pytest-9.1.1.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82f758716a210e89ec19d4164cb4bc3298b57a00 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312-pytest-9.1.1.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b589382338b2740ec1daa61452b4c0b95ebe0fd1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/test_operators.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/tiling_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/tiling_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aaca787708420edcd0b889677d5a5ea8f73b4f5f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/tiling_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/triton_bundler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/triton_bundler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..331b1752331aa45b8f679c0fc2cb4a588fc3f9b4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/triton_bundler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..474364fe9132944793e38078a7bee8f63ab18fe2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/utils.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5539c8cf92f9ffdeb8473ee14e4fba9cccfaf6ed35e78f183f974157975af34 +size 218651 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/virtualized.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/virtualized.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad330b0dd278b6147fb606156a3001efc2dc16cf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/virtualized.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/wrapper_benchmark.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/wrapper_benchmark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..958bf1cd18914142c3bb8c78d7dcec4e36e935f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/__pycache__/wrapper_benchmark.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/_functionalize_collectives.py b/.venv/lib/python3.12/site-packages/torch/_inductor/_functionalize_collectives.py new file mode 100644 index 0000000000000000000000000000000000000000..6a25c0a64b07a9b71085eee5a9e8d965e02fdc34 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/_functionalize_collectives.py @@ -0,0 +1,283 @@ +"""Rewrite raw ``c10d.{op}_`` inplace ops produced by ``make_fx`` into +``_c10d_functional.{op}`` + ``wait_tensor`` + ``aten.copy_`` form so +``standalone_compile`` (and Inductor's collective machinery underneath) can +recognize and lower them. + +The structure separates concerns: + * Arg resolution (PG, ReduceOp) lives in ``_resolve_*``. + * The functional + wait + copy_ chain construction lives in + ``_emit_collective_chain`` (used by every per-op rewrite). + * Use redirection lives in ``_redirect_*_work_uses`` keyed by output schema. + * Per-op rewrites (``_rewrite__``) glue these together. + * The driver ``_functionalize_inplace_collectives`` walks the graph, + dispatches by target, and runs final cleanup. +""" + +from __future__ import annotations + +import operator +from collections.abc import Callable +from typing import Any + +import torch +from torch.fx.graph_module import _assign_attr, _del_attr, _get_attr + + +def _resolve_reduce_op_str( + gm: torch.fx.GraphModule, arg: torch.fx.node.Argument +) -> str: + """Get the lower-case op string (``"sum"``/``"avg"``/...) for a c10d + ReduceOp ``get_attr`` arg, converting from the torchbind ScriptObject + form if needed. + + Only the ``get_attr`` (constant-baked) shape is supported today. Any + other producer (placeholder, call_function, ...) would require + ``_c10d_functional.*`` to accept ReduceOp directly (today it only + takes the string form); deferred to a follow-up PR. + """ + import torch.distributed as dist + from torch.distributed._functional_collectives import REDUCE_OP_TO_STR + + if not isinstance(arg, torch.fx.Node) or arg.op != "get_attr": + raise NotImplementedError( + f"ReduceOp arg must be a constant ``get_attr``; got {arg!r}." + ) + reduce_op = _get_attr(gm, arg.target) # type: ignore[arg-type] + if isinstance(reduce_op, torch.ScriptObject): + reduce_op = dist.ReduceOp.RedOpType(reduce_op.op()) # type: ignore[attr-defined] + return REDUCE_OP_TO_STR[reduce_op] + + +def _emit_collective_chain( + gm: torch.fx.GraphModule, + before: torch.fx.Node, + input_t: torch.fx.Node, + output_t: torch.fx.Node, + functional_target: Any, + extra_args: tuple[Any, ...], + pg_arg: torch.fx.Node, + custom: Any, +) -> torch.fx.Node: + """Insert ``_c10d_functional.(input, *extra_args, pg_arg)`` -> + ``wait_tensor`` -> ``aten.copy_(output, wait)`` immediately before + ``before`` and return the ``wait_tensor`` node. + + Propagates ``output_t.meta["val"]`` onto every new node — every functional + collective we rewrite to produces a tensor with the same shape/dtype as + ``output_t``, and ``aten.copy_`` returns ``output_t``. Also carries the + rewritten node's ``custom`` annotation forward so region scooping continues + to work. + """ + val = output_t.meta.get("val") + with gm.graph.inserting_before(before): + ar = gm.graph.call_function(functional_target, (input_t, *extra_args, pg_arg)) + wait = gm.graph.call_function( + torch.ops._c10d_functional.wait_tensor.default, (ar,) + ) + copy_ = gm.graph.call_function(torch.ops.aten.copy_.default, (output_t, wait)) + if val is not None: + ar.meta["val"] = wait.meta["val"] = copy_.meta["val"] = val + if custom is not None: + ar.meta["custom"] = wait.meta["custom"] = copy_.meta["custom"] = custom + return wait + + +def _redirect_inplace_collective_uses( + gm: torch.fx.GraphModule, + node: torch.fx.Node, + wait_nodes: list[torch.fx.Node], +) -> None: + """Re-route uses for an inplace c10d op with output schema + ``(Tensor[], Work)`` — e.g. ``allreduce_``, ``broadcast_``, + ``reduce_scatter_``, ``alltoall_``. + + ``make_fx`` lowers tensor consumers into ``getitem(node, 0)[i]``; replace + each with ``wait_nodes[i]``. The work-handle ``getitem(node, 1)`` is erased + if unused (live users raise — functional collectives have no Work object + to forward to, so we can't preserve that synchronization). + + TODO: extend to ``(Tensor, Work)`` schemas (``_allgather_base_``, + ``_reduce_scatter_base_``) when those rewrites are added. There the + ``getitem(node, 0)`` is itself the tensor consumer (no inner + ``getitem`` chain), so the inner loop below would need to fall back to + ``use.replace_all_uses_with(wait_nodes[0])`` when ``use`` has no inner + ``getitem`` users. + """ + for use in list(node.users): + if use.op != "call_function" or use.target is not operator.getitem: + raise AssertionError( + f"Cannot functionalize {node.target}: unexpected use {use} " + f"(op={use.op!r}, target={use.target!r}). The c10d inplace " + f"output is a tuple consumed via ``getitem`` in ``make_fx`` " + f"graphs; non-getitem users are not supported by this pass." + ) + if use.args[1] == 0: + for sub_use in list(use.users): + if ( + sub_use.op != "call_function" + or sub_use.target is not operator.getitem + ): + raise AssertionError( + f"Cannot functionalize {node.target}: tensor list " + f"consumed by non-getitem user {sub_use}. Extend " + f"_redirect_inplace_collective_uses to support this " + f"schema if needed." + ) + sub_use.replace_all_uses_with(wait_nodes[sub_use.args[1]]) # type: ignore[index] + gm.graph.erase_node(sub_use) + gm.graph.erase_node(use) + elif use.args[1] == 1: + if use.users: + raise AssertionError( + f"Cannot functionalize {node.target}: Work handle has " + f"{len(use.users)} live use(s) ({list(use.users)}). " + f"Functional collectives express synchronization via " + f"``wait_tensor`` on the data tensor, so the Work object " + f"has no equivalent to forward to." + ) + gm.graph.erase_node(use) + + +def _rewrite_allreduce_(gm: torch.fx.GraphModule, node: torch.fx.Node) -> None: + """Reference rewrite — use this as a template for new collectives. + + Schema: ``c10d::allreduce_(Tensor[] tensors, ProcessGroup pg, ReduceOp op, + Tensor? sparse_indices, bool async_op, int timeout=-1) -> (Tensor[], Work)``. + + Before:: + + allreduce_ = c10d.allreduce_([t0, t1], pg, reduce_op, None, False) + getitem = allreduce_[0] + getitem_1 = getitem[0] # consumer of t0 post-allreduce + getitem_2 = getitem[1] # consumer of t1 post-allreduce + ... = allreduce_[1] # work handle (unused) + + After (per input tensor; ``pg`` is the original ``get_attr`` Node — a + later pass will bake it into a ``group_name`` string):: + + ar_i = _c10d_functional.all_reduce(t_i, op_str, pg) + wait_i = _c10d_functional.wait_tensor(ar_i) + _ = aten.copy_(t_i, wait_i) # preserves inplace semantics + # downstream uses of ``getitem_`` are redirected to ``wait_i`` + """ + tensors = node.args[0] + pg_arg = node.args[1] + if not isinstance(tensors, (list, tuple)): + raise AssertionError(f"expected ``Tensor[]`` arg list, got {type(tensors)}") + if not isinstance(pg_arg, torch.fx.Node): + raise AssertionError(f"expected ProcessGroup as fx.Node, got {type(pg_arg)}") + op_str = _resolve_reduce_op_str(gm, node.args[2]) + custom = node.meta.get("custom") + waits = [] + for t in tensors: + if not isinstance(t, torch.fx.Node): + raise AssertionError(f"expected tensor entry as fx.Node, got {type(t)}") + waits.append( + _emit_collective_chain( + gm, + node, + t, + t, + torch.ops._c10d_functional.all_reduce.default, + (op_str,), + pg_arg, + custom, + ) + ) + _redirect_inplace_collective_uses(gm, node, waits) + + +_InplaceCollectiveRewrite = Callable[[torch.fx.GraphModule, torch.fx.Node], None] + + +def _inplace_c10d_rewrites() -> dict[Any, _InplaceCollectiveRewrite] | None: + """Map inplace ``c10d.{op}_`` op targets to per-op rewrite functions. + + Returns ``None`` if ``torch.distributed`` is not available. + + To support a new collective: write ``_rewrite__`` (typically a few + lines using ``_resolve_reduce_op_str`` / ``_emit_collective_chain`` / + ``_redirect_inplace_collective_uses``), then register it here. + """ + if not torch.distributed.is_available(): + return None + return { + torch.ops.c10d.allreduce_.default: _rewrite_allreduce_, + } + + +def _functionalize_inplace_collectives( + gm: torch.fx.GraphModule, +) -> torch.fx.GraphModule: + """Rewrite raw ``torch.ops.c10d.{op}_`` inplace calls in ``gm`` into + ``_c10d_functional.{op}`` + ``wait_tensor`` + ``aten.copy_`` form so + Inductor's collective machinery can recognize and lower them. + """ + rewrites = _inplace_c10d_rewrites() + if rewrites is None: + return gm + + found = False + for node in list(gm.graph.nodes): + if node.op != "call_function": + continue + rewrite = rewrites.get(node.target, None) + if rewrite is None: + continue + rewrite(gm, node) + # Snapshot ``get_attr`` args before erasing the rewritten node. + # Inplace c10d ops are impure; ``eliminate_dead_code`` keeps them + # alive even with no users, so erase explicitly. Then drop any + # ``get_attr`` arg that became orphan (e.g. the ReduceOp whose + # value got baked into ``op_str``) along with its backing module + # attribute. Live ones (e.g. the ProcessGroup, still referenced + # by the new ``_c10d_functional`` call) are kept. + get_attr_args = [ + a for a in node.args if isinstance(a, torch.fx.Node) and a.op == "get_attr" + ] + gm.graph.erase_node(node) + for a in get_attr_args: + if not a.users: + _del_attr(gm, a.target) # type: ignore[arg-type] + gm.graph.erase_node(a) + found = True + + if found: + gm.recompile() + return gm + + +def _unbox_process_group_torchbinds( + gm: torch.fx.GraphModule, +) -> torch.fx.GraphModule: + """Replace ProcessGroup torchbind attrs with their unboxed Python + ``dist.ProcessGroup``. + + ``make_fx`` traces ``dist.*`` collectives with a torchbind + ``__torch__.torch.classes.c10d.ProcessGroup`` baked in as a graph attr. + Inductor's collective ops (``_c10d_functional.{op}``) accept either a + ``group_name`` string or a Python ``dist.ProcessGroup`` — but **not** a + raw torchbind, which fails at runtime with:: + + all_reduce_(): argument 'group_name' must be either a string ... + but got __torch__.torch.classes.c10d.ProcessGroup + + Unboxing the attribute in-place (without changing the FX graph) makes + the PG acceptable to the runtime collective op. The deepcopy + share-by-reference hook in ``GraphModule.__deepcopy__`` is what lets + ``standalone_compile``'s deepcopy of the gm survive the non-pickleable + Python ``dist.ProcessGroup``. + """ + import torch.distributed as dist + + if not torch.distributed.is_available(): + return gm + + for node in gm.graph.find_nodes(op="get_attr"): + attr = _get_attr(gm, node.target) # type: ignore[arg-type] + if not isinstance(attr, torch.ScriptObject): + continue + if attr._type().qualified_name() != "__torch__.torch.classes.c10d.ProcessGroup": # type: ignore[attr-defined] + continue + _assign_attr(dist.ProcessGroup.unbox(attr), gm, node.target) # type: ignore[arg-type] + return gm diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85f59e1a1ad8225e2be86c295e1eca5b480f36a3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/device_info.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/device_info.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddd4071a68d046ae3aec8c1a089353002b56b83f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/device_info.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/profile_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/profile_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c6a5f51a5ea730c3b8cbefa66b75e67a760892d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/__pycache__/profile_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/device_info.py b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/device_info.py new file mode 100644 index 0000000000000000000000000000000000000000..737ead7be59806bdb708dbe1c258a6a6cf61dcf2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/device_info.py @@ -0,0 +1,345 @@ +import logging +from dataclasses import dataclass + +import torch + + +log = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class DeviceInfo: + """ + Theoretical numbers from data sheet. When a data sheet reports both + Tensor/Matrix-Core and non-Tensor-Core numbers, the higher (Tensor Core) + number is used. + + NVIDIA data sheets since Hopper (H100) only publish Tensor-Core TFLOPS + with 2:4 structured sparsity (marked ``*With sparsity``). For devices + whose ``tops`` include sparsity, set ``tops_sparsity_factor`` to 2 so + that callers can recover the dense (non-sparse) throughput used by + cuBLAS / cuDNN in normal (non-sparse) workloads. + + Bandwidth numbers are tricky, because there are platform differences + that may not show up in the profiler trace. + """ + + tops: dict[torch.dtype | str, float] + dram_bw_gbs: float + dram_gb: float + tops_sparsity_factor: int = 1 + + +# Indexing is based on `torch.cuda.get_device_name()`, normalized to upper-case. +# TODO investigate profiler support for tf32 and allow device to report correct number when it's turned on. +_device_mapping: dict[str, DeviceInfo] = { + # Source: + # @lint-ignore https://www.nvidia.com/en-us/data-center/h100/ + # Tensor Core values are *with sparsity* per the datasheet. + "NVIDIA H100": DeviceInfo( + tops={ + torch.float64: 67.0, + torch.float32: 67.0, + "torch.tf32": 989.0, + torch.bfloat16: 1979.0, + torch.float16: 1979.0, + torch.float8_e8m0fnu: 3958.0, + torch.float8_e8m0fnu: 3958.0, + torch.float8_e4m3fnuz: 3958.0, + torch.float8_e5m2: 3958.0, + torch.float8_e5m2fnuz: 3958.0, + torch.float8_e8m0fnu: 3958.0, + torch.int8: 3958.0, + }, + dram_bw_gbs=3350, + dram_gb=80, + tops_sparsity_factor=2, + ), + # Source: + # @lint-ignore https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/ + # nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf + "NVIDIA A100": DeviceInfo( + tops={ + torch.float64: 19.5, + torch.float32: 19.5, + torch.bfloat16: 312.5, + torch.float16: 312.5, + # Not in datasheet: float8 + torch.int8: 624.0, + "torch.tf32": 156.0, + }, + dram_bw_gbs=2039.0, + dram_gb=80.0, + ), + # Source: + # @lint-ignore https://resources.nvidia.com/en-us-gpu-resources/l4-tensor-datasheet + "NVIDIA L4": DeviceInfo( + tops={ + # This is a guess, not in datasheet + torch.float64: 15.1, + torch.float32: 30.3, + "torch.tf32": 120.0, + torch.bfloat16: 242.0, + torch.float16: 242.0, + torch.float8_e8m0fnu: 485.0, + torch.float8_e8m0fnu: 485.0, + torch.float8_e4m3fnuz: 485.0, + torch.float8_e5m2: 485.0, + torch.float8_e5m2fnuz: 485.0, + torch.float8_e8m0fnu: 485.0, + torch.int8: 485.0, + }, + dram_bw_gbs=3350, + dram_gb=24, + ), + # Source: + # @lint-ignore https://www.amd.com/content/dam/amd/en/documents\ + # /instinct-tech-docs/product-briefs/amd-instinct-mi350x-gpu-brochure.pdf + "AMD MI350X": DeviceInfo( + tops={ + torch.float64: 72.1, + torch.float32: 144.2, + # not specified, fall back to float32 numbers + "torch.tf32": 144.2, + torch.bfloat16: 2309.6, + torch.float16: 2309.6, + torch.float8_e8m0fnu: 4614.0, + torch.float8_e8m0fnu: 4614.0, + torch.float8_e4m3fnuz: 4614.0, + torch.float8_e5m2: 4614.0, + torch.float8_e5m2fnuz: 4614.0, + torch.float8_e8m0fnu: 4614.0, + torch.int8: 4614.0, + }, + dram_bw_gbs=8000.0, + dram_gb=288.0, + ), + # Source: + # @lint-ignore https://www.amd.com/content/dam/amd/en/documents\ + # /instinct-tech-docs/data-sheets/amd-instinct-mi300a-data-sheet.pdf + "AMD MI300A": DeviceInfo( + tops={ + torch.float64: 122.6, + torch.float32: 122.6, + "torch.tf32": 490.3, + torch.bfloat16: 980.6, + torch.float16: 980.6, + torch.float8_e8m0fnu: 1961.2, + torch.float8_e8m0fnu: 1961.2, + torch.float8_e4m3fnuz: 1961.2, + torch.float8_e5m2: 1961.2, + torch.float8_e5m2fnuz: 1961.2, + torch.float8_e8m0fnu: 1961.2, + torch.int8: 1961.2, + }, + dram_bw_gbs=5300.0, + dram_gb=128.0, + ), + # Source: + # @lint-ignore https://www.amd.com/content/dam/amd/en/documents/\ + # instinct-tech-docs/data-sheets/amd-instinct-mi300x-data-sheet.pdf + "AMD MI300X": DeviceInfo( + tops={ + torch.float64: 163.4, + torch.float32: 163.4, + "torch.tf32": 653.7, + torch.bfloat16: 1307.4, + torch.float16: 1307.4, + torch.float8_e8m0fnu: 2614.9, + torch.float8_e8m0fnu: 2614.9, + torch.float8_e4m3fnuz: 2614.9, + torch.float8_e5m2: 2614.9, + torch.float8_e5m2fnuz: 2614.9, + torch.float8_e8m0fnu: 2614.9, + torch.int8: 2614.9, + }, + dram_bw_gbs=5300.0, + dram_gb=192.0, + ), + # Source: + # @lint-ignore https://www.amd.com/content/dam/amd/\ + # en/documents/instinct-business-docs/product-briefs/instinct-mi210-brochure.pdf + "AMD MI210X": DeviceInfo( + tops={ + torch.float64: 45.3, + torch.float32: 45.3, + # not specified, fall back to float32 numbers + "torch.tf32": 45.3, + torch.bfloat16: 181.0, + torch.float16: 181.0, + # not specified, fall back to float16 numbers + torch.float8_e8m0fnu: 181.0, + torch.float8_e8m0fnu: 181.0, + torch.float8_e4m3fnuz: 181.0, + torch.float8_e5m2: 181.0, + torch.float8_e5m2fnuz: 181.0, + torch.float8_e8m0fnu: 181.0, + torch.int8: 181.0, + }, + # pcie4.0x16 + dram_bw_gbs=1600.0, + dram_gb=64.0, + ), + # Source: + # @lint-ignore https://www.intel.com/content/www/us/en/products/sku/241598/ + # intel-arc-b580-graphics/specifications.html + "INTEL B580": DeviceInfo( + tops={ + # Estimated from published single-precision throughput. + torch.float64: 6.83, + torch.float32: 13.67, + "torch.tf32": 116.5, + torch.bfloat16: 116.5, + torch.float16: 116.5, + # not specified, fall back to fp16 matrix throughput + torch.float8_e8m0fnu: 116.5, + torch.float8_e4m3fnuz: 116.5, + torch.float8_e5m2: 116.5, + torch.float8_e5m2fnuz: 116.5, + torch.int8: 233, + }, + dram_bw_gbs=456.0, + dram_gb=12.0, + ), + # Source: + # @lint-ignore https://www.intel.com/content/www/us/en/products/sku/245797/ + # intel-arc-pro-b70-graphics/specifications.html + "INTEL B70": DeviceInfo( + tops={ + torch.float64: 11.47, + torch.float32: 22.94, + "torch.tf32": 183.5, + torch.bfloat16: 183.5, + torch.float16: 183.5, + torch.float8_e8m0fnu: 183.5, + torch.float8_e4m3fnuz: 183.5, + torch.float8_e5m2: 183.5, + torch.float8_e5m2fnuz: 183.5, + torch.int8: 367, + }, + dram_bw_gbs=608.0, + dram_gb=32.0, + ), + # Source: + # @lint-ignore https://www.intel.com/content/www/us/en/products/sku/232876/\ + # intel-data-center-gpu-max-1100/specifications.html + "Intel(R) Data Center GPU Max 1100": DeviceInfo( + # XeCore count: 56, + # vector/matrix engines per XeCore: 8 + # freq: 1.55GHz + tops={ + # Vector engine + torch.float64: 11.1, + torch.float32: 22.2, + # not specified, fall back to float32 numbers + "torch.tf32": 22.2, + # Matrix engine + torch.float16: 355.5, + torch.bfloat16: 355.5, + # not supported, fall back to float32 numbers + torch.float8_e8m0fnu: 22.2, + torch.float8_e4m3fnuz: 22.2, + torch.float8_e5m2: 22.2, + torch.float8_e5m2fnuz: 22.2, + torch.int8: 711.1, + }, + dram_bw_gbs=1228.8, + dram_gb=48, + ), +} +_device_mapping["AMD INSTINCT MI350X"] = _device_mapping["AMD MI350X"] +_device_mapping["AMD INSTINCT MI300X"] = _device_mapping["AMD MI300X"] +_device_mapping["AMD INSTINCT MI210X"] = _device_mapping["AMD MI210X"] +_device_mapping["Intel(R) Arc(TM) B580 Graphics"] = _device_mapping["INTEL B580"] +_device_mapping["Intel(R) Arc(TM) Pro B70 Graphics"] = _device_mapping["INTEL B70"] + +# Enforce the upper-case-key invariant so entries cannot silently miss +# `lookup_device_info` (which upper-cases the query before lookup). +_device_mapping = {k.upper(): v for k, v in _device_mapping.items()} + + +def lookup_device_info(name: str) -> DeviceInfo | None: + """ + Problem: when diffing profiles between amd and nvidia, we don't have access to the device information + of the other one. Also, since the analysis is static, we should be able to do it on another device unrelated + to the recorded device. Therefore, _device_mapping statically contains the information for lots of devices. + If one is missing, please run DeviceInfo.get_device_info() and add it to _device_mapping. + name (str): name of the device to lookup. Should map onto torch.cuda.get_device_name(). + Will be upper-cased before lookup. + """ + return _device_mapping.get(name.upper()) + + +def datasheet_tops( + dtype: torch.dtype, is_tf32: bool = False, device_name: str | None = None +) -> float | None: + """ + Get the theoretical *dense* TFLOPS of the device for a given dtype. + + If the datasheet values include 2:4 structured sparsity + (``tops_sparsity_factor > 1``), they are divided by that factor so + callers always receive the throughput achievable by cuBLAS/cuDNN on + non-sparse data. + + If ``device_name`` is given, the datasheet is looked up for that named + device instead of querying the current device. This lets callers pin a + device spec for deterministic, hardware-independent estimates. + """ + if device_name is not None: + name: str | None = device_name + elif torch.cuda.is_available(): + name = torch.cuda.get_device_name() + elif torch.xpu.is_available(): + name = torch.xpu.get_device_name() + else: + log.info("No supported device available, skipping datasheet lookup") + return None + + if name is None: + log.info("No device found, returning None") + return None + device_info = lookup_device_info(name) + if device_info is None: + log_str = f"Device {name} not in datasheet, returning None" + log.info(log_str) + return None + if dtype not in device_info.tops: + log.info( + "Device %s does not have a datasheet entry for %s, returning None", + name, + dtype, + ) + return None + + tops = device_info.tops[ + "torch.tf32" if dtype == torch.float32 and is_tf32 else dtype + ] + return tops / device_info.tops_sparsity_factor + + +def datasheet_dram_bw_gbs(device_name: str | None = None) -> float | None: + """ + Get the theoretical DRAM bandwidth (GB/s) of a device from the datasheet, + or None if the device is not present. + + If ``device_name`` is given, that named device is looked up; otherwise the + current CUDA/XPU device is queried. + """ + if device_name is None: + if torch.cuda.is_available(): + device_name = torch.cuda.get_device_name() + elif torch.xpu.is_available(): + device_name = torch.xpu.get_device_name() + else: + log.info("No supported device available, skipping datasheet lookup") + return None + + if device_name is None: + log.info("No device found, returning None") + return None + + device_info = lookup_device_info(device_name) + if device_info is None: + log.info("Device %s not in datasheet, returning None", device_name) + return None + return device_info.dram_bw_gbs diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/profile_analysis.py b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/profile_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..9ba32ec7a16ca478ed5a72c1355520d083378f2d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/analysis/profile_analysis.py @@ -0,0 +1,859 @@ +import json +import logging +import math +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Optional + +import torch +from torch._inductor.analysis.device_info import DeviceInfo, lookup_device_info +from torch._inductor.utils import tabulate_2d, zip_dicts +from torch.utils import _pytree as pytree +from torch.utils._ordered_set import OrderedSet +from torch.utils.flop_counter import flop_registry + + +log = logging.getLogger(__name__) + + +ATEN_PREFIX = "aten::" + + +@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 + + +# adapters convert the json trace into a format that works with flops_counter +ArgsType = tuple[tuple[Any, ...], dict[Any, Any]] +AdapterType = Callable[[tuple[Any, ...], tuple[Any, ...]], ArgsType] +adapters_map: dict[str, AdapterType] = {} + + +def parse_list(lst: str) -> list[int]: + lst = lst.replace("[", "").replace("]", "") + substrings = lst.split(",") + + return [int(substring.strip()) for substring in substrings] + + +def register_adapter( + aten: str | list[str], +) -> Callable[ + [AdapterType], + AdapterType, +]: + def decorator(func: AdapterType) -> AdapterType: + # pyrefly: ignore [unknown-name] + global _adapters_map + + if isinstance(aten, str): + adapters_map[aten] = func + else: + for at in aten: + adapters_map[at] = func + return func + + return decorator + + +@register_adapter(["_slow_conv2d_forward"]) +def _slow_conv2d_adapter( + shapes: tuple[Any, ...], concrete: tuple[Any, ...] +) -> tuple[tuple[Any], dict[Any, Any]]: + tmp = list(shapes) + tmp.append(False) + tmp2 = list(concrete) + if len(tmp2) < 5: + raise ParseException("slow conv2d has less than 5 concrete inputs") + tmp2[3] = tmp2[4] + return conv_adapter(tuple(tmp), tuple(tmp2)) + + +@register_adapter( + ["convolution", "_convolution", "cudnn_convolution", "convolution_overrideable"] +) +def conv_adapter( + shapes: tuple[Any, ...], concrete: tuple[Any, ...] +) -> tuple[tuple[Any], dict[Any, Any]]: + tmp = list(shapes) + if len(tmp) == 4: + transposed = False + elif len(tmp) > 6: + transposed = bool(tmp[6]) + tmp[6] = transposed + else: + raise ParseException(f"Convolution has the wrong number of inputs: {len(tmp)}") + + kwargs: dict[Any, Any] = {} + if not transposed: + # calculate output shape if not transposed. + def conv_out_dims(x: int, kernel: int, stride: int) -> int: + return (x - kernel) // stride + 1 + + stride = parse_list(concrete[3]) + inp = shapes[0] + w = shapes[1] + out_x_y = [conv_out_dims(*args) for args in zip(inp[2:], w[2:], stride)] + out = [inp[0], w[0]] + out_x_y # we only need the xy values + kwargs["out_val"] = out + + return tuple(tmp), kwargs + + +def default_adapter( + shapes: tuple[Any], concrete: tuple[Any] +) -> tuple[tuple[Any], dict[Any, Any]]: + return shapes, {} + + +@register_adapter("addmm") +def addmm_adapter( + shapes: tuple[Any], concrete: tuple[Any] +) -> tuple[tuple[Any], dict[Any, Any]]: + tmp = list(shapes)[:3] + return tuple(tmp), {} + + +@register_adapter("bmm") +def bmm_adapter( + shapes: tuple[Any], concrete: tuple[Any] +) -> tuple[tuple[Any], dict[Any, Any]]: + tmp = list(shapes) + return tuple(tmp[:2]), {} + + +@register_adapter("baddbmm") +def baddbmm_adapter( + shapes: tuple[Any], concrete: tuple[Any] +) -> tuple[tuple[Any], dict[Any, Any]]: + tmp = list(shapes)[:3] + return tuple(tmp), {} + + +@register_adapter("mm") +def mm_adapter( + shapes: tuple[Any], concrete: tuple[Any] +) -> tuple[tuple[Any], dict[Any, Any]]: + return shapes, {} + + +def _parse_kernel_name(name: str) -> str | None: + """ + parse the name of the kernel from the event name. + """ + if name.startswith(ATEN_PREFIX): + return name[len(ATEN_PREFIX) :] + elif "conv" in name: + return "convolution" + elif "addmm" in name: + return "addmm" + elif "bmm" in name: + return "bmm" + elif "baddbmm" in name: + return "baddbmm" + elif "_mm" in name: + return "mm" + else: + return None + + +def _calculate_flops(event: dict[str, Any]) -> int: + """ + This function has to parse the kernel name, which is error prone. There doesn't seem to be another solution that + will support all the different backends that can generate kernels, so make sure to update this function when new + ops and backends are desired. + """ + name = event["name"] + if "kernel_flop" in event["args"] and event["args"]["kernel_flop"] != 0: + return event["args"]["kernel_flop"] + op_name = _parse_kernel_name(name) + if op_name is None: + return 0 + + op_obj = getattr(torch.ops.aten, op_name, None) + if op_obj is None or op_obj not in flop_registry: + return 0 + + flop_function = flop_registry[op_obj] + + if "Input Dims" not in event["args"] or "Concrete Inputs" not in event["args"]: + return 0 + input_shapes = event["args"]["Input Dims"] + concrete = event["args"]["Concrete Inputs"] + if op_name in adapters_map: + try: + args, kwargs = adapters_map[op_name](input_shapes, concrete) + except ParseException as e: + msg = f"Failed to parse {op_name} with {e}" + log.warning(msg) + return 0 + else: + try: + args, kwargs = default_adapter(input_shapes, concrete) + except ParseException as e: + msg = f"Failed to parse {op_name} with {e}" + log.warning(msg) + return 0 + return flop_function(*args, **kwargs) + + +def _get_size_from_string(type_string: str) -> int: + if not hasattr(torch, type_string): + return 1 + else: + return getattr(torch, type_string).itemsize + + +def _default_estimate_gb(event: dict[str, Any]) -> float: + sizes_and_types = zip(event["args"]["Input Dims"], event["args"]["Input type"]) + bw = 0 + for size, typ in sizes_and_types: + isize = _get_size_from_string(typ) + bw += isize * math.prod(pytree.tree_flatten(size)[0]) + return bw / 1e9 + + +def _estimate_gb(event: dict[str, Any]) -> float: + """ + Our best effort to estimate the gb, should be refactored soon with MemoryCounter. + """ + name = event["name"] + if "kernel_num_gb" in event["args"] and event["args"]["kernel_num_gb"] != 0: + return event["args"]["kernel_num_gb"] + if "Input type" not in event["args"] or "Input Dims" not in event["args"]: + return 0 + op_name = _parse_kernel_name(name) + if op_name is None: + return _default_estimate_gb(event) + + op_obj = getattr(torch.ops.aten, op_name, None) + if op_obj is None: + return _default_estimate_gb(event) + + if "Input Dims" not in event["args"] or "Concrete Inputs" not in event["args"]: + return _default_estimate_gb(event) + input_shapes = event["args"]["Input Dims"] + + # NOTE these will be refactored into a similar object to FlopCounter soon + def mm_formula(M: int, N: int, K: int, size: int) -> int: + return 2 * (M * K + N * K + M * N) * size + + if op_name == "addmm": + add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0]) + add_type_size = _get_size_from_string(event["args"]["Input type"][0]) + M = input_shapes[1][0] + N = input_shapes[1][1] + if input_shapes[1][1] != input_shapes[2][0]: + raise AssertionError( + f"Shape mismatch for addmm: {input_shapes[1][1]} != {input_shapes[2][0]}" + ) + K = input_shapes[2][1] + mul_type_size = _get_size_from_string(event["args"]["Input type"][1]) + return (mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size) / 1e9 + elif op_name == "mm": + M = input_shapes[0][0] + N = input_shapes[0][1] + if input_shapes[0][1] != input_shapes[1][0]: + raise AssertionError( + f"Shape mismatch for mm: {input_shapes[0][1]} != {input_shapes[1][0]}" + ) + K = input_shapes[1][1] + type_size = _get_size_from_string(event["args"]["Input type"][0]) + return mm_formula(M, N, K, type_size) / 1e9 + elif op_name == "baddbmm": + add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0]) + add_type_size = _get_size_from_string(event["args"]["Input type"][0]) + B = input_shapes[0][0] + M = input_shapes[1][1] + N = input_shapes[1][2] + K = input_shapes[2][2] + mul_type_size = _get_size_from_string(event["args"]["Input type"][1]) + return ( + B * mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size + ) / 1e9 + elif op_name == "bmm": + add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0]) + add_type_size = _get_size_from_string(event["args"]["Input type"][0]) + B = input_shapes[0][0] + M = input_shapes[0][1] + N = input_shapes[0][2] + K = input_shapes[1][2] + mul_type_size = _get_size_from_string(event["args"]["Input type"][1]) + return ( + B * mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size + ) / 1e9 + elif op_name in [ + "convolution", + "_convolution", + "cudnn_convolution", + "_slow_conv2d_forward", + ]: + concrete = event["args"]["Concrete Inputs"] + + def conv_out_dim(x: int, kernel: int, stride: int) -> int: + return (x - kernel) // stride + 1 + + stride = parse_list( + concrete[3] if op_name != "_slow_conv2d_forward" else concrete[4] + ) + inp = input_shapes[0] + w = input_shapes[1] + out_x_y = [conv_out_dim(*args) for args in zip(inp[2:], w[2:], stride)] + out = [inp[0], w[0]] + out_x_y + # each output element reads in * w * w chunk + input_reads = out[0] * out[1] * out[2] * out[3] * inp[1] * w[2] * w[3] + # Assume weights are in cache, so only read once + weight_reads = w[0] * w[1] * w[2] * w[3] + return (input_reads + weight_reads) / 1e9 + + return _default_estimate_gb(event) + + +def _create_extern_mapping( + data: dict[str, Any], +) -> defaultdict[int, list[dict[str, Any]]]: + """ + compute a mapping from external ids to non kernels, which contain the information we need to estimate flops etc + """ + extern_mapping: defaultdict[int, list[dict[str, Any]]] = defaultdict(list) + for event in data["traceEvents"]: + if ( + "args" not in event + or "External id" not in event["args"] + or event["cat"] != "cpu_op" + ): + continue + if len(extern_mapping[event["args"]["External id"]]) > 0: + raise ParseException("duplicate external id in event") + extern_mapping[event["args"]["External id"]].append(event) + return extern_mapping + + +def _augment_trace_helper(data: dict[str, Any]) -> dict[str, Any]: + extern_mapping = _create_extern_mapping(data) + + for event in data["traceEvents"]: + if "cat" not in event or event["cat"] != "kernel": + continue + if "args" not in event: + raise ParseException(f"kernel has no args: {event}") + if "External id" not in event["args"]: + event_str = f"kernel has no External id: {event}" + log.info(event_str) + continue + + external_op = extern_mapping[event["args"]["External id"]][0] + flops = _calculate_flops(external_op) + if flops == 0: + flops = _calculate_flops(event) + external_op["args"]["kernel_flop"] = flops + external_op["args"]["kernel_num_gb"] = _estimate_gb(external_op) + event["args"]["kernel_flop"] = external_op["args"]["kernel_flop"] + event["args"]["kernel_num_gb"] = external_op["args"]["kernel_num_gb"] + return data + + +_dtype_map: dict[str, torch.dtype] = { + "float": torch.float, + "float32": torch.float, + "double": torch.double, + "float64": torch.double, + "int": torch.int, + "int8": torch.int8, + "int16": torch.int16, + "int32": torch.int, + "long": torch.long, + "long int": torch.long, + "signed char": torch.int8, + "unsigned char": torch.uint8, + "bool": torch.bool, + "bfloat16": torch.bfloat16, + "float16": torch.float16, + "c10::BFloat16": torch.bfloat16, + "c10::Half": torch.float16, + "c10::complex": torch.complex64, + "c10::complex": torch.complex128, +} + + +@dataclass(frozen=True) +class KernelStats: + flops: int + bw: float + latency: float # us + achieved_flops: float + achieved_bandwidth: float + + +KernelNameMap = defaultdict[str, OrderedSet[KernelStats]] + + +@dataclass(frozen=False) +class Device: + name: str + index: int + info: DeviceInfo | None + stats: KernelNameMap + + def __repr__(self) -> str: + return f"Device({self.name}, {self.index}): {self.info}" + + +DeviceMap = dict[int, Device] +Table = tuple[list[str], dict[str, list[str]]] + + +class JsonProfile: + _devices: DeviceMap + + def __init__( + self, + path: str, + benchmark_name: str | None = None, + dtype: torch.dtype | str | None = None, + ): + """ + Convenience class for running common operations on chrome/perfetto json traces. + """ + self.path = path + with open(path) as f: + self.data = json.load(f) + self.events = self.data["traceEvents"] + self.benchmark_name = benchmark_name + if dtype is None: + self.dtype = None + elif isinstance(dtype, torch.dtype): + # pyrefly: ignore [bad-assignment] + self.dtype = dtype + else: + # pyrefly: ignore [bad-assignment] + self.dtype = _dtype_map.get(dtype) + self._create_devices() + + def convert_dtype(self, event: dict[str, Any]) -> torch.dtype | None: + """ + Each op has a list of dtypes for each input arg. We need to convert these into a single dtype for flop estimation. + Issues: + - converting the strings to concrete torch.dtypes + - What if we have float32, float, float16 all in the inputs? Our choice is to use the largest buffer dtype. + """ + + if ( + "Input Dims" not in event["args"] + or "Input type" not in event["args"] + or "Concrete Inputs" not in event["args"] + ): + if "bfloat16" in event["name"]: + return torch.bfloat16 + elif "float16" in event["name"]: + return torch.float16 + else: + return None + + input_sizes = event["args"]["Input Dims"] + input_types = event["args"]["Input type"] + concrete_inputs = event["args"]["Concrete Inputs"] + if len(input_sizes) != len(input_types): + raise AssertionError( + f"input_sizes and input_types length mismatch: " + f"{len(input_sizes)} != {len(input_types)}" + ) + if len(input_types) != len(concrete_inputs): + raise AssertionError( + f"input_types and concrete_inputs length mismatch: " + f"{len(input_types)} != {len(concrete_inputs)}" + ) + + if len(input_sizes) == 0: + raise RuntimeError("Empty input_sizes and input_types") + + biggest_size = 0 + biggest_index = 0 + for i in range(len(input_sizes)): + if concrete_inputs[i] != "": + # concrete inputs are usually small tensors, so we can just skip + continue + my_size = input_sizes[i] + total_size = sum(parse_list(my_size)) + if total_size > biggest_size: + biggest_size = total_size + biggest_index = i + ret_type = input_types[biggest_index] + if ret_type in _dtype_map: + return _dtype_map[ret_type] + raise RuntimeError(f"Unknown type: {ret_type}. Please add to _dtype_map.") + + def _create_devices(self) -> None: + self._devices = {} + for dev in self.data["deviceProperties"]: + name = dev["name"] + device_info = lookup_device_info(name) + + if device_info is None: + log.info( + "Unsupported device in profile: %s, please consider contributing to _device_mapping.", + name, + ) + self._devices[dev["id"]] = Device( + name, dev["id"], device_info, defaultdict(OrderedSet) + ) + + def calculate_flops(self, event: dict[str, Any]) -> int: + return _calculate_flops(event) + + def estimate_gb(self, event: dict[str, Any]) -> float: + return _estimate_gb(event) + + def augment_trace(self) -> None: + self.data = _augment_trace_helper(self.data) + + def _compute_stats(self) -> None: + """populates the name -> stats map""" + for event in self.events: + if "cat" not in event or "args" not in event or event["cat"] != "kernel": + continue + if "device" not in event["args"]: + continue + dev_tmp = event["args"]["device"] + if dev_tmp not in self._devices: + continue + dev = self._devices[event["args"]["device"]] + + dur = event["dur"] # us + if "kernel_flop" in event["args"]: + if dur == 0: + raise AssertionError( + "Event duration is 0 for kernel_flop calculation" + ) + # 1,000,000us/s * flop / us + op_flops = event["args"]["kernel_flop"] / (dur / 1e6) + else: + op_flops = 0 + + if "kernel_num_gb" in event["args"]: + if dur == 0: + raise AssertionError( + "Event duration is 0 for kernel_num_gb calculation" + ) + # 1,000,000us/s * gb = gb/s + op_gbps = event["args"]["kernel_num_gb"] / (dur / 1e6) + else: + op_gbps = 0 + + if dev.info is not None: + dtype = self.convert_dtype(event) or self.dtype + if dtype is None: + raise RuntimeError( + "dtype is not found on tensor and default dtype is not set" + ) + achieved_flops = 100 * op_flops / (1e12 * dev.info.tops[dtype]) + achieved_bandwidth = 100 * op_gbps / dev.info.dram_bw_gbs + else: + achieved_flops = 0 + achieved_bandwidth = 0 + + if "name" not in event["args"]: + continue + dev.stats[event["name"]].add( + KernelStats( + flops=op_flops, + bw=op_gbps, + latency=dur, + achieved_bandwidth=achieved_bandwidth, + achieved_flops=achieved_flops, + ) + ) + + def _create_single_table(self, dev: Device) -> Table: + """Create a table with the devices mapped to indices.""" + headers = [ + "Kernel Name", + "Kernel Count", + "FLOPS", + "Kernel Reads (GB)", + "Dur (us)", + "Achieved FLOPS %", + "Achieved Bandwidth %", + ] + rows: dict[str, list[str]] = {} + + def safe_div_format(x: float, y: float) -> str: + if y == 0: + return "0.0" + return f"{x / y:.4f}" + + for kernel_name, stats_set in dev.stats.items(): + ker_count = 0 + flops = 0 + flops_count = 0 + achieved_flops = 0.0 + bw = 0.0 + bw_count = 0 + achieved_bandwidth = 0.0 + latency = 0.0 + for stats in stats_set: + if stats.flops != 0: + flops += stats.flops + achieved_flops += stats.achieved_flops + flops_count += 1 + if stats.bw != 0: + bw += stats.bw + achieved_bandwidth += stats.achieved_bandwidth + bw_count += 1 + latency += stats.latency + ker_count += 1 + if ker_count == 0: + raise AssertionError("ker_count is 0 when computing kernel stats") + rows[kernel_name] = [ + str(ker_count), + safe_div_format(flops, flops_count), + safe_div_format(bw, bw_count), + safe_div_format(latency, ker_count), + safe_div_format(achieved_flops, flops_count), + safe_div_format(achieved_bandwidth, bw_count), + ] + + return headers, rows + + def _create_tables(self, devs: DeviceMap) -> dict[int, Table]: + return {idx: self._create_single_table(dev) for idx, dev in devs.items()} + + def _combine_tables( + self, table1: Table, table1_name: str, table2: Table, table2_name: str + ) -> Table: + new_headers = ( + ["Kernel Name"] + + [f"{table1_name} {head}" for head in table1[0][1:]] + + [f"{table2_name} {head}" for head in table2[0][1:]] + ) + t1_length = len(table1[0][1:]) + t2_length = len(table2[0][1:]) + new_rows = {} + + for key, row1, row2 in zip_dicts( + table1[1], + table2[1], + d1_default=["Empty"] * t1_length, + d2_default=["Empty"] * t2_length, + ): + if row1 is None: + raise AssertionError("row1 must not be None in table combination") + if row2 is None: + raise AssertionError("row2 must not be None in table combination") + new_rows[key] = row1 + row2 + return new_headers, new_rows + + def report( + self, other: Optional["JsonProfile"] = None, name_limit: int = 40 + ) -> str: + def create_ret( + table_headers: list[str], table_rows: dict[str, list[str]] + ) -> str: + table_flattened = [ + [kernel_name[:name_limit], *kernel_vals] + for kernel_name, kernel_vals in table_rows.items() + ] + return tabulate_2d(table_flattened, headers=table_headers) + + if other is not None: + self._compute_stats() + other._compute_stats() + + self_tables = self._create_tables(self._devices) + other_tables = self._create_tables(other._devices) + + self_name = ( + self.benchmark_name if self.benchmark_name is not None else "Table 1" + ) + other_name = ( + other.benchmark_name if other.benchmark_name is not None else "Table 2" + ) + + ret = [] + if self._devices.keys() != other._devices.keys(): + raise AssertionError( + f"Device key mismatch: {self._devices.keys()} != {other._devices.keys()}" + ) + for device_idx, t1, t2 in zip_dicts( + self_tables, other_tables, d1_default=None, d2_default=None + ): + if t1 is None: + raise AssertionError("t1 must not be None for device comparison") + if t2 is None: + raise AssertionError("t2 must not be None for device comparison") + table_headers, table_rows = self._combine_tables( + t1, self_name, t2, other_name + ) + tab_string = create_ret(table_headers, table_rows) + # pyrefly: ignore [bad-argument-type] + ret.append(f"{self._devices[device_idx]}:\n{tab_string}") + return "\n".join(ret) + self._compute_stats() + + self_tables = self._create_tables(self._devices) + + ret = [] + for idx, table in self_tables.items(): + table_headers, table_rows = table + tab_string = create_ret(table_headers, table_rows) + # pyrefly: ignore [bad-argument-type] + ret.append(f"{self._devices[idx]}:\n{tab_string}") + return "\n".join(ret) + + def dump(self, out: str) -> None: + with open(out, "w") as f: + json.dump(self.data, f) + + def combine_with(self, other: "JsonProfile") -> "JsonProfile": + """ + Combine this profile with another profile by merging their trace events. + Returns a new JsonProfile object with combined data. + """ + # Create a new combined data structure + combined_data = { + "traceEvents": self.data["traceEvents"] + other.data["traceEvents"], + "deviceProperties": self.data.get("deviceProperties", []), + } + + # Merge device properties, avoiding duplicates + other_device_props = other.data.get("deviceProperties", []) + existing_device_ids = OrderedSet( + [dev["id"] for dev in combined_data["deviceProperties"]] + ) + + for device_prop in other_device_props: + if device_prop["id"] not in existing_device_ids: + combined_data["deviceProperties"].append(device_prop) + + # Copy any other top-level properties from the first profile + for key, value in self.data.items(): + if key not in combined_data: + combined_data[key] = value + + import os + + # Create a temporary file to write the combined data + import tempfile + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".json", delete=False + ) as tmp_file: + json.dump(combined_data, tmp_file) + tmp_path = tmp_file.name + + try: + # Create new JsonProfile from the combined data + combined_profile = JsonProfile( + tmp_path, + benchmark_name=f"{self.benchmark_name or 'Profile1'}_+_{other.benchmark_name or 'Profile2'}", + dtype=self.dtype or other.dtype, + ) + return combined_profile + finally: + # Clean up temporary file + os.unlink(tmp_path) + + +class ParseException(RuntimeError): + pass + + +def main() -> None: + """ + Main function for the profile analysis script. + """ + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument( + "--diff", + nargs=5, + metavar=( + "input_file1", + "name1", + "input_file2", + "name2", + "dtype", + ), + help="Two json traces to compare with, specified as ", + ) + parser.add_argument( + "--name_limit", + type=int, + help="the maximum name size in the final report", + ) + parser.add_argument( + "--augment_trace", + "-a", + nargs=3, + metavar=("input_file", "output_file", "dtype"), + help="Augment a trace with inductor meta information. Provide input and output file paths.", + ) + parser.add_argument( + "--analysis", + nargs=2, + metavar=("input_file", "dtype"), + help="Run analysis on a single trace, specified as ", + ) + parser.add_argument( + "--combine", + nargs="+", + metavar=("input_files", "output_file"), + help="Combine multiple profiles into a single profile by merging trace events. Specify as \ + [input_file3 ...] . The last argument is the output file, all preceding arguments are \ +input files to combine.", + ) + args = parser.parse_args() + + if args.diff: + p1 = JsonProfile(args.diff[0], args.diff[1], dtype=args.diff[4]) + p1.augment_trace() + p2 = JsonProfile(args.diff[2], args.diff[3], dtype=args.diff[4]) + p2.augment_trace() + if args.name_limit: + print(p1.report(p2, name_limit=args.name_limit)) + else: + print(p1.report(p2)) + if args.analysis: + p1 = JsonProfile( + args.analysis[0], + dtype=args.analysis[1], + ) + p1.augment_trace() + if args.name_limit: + print(p1.report(name_limit=args.name_limit)) + else: + print(p1.report()) + if args.augment_trace: + p = JsonProfile(args.augment_trace[0], dtype=args.augment_trace[2]) + p.augment_trace() + p.dump(args.augment_trace[1]) + if args.combine: + input_files = args.combine[:-1] # All arguments except the last one + output_file = args.combine[-1] # Last argument is the output file + + if len(input_files) < 2: + print("Error: At least 2 input files are required for combining") + return + + # Load the first profile + combined = JsonProfile(input_files[0], dtype=None) + + # Iteratively combine with all other profiles + for input_file in input_files[1:]: + profile = JsonProfile(input_file, dtype=None) + combined = combined.combine_with(profile) + + combined.dump(output_file) + print(f"Successfully combined {', '.join(input_files)} into {output_file}") + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/analyze_preserves_zero_mask.py b/.venv/lib/python3.12/site-packages/torch/_inductor/analyze_preserves_zero_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..1e838eb90a2f0617e6f8518270f45a649c615c3d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/analyze_preserves_zero_mask.py @@ -0,0 +1,171 @@ +import dataclasses +import itertools +from typing import Any, TYPE_CHECKING + +import sympy + +import torch +from torch._inductor import config +from torch._inductor.dtype_propagation import DtypePropagationOpsHandler +from torch._inductor.index_propagation import SymPyOps, TypedExpr + +from .ops_handler import DefaultHandler +from .virtualized import StoreMode, V + + +if TYPE_CHECKING: + from torch._inductor.scheduler import SchedulerNode + + +def construct_symbol(count: int, dtype: torch.dtype) -> sympy.Symbol: + return sympy.Symbol(f"unknown_{count}") + + +class PreservesZeros(SymPyOps, DefaultHandler): + """ + For prologue kernels where the loads are masked, does the final store of this kernel preserve + the zeros. + """ + + def __init__(self) -> None: + self.count = itertools.count(0) + self.store_preserves_zeros: bool | None = None + self.dtype_prop = DtypePropagationOpsHandler() + + def load(self, name: str, index: sympy.Expr) -> TypedExpr: + # In prologue fusion, all loads get broadcasted + dtype = self.dtype_prop.load(name, index) + return TypedExpr( + sympy.Float(0) if dtype.is_floating_point else sympy.Integer(0), dtype + ) + + def store( + self, name: str, index: sympy.Expr, value: TypedExpr, mode: "StoreMode" = None + ) -> None: + if not isinstance(self, PreservesZeros): + raise AssertionError(f"expected PreservesZeros, got {type(self)}") + # should only have a single store in prologue + if self.store_preserves_zeros is not None: + raise AssertionError("prologue should only have a single store") + self.store_preserves_zeros = value.is_constant() and value.expr == 0 + + def indirect_indexing(self, *args: Any, **kwargs: Any) -> sympy.Expr: + return construct_symbol(next(self.count), torch.int32) + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + from torch._inductor.codegen.common import OpDecompositions + + if hasattr(OpDecompositions, name): + return getattr(OpDecompositions, name)(*args, **kwargs).value + + dtype = getattr(self.dtype_prop, name)(*args, **kwargs) + return TypedExpr(construct_symbol(next(self.count), dtype), dtype) + + +def prologue_preserves_zero_mask(prologue: "SchedulerNode") -> bool: + """ + Does this prologue preserve zero masks + """ + preserves_zeros = PreservesZeros() + with V.set_ops_handler(preserves_zeros): + prologue._body(*prologue.get_ranges()) + + store_preserves_zeros = preserves_zeros.store_preserves_zeros + if not isinstance(store_preserves_zeros, bool): + raise AssertionError( + f"expected bool store_preserves_zeros, got {type(store_preserves_zeros)}" + ) + + return store_preserves_zeros + + +@dataclasses.dataclass +class DTypeContainer: + dtype: torch.dtype + is_scalar: bool = False + + +class RecordLowPrecisionOps(DefaultHandler): + def __init__(self, disallow_fp32_ops: bool = False) -> None: + self.disallow_fp32_ops = disallow_fp32_ops + self.low_precision_numeric_op = False + self.dtype_prop = DtypePropagationOpsHandler() + self.non_numeric_ops = ( + "to_dtype", + "constant", + "where", + ) + + def load(self, name: str, index: sympy.Expr) -> DTypeContainer: + return DTypeContainer(self.dtype_prop.load(name, index)) + + @staticmethod + def store( + name: str, index: sympy.Expr, value: TypedExpr, mode: "StoreMode" = None + ) -> None: + pass + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + pass + + @staticmethod + # pyrefly: ignore [bad-override] + def indirect_indexing(*args: Any, **kwargs: Any) -> sympy.Expr: + return sympy.S.Zero + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + out_dtype = getattr(self.dtype_prop, name)(*args, **kwargs) + out = DTypeContainer(out_dtype, is_scalar=(name == "constant")) + if name == "constant": + return DTypeContainer(torch.float, is_scalar=True) + + uses_low_prec = any( + isinstance(dtype_cont, DTypeContainer) + and dtype_cont.dtype is not None + and low_prec_float(dtype_cont.dtype) + for dtype_cont in itertools.chain((out,), args, kwargs.values()) + ) + + if uses_low_prec and name not in self.non_numeric_ops: + self.low_precision_numeric_op = True + + if ( + self.disallow_fp32_ops + and out.dtype in (torch.float32, torch.float64) + and not out.is_scalar + ): + self.low_precision_numeric_op = True + + return out + + +def low_prec_float(dtype: torch.dtype) -> bool: + return dtype.is_floating_point and dtype.itemsize < 4 + + +def can_codegen_without_upcasts( + prologue: "SchedulerNode", + disallow_fp32_ops: bool = False, +) -> bool: + """ + Can this prologue be run without `upcast_to_fp32` while preserving numerics. + + This is only true if the node only contains dtype conversions, indexing, and other non-arithmetic operators. + + If disallow_fp32_ops is True, then we also disallow ops that are explicitly computed in fp32 or fp64. + """ + if prologue.get_operation_names() <= V.graph.low_precision_codegen_ops: + return True + + low_prec_analysis = RecordLowPrecisionOps(disallow_fp32_ops) + + # Need to turn off upcasting to do analysis of whether we can turn it off + with ( + config.patch("triton.codegen_upcast_to_fp32", False), + V.set_ops_handler(low_prec_analysis), + ): + prologue._body(*prologue.get_ranges()) + + return not low_prec_analysis.low_precision_numeric_op diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/aoti_eager.py b/.venv/lib/python3.12/site-packages/torch/_inductor/aoti_eager.py new file mode 100644 index 0000000000000000000000000000000000000000..1b4afe242d25b189b779a89453e45db5355ae9c7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/aoti_eager.py @@ -0,0 +1,388 @@ +import json +import logging +import os +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any +from unittest import mock + +import torch +import torch._export +from torch._inductor.utils import is_cpu_device + +from .runtime.runtime_utils import cache_dir + + +log = logging.getLogger(__name__) + + +@dataclass +class AOTICompileBackend: + compile_fn: Callable[..., str] + load_fn: Callable[[str, str, str], list[dict[str, Any] | None]] + + +_aoti_compile_backends: dict[str, AOTICompileBackend] = {} + + +def register_aoti_compile_backend( + device_type: str, + compile_fn: Callable[..., str], + load_fn: Callable[[str, str, str], list[dict[str, Any] | None]], +) -> None: + _aoti_compile_backends[device_type] = AOTICompileBackend( + compile_fn=compile_fn, + load_fn=load_fn, + ) + + +def aoti_eager_cache_dir(namespace: str, device: str) -> Path: + return Path(cache_dir()) / "aoti_eager" / namespace / device + + +def aoti_eager_op_conf_lock(op_func_name_with_overload: str) -> Any: + # Avoid circular import + from torch._inductor.codecache import get_lock_dir, LOCK_TIMEOUT + from torch.utils._filelock import FileLock + + op_conf_lock_file = f"{op_func_name_with_overload}.lock" + lock_dir = get_lock_dir() + return FileLock(os.path.join(lock_dir, op_conf_lock_file), timeout=LOCK_TIMEOUT) + + +def load_aoti_eager_cache( + ns: str, op_func_name_with_overload: str, device_type: str +) -> list[dict[str, Any] | None]: + backend = _aoti_compile_backends.get(device_type) + if backend: + return backend.load_fn(ns, op_func_name_with_overload, device_type) + + device_kernel_cache = aoti_eager_cache_dir(ns, device_type) + op_conf = device_kernel_cache / f"{op_func_name_with_overload}.json" + if not op_conf.exists(): + return [] + + try: + with aoti_eager_op_conf_lock(op_func_name_with_overload): + with open(op_conf) as f: + json_data = json.load(f) + for item in json_data: + # Get absolute path for kernel library + kernel_lib_abs_path = device_kernel_cache / item["kernel_path"] + item["kernel_path"] = kernel_lib_abs_path.as_posix() + + # Check if the kernel library exists + if not kernel_lib_abs_path.exists(): + return [] + + for metadata in item["meta_info"]: + if metadata.get("is_dynamic"): + raise NotImplementedError( + "Only support static shape for now" + ) + if ( + "device_type" in metadata + and metadata["device_type"] == "cpu" + ): + metadata["device_index"] = -1 + for dtype_key in ["dtype", "dtype_value"]: + if dtype_key in metadata: + metadata[dtype_key] = getattr( + torch, metadata[dtype_key].split(".")[-1] + ) + if "layout_value" in metadata: + metadata["layout_value"] = getattr( + torch, metadata["layout_value"].split(".")[-1] + ) + if "memory_format_value" in metadata: + metadata["memory_format_value"] = getattr( + torch, metadata["memory_format_value"].split(".")[-1] + ) + + return json_data + except Exception as e: + err_msg = f"Failed to load aoti eager cache: {e}" + log.exception(err_msg) + return [] + + +def supported_builtin_dtype_torch_dtype() -> dict[type, torch.dtype]: + return {int: torch.int32, float: torch.float, bool: torch.bool} + + +def supported_scalar_types() -> tuple[type, ...]: + type_to_torch_dtype = supported_builtin_dtype_torch_dtype() + return tuple(type_to_torch_dtype.keys()) + + +def extract_tensor_metadata(dynamic: bool, input: torch.Tensor) -> dict[str, Any]: + metadata: dict[str, Any] = {} + metadata["is_dynamic"] = dynamic + + if not isinstance(input, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(input)}") + metadata["device_type"] = f"{input.device.type}" + if is_cpu_device([input]): + metadata["device_index"] = -1 + else: + metadata["device_index"] = input.device.index + metadata["dtype"] = f"{input.dtype}" + metadata["sizes"] = list(input.size()) + metadata["strides"] = list(input.stride()) + metadata["requires_grad"] = input.requires_grad + metadata["dispatch_key_set"] = torch._C._dispatch_keys(input).raw_repr() + return metadata + + +def extract_tensor_list_metadata( + dynamic: bool, + input: list[torch.Tensor], +) -> dict[str, Any]: + metadata_list = [] + for item in input: + if not isinstance(item, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(item)}") + metadata_list.append(extract_tensor_metadata(dynamic, item)) + + metadata: dict[str, Any] = {} + metadata["tensor_list"] = metadata_list + return metadata + + +def extract_scalar_metadata(device_type: str, input: Any) -> dict[str, Any]: + if not isinstance(input, supported_scalar_types()): + raise AssertionError(f"expected a supported scalar type, got {type(input)}") + metadata: dict[str, Any] = {} + metadata["is_dynamic"] = False + # Scalar tensor + metadata["device_type"] = device_type + metadata["device_index"] = -1 if device_type == "cpu" else 0 + type_to_torch_dtype = supported_builtin_dtype_torch_dtype() + metadata["dtype"] = f"{type_to_torch_dtype[type(input)]}" + metadata["scalar_value"] = input + return metadata + + +def extract_string_metadata(input: str) -> dict[str, Any]: + if not isinstance(input, str): + raise AssertionError(f"expected str, got {type(input)}") + metadata: dict[str, Any] = {} + metadata["string_value"] = input + return metadata + + +def extract_dtype_metadata(input: torch.dtype) -> dict[str, Any]: + if not isinstance(input, torch.dtype): + raise AssertionError(f"expected torch.dtype, got {type(input)}") + metadata: dict[str, Any] = {} + metadata["dtype_value"] = f"{input}" + return metadata + + +def extract_device_metadata(input: torch.device) -> dict[str, Any]: + if not isinstance(input, torch.device): + raise AssertionError(f"expected torch.device, got {type(input)}") + metadata: dict[str, Any] = {} + metadata["device_type_value"] = f"{input.type}" + metadata["device_index_value"] = input.index + return metadata + + +def extract_layout_metadata(input: torch.layout) -> dict[str, Any]: + if not isinstance(input, torch.layout): + raise AssertionError(f"expected torch.layout, got {type(input)}") + metadata: dict[str, Any] = {} + metadata["layout_value"] = f"{input}" + return metadata + + +def extract_int_list_metadata(input: list[int]) -> dict[str, Any]: + if not ( + isinstance(input, (list, tuple)) + and all(isinstance(item, int) and not isinstance(item, bool) for item in input) + ): + raise AssertionError(f"expected a list/tuple of int, got {input!r}") + metadata: dict[str, Any] = {} + metadata["int_list_value"] = list(input) + return metadata + + +def aoti_compile_with_persistent_cache( + ns: str, + op_func_name_with_overload: str, + device_type: str, + dynamic: bool, + f: Callable[..., Any], + args: tuple[Any], + kwargs: dict[str, Any], + *, + dynamic_shapes: dict[str, Any] | None = None, + options: dict[str, Any] | None = None, + remove_runtime_assertions: bool = False, + disable_constraint_solver: bool = False, +) -> str: + """ + Compile the given function with persistent cache for AOTI eager mode. + """ + backend = _aoti_compile_backends.get(device_type) + if backend: + return backend.compile_fn( + ns, + op_func_name_with_overload, + device_type, + dynamic, + f, + args, + kwargs, + dynamic_shapes=dynamic_shapes, + options=options, + remove_runtime_assertions=remove_runtime_assertions, + disable_constraint_solver=disable_constraint_solver, + ) + + if dynamic: + raise AssertionError("Only support static shape for now") + flattened_inputs = list(args) + list(kwargs.values()) + if not all( + isinstance( + input, + ( + supported_scalar_types(), + torch.Tensor, + list, + str, + torch.dtype, + torch.device, + torch.layout, + ), + ) + for input in flattened_inputs + ): + err_msg = f"Unsupported input types: {flattened_inputs}" + log.exception(err_msg) + raise NotImplementedError(err_msg) + + for input in flattened_inputs: + if isinstance(input, list) and not all( + isinstance(item, torch.Tensor) for item in input + ): + err_msg = f"_impl_with_aoti_compile encounters unsupported input types: {flattened_inputs}" + log.exception(err_msg) + raise NotImplementedError(err_msg) + + persistent_cache = aoti_eager_cache_dir(ns, device_type) + if not persistent_cache.exists(): + persistent_cache.mkdir(parents=True) + + persistent_cache_lib = persistent_cache / "lib" + if not persistent_cache_lib.exists(): + persistent_cache_lib.mkdir() + + with mock.patch.dict( + os.environ, + {"TORCHINDUCTOR_CACHE_DIR": persistent_cache_lib.absolute().as_posix()}, + ): + try: + kernel_lib_path = torch._export.aot_compile( + f, + args, + kwargs, + dynamic_shapes=dynamic_shapes, + remove_runtime_assertions=remove_runtime_assertions, + disable_constraint_solver=disable_constraint_solver, + # Some operations may have non-Tensor parameters like int, float, bool. These + # non-Tensor parameters will not be the input of the graph. Therefore, we do + # need to keep the same signature. + same_signature=False, + ) + if not isinstance(kernel_lib_path, str): + raise AssertionError( + f"expected kernel_lib_path to be str, got {type(kernel_lib_path)}" + ) + + kernel_metadata_items = [] + + for idx, input in enumerate(flattened_inputs): + # Skip explicit-None args (e.g. an optional `int[1]? dim`) so the + # written metadata vector matches the cache reader, which also + # drops None entries. + if input is None: + continue + if isinstance(input, torch.Tensor): + metadata = extract_tensor_metadata(dynamic, input) + elif isinstance(input, (list, tuple)) and all( + isinstance(item, int) and not isinstance(item, bool) + for item in input + ): + # `int[]` / `SymInt[]` params. Checked before the Tensor-list + # branch so an empty list/tuple is tagged INT_LIST, matching + # the cache reader and C++ unpack_input_parameters for an + # empty `int[]`. An empty `Tensor[]` is the converse case: + # C++ tags it TENSOR_LIST (isTensorList() is checked before + # isIntList()) while this tags it INT_LIST -- only a cache + # miss/recompile (per-op cache, fixed schema type per slot -> + # no aliasing), and it does not arise for real ops + # (`cat([])`/`stack([])` raise in eager). + metadata = extract_int_list_metadata(list(input)) + elif isinstance(input, (list, tuple)) and all( + isinstance(item, torch.Tensor) for item in input + ): + metadata = extract_tensor_list_metadata(dynamic, list(input)) + elif isinstance(input, supported_scalar_types()): + metadata = extract_scalar_metadata(device_type, input) + elif isinstance(input, str): + metadata = extract_string_metadata(input) + elif isinstance(input, torch.dtype): + metadata = extract_dtype_metadata(input) + elif isinstance(input, torch.device): + metadata = extract_device_metadata(input) + elif isinstance(input, torch.layout): + metadata = extract_layout_metadata(input) + else: + raise NotImplementedError(f"Unsupported input type: {type(input)}") + + metadata["arg_order"] = idx + kernel_metadata_items.append(metadata) + + kernel_meta_info: dict[str, Any] = {} + kernel_meta_info["meta_info"] = kernel_metadata_items + kernel_meta_info["kernel_path"] = ( + Path(kernel_lib_path).relative_to(persistent_cache).as_posix() + ) + + json_data = [] + update_json = True + op_conf = persistent_cache / f"{op_func_name_with_overload}.json" + mode = "r" if op_conf.exists() else "w" + with aoti_eager_op_conf_lock(op_func_name_with_overload): + with open(op_conf, mode) as op_conf_file: + try: + json_data = json.load(op_conf_file) + except Exception: + json_data = [] + + if not isinstance(json_data, list): + raise AssertionError( + f"expected json_data to be list, got {type(json_data)}" + ) + for item in json_data: + if not isinstance(item, dict): + raise AssertionError( + f"expected item to be dict, got {type(item)}" + ) + # Same kernel meta info already exists in the json file + if item["meta_info"] == kernel_metadata_items: + update_json = False + break + + if update_json: + json_data.append(kernel_meta_info) + with open(op_conf, "w") as op_conf_file: + json.dump(json_data, op_conf_file, indent=4) + + return kernel_lib_path + except Exception as e: + err_msg = f"Failed to compile {op_func_name_with_overload}: {e}" + log.exception(err_msg) + return "" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/async_compile.py b/.venv/lib/python3.12/site-packages/torch/_inductor/async_compile.py new file mode 100644 index 0000000000000000000000000000000000000000..8c8c84be48acd161157983c03fa3c25a29c6d58c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/async_compile.py @@ -0,0 +1,987 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import atexit +import functools +import json +import logging +import multiprocessing +import os +import re +import sys +from concurrent.futures import ( + Future, + ThreadPoolExecutor, + TimeoutError as FuturesTimeoutError, +) +from concurrent.futures.process import BrokenProcessPool +from functools import partial +from time import time, time_ns +from typing import Any, TYPE_CHECKING + +import torch +from torch._dynamo.device_interface import get_registered_device_interfaces +from torch._dynamo.utils import ( + counters, + dynamo_timed, + get_metrics_context, + set_feature_use, +) +from torch._inductor import config +from torch._inductor.codecache import ( + _load_triton_kernel_from_source, + code_hash, + CodeCacheFuture, + CppCodeCache, + CppPythonBindingsCodeCache, + CUDACodeCache, + HalideCodeCache, + LambdaFuture, + ROCmCodeCache, + StaticAutotunerFuture, + torch_key, + XPUCodeCache, +) +from torch._inductor.compile_worker.subproc_pool import ( + AnyPool, + SubprocException, + SubprocPool, +) +from torch._inductor.compile_worker.tracked_process_pool import ( + TrackedProcessPoolExecutor, +) +from torch._inductor.compile_worker.utils import _async_compile_initializer +from torch._inductor.runtime.compile_tasks import ( + _set_triton_libdevice_path, + _set_triton_ptxas_path, + _worker_compile_pycodecache_kernel, + _worker_compile_triton, +) +from torch._inductor.utils import clear_on_fresh_cache +from torch._inductor.virtualized import V +from torch._utils_internal import log_triton_builds +from torch.hub import _Faketqdm, tqdm +from torch.utils._ordered_set import OrderedSet +from torch.utils._triton import has_triton_package + + +if TYPE_CHECKING: + from collections.abc import Callable + + from torch._inductor.runtime.hints import HalideMeta + from torch._inductor.runtime.triton_heuristics import CachingAutotuner + +# timing metrics for time spent in the compilation +_cumulative_compile_time = 0.0 +_t0: float | None = None + +kernel_code_log = torch._logging.getArtifactLogger(__name__, "kernel_code") + +log = logging.getLogger(__name__) + +_triton_kernel_metrics: dict[str, dict[str, Any]] | None = None + +size_hints_regex = re.compile( + r"size_hints=(\{.*?\})", +) + + +def _pycodecache_kernel_compile_env() -> dict[str, str | None]: + env_vars = [ + "TORCHINDUCTOR_CACHE_DIR", + "TRITON_CACHE_DIR", + "TORCHINDUCTOR_CUTLASS_DIR", + ] + return {v: os.environ.get(v) for v in env_vars} + + +def pre_fork_setup(): + """ + Setup that must be done prior to forking with a process pool. + """ + # ensure properties have been calculated before processes + # are forked + caching_device_properties() + + # Computing the triton key can be slow. If we call it before fork, + # it will be cached for the forked subprocesses. + from torch._inductor.runtime.triton_compat import HAS_TRITON, triton_key + + if HAS_TRITON: + triton_key() + + +def caching_device_properties(): + for _, device_interface in get_registered_device_interfaces(): + if device_interface.is_available(): + device_interface.Worker.get_device_properties() + + +def _compile_start() -> None: + global _t0, _triton_kernel_metrics + if _t0 is None: + _t0 = time() + if _triton_kernel_metrics is None: + _triton_kernel_metrics = {} + + +def _compile_end() -> None: + global _cumulative_compile_time, _t0, _triton_kernel_metrics + if _t0 is not None: + t1 = time() + _cumulative_compile_time += t1 - _t0 + _t0 = None + # print("CUMULATIVE COMPILE TIME", _cumulative_compile_time) + if _triton_kernel_metrics: + # Log triton kernel info + sorted_info = dict(sorted(_triton_kernel_metrics.items())) + torch._logging.trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "triton_kernel_info", + "encoding": "json", + }, + payload_fn=lambda: json.dumps(sorted_info), + ) + _triton_kernel_metrics = None + + +def _add_triton_kernel_info(kernel_name: str, info: dict[str, Any]): + global _triton_kernel_metrics + # Must be called between _compile_start and _compile_end + if _triton_kernel_metrics is not None: + _triton_kernel_metrics[kernel_name] = info + + +def _emit_triton_kernel_compile_metric( + kernel: CachingAutotuner, + kernel_name: str, + elapsed_us: int, +) -> None: + """Emit per-kernel ``compile_time_us`` to both the dynamo + ``_triton_kernel_metrics`` map and the ``MetricsContext`` top-N. + + Note: ``kernel.autotune_cache_info`` is only mutated in place when + non-empty; when ``None`` or ``{}`` the metric still reaches + ``_triton_kernel_metrics`` via a throwaway dict, but the kernel + attribute stays untouched. + """ + info = kernel.autotune_cache_info or {} + info["compile_time_us"] = elapsed_us + _add_triton_kernel_info(kernel_name, info) + get_metrics_context().add_top_n( + "triton_kernel_compile_times_us", kernel_name, elapsed_us + ) + + +_IS_WINDOWS = sys.platform == "win32" + +log = logging.getLogger(__name__) + +# Used to keep track of all process pools invoked so far. +_pool_set = OrderedSet[AnyPool]() + + +def shutdown_compile_workers() -> None: + """Shut down all outstanding compile-worker pools.""" + for pool in _pool_set: + pool.shutdown() + AsyncCompile._ready_future = None + after_fork() + + +def after_fork(): + """Reset pools to initial state without shutting them down""" + _pool_set.clear() + AsyncCompile._ready_future = None + AsyncCompile.process_pool.cache_clear() + + +try: + os.register_at_fork(after_in_child=after_fork) +except AttributeError: + pass # register_at_fork does not exist on windows + + +def get_compile_threads() -> int: + """ + Temporary for internal rollout. Assign config.compile_threads lazily and return it. + TODO: remove after rollout. + """ + if config.compile_threads is None: + config.compile_threads = config.decide_compile_threads() + return config.compile_threads + + +def _process_pool_allowed() -> bool: + # Multiprocessing daemons are not allowed to create child processes. This + # only applies to direct multiprocessing modes: SubprocPool starts its + # sidecar with subprocess.Popen, so the sidecar does not inherit the + # multiprocessing daemon flag and can own its own ProcessPoolExecutor. + return ( + config.worker_start_method == "subprocess" + or not multiprocessing.current_process().daemon + ) + + +@clear_on_fresh_cache +class CompiledTritonKernels: + """ + In memory cache for storing compiled triton kernels. + + Each triton kernel is keyed by the hash of its source code. Each value stored + in the cache is a return value of AsyncCompile.triton(). + + Currently, the cache stores Future objects, but it should be generalizable for any kernels. + """ + + _cache: dict[str, CodeCacheFuture] = {} + + @staticmethod + def key(kernel_src: str): + """ + Generates a cache key given a triton kernel's full source code. + This source includes the inductor meta, compilation metadata, the kernel itself, etc. + `kernel_src` should be the exact string passed to async_compile.triton()'s first argument. + """ + # Hashes the kernel source with torch_key into a single hash key + return code_hash(kernel_src, extra=torch_key()) + + @staticmethod + def save(kernel_src: str, future: CodeCacheFuture): + """ + Saves a compiled triton kernel to the cache. + TODO: We store a LambdaFuture as that's the callable returned by async_compile.triton, + but the real type we want to return here is actually an abstract triton kernel. + + TODO: Source code here is not just the kernel's source code, but also includes the inductor preamble, etc. + so it could be less strict. + """ + key = CompiledTritonKernels.key(kernel_src) + CompiledTritonKernels._cache[key] = future + + @staticmethod + def get(kernel_src: str) -> CodeCacheFuture | None: + key = CompiledTritonKernels.key(kernel_src) + return CompiledTritonKernels._cache.get(key, None) + + @staticmethod + def cache_clear(): + CompiledTritonKernels._cache = {} + + @staticmethod + def remove_future(kernel_src: str) -> None: + key = CompiledTritonKernels.key(kernel_src) + + # Delete the LambdaFuture if there is one + if key in CompiledTritonKernels._cache: + del CompiledTritonKernels._cache[key] + + +class AsyncCompile: + """ + Utilities to compile in thread pools or subprocess pools (in the case of Triton). + """ + + _ready_future: Future[Any] | None = None + _metal_sources: list[tuple[str, str, list[str]]] | None = None + + def __init__(self) -> None: + pass + + @staticmethod + @functools.lru_cache(1) + def pool() -> ThreadPoolExecutor: + if get_compile_threads() <= 1: + raise AssertionError( + f"expected get_compile_threads() > 1, got {get_compile_threads()}" + ) + return ThreadPoolExecutor(get_compile_threads()) + + @staticmethod + def _get_ready(): + """No-op function to help mark when the subprocess pool is ready.""" + return "ready" + + @staticmethod + @functools.lru_cache(1) + def process_pool() -> AnyPool: + if get_compile_threads() <= 1: + raise AssertionError( + f"expected get_compile_threads() > 1, got {get_compile_threads()}" + ) + if not _process_pool_allowed(): + raise RuntimeError( + "Inductor async compile process pools are disabled in daemonic " + "multiprocessing processes. Set " + "torch._inductor.config.worker_start_method = 'subprocess' " + "(or TORCHINDUCTOR_WORKER_START=subprocess) to use the " + "SubprocPool path, which is not affected by the daemon restriction." + ) + AsyncCompile._ready_future = None + log.info( + "Creating '%s' pool with %d workers", + config.worker_start_method, + get_compile_threads(), + ) + + pool: AnyPool + if config.worker_start_method == "subprocess": + # Wrapper around ProcessPoolExecutor forks in a new process we control + pool = SubprocPool( + get_compile_threads(), quiesce=config.quiesce_async_compile_pool + ) + else: + if config.worker_start_method == "spawn": + # Avoid creating pools in the spawned subprocs themselves: + os.environ["TORCH_WARM_POOL"] = "0" + pre_fork_setup() + ctx = multiprocessing.get_context(config.worker_start_method) + pool = TrackedProcessPoolExecutor( + get_compile_threads(), + mp_context=ctx, + initializer=partial(_async_compile_initializer, os.getpid()), + ) + + # When this pool is created in a multiprocessing subprocess, the normal + # atexit handler may not run, and we need to register our own handler. + # exitpriority has to be high, because another one of the finalizers will + # kill the worker thread that sends the shutdown message to the workers. + multiprocessing.util.Finalize(None, pool.shutdown, exitpriority=sys.maxsize) + + _pool_set.add(pool) + return pool + + @classmethod + def warm_pool(cls) -> None: + if get_compile_threads() <= 1 or not _process_pool_allowed(): + return + _compile_start() + # Pool is created on first access. Note for a SubprocPool, the sidecar process starts, + # but its ProcessPoolExecutor does not initialize until a wakeup() call or the first + # job is submitted. + cls.process_pool() + _compile_end() + + @classmethod + def wait_pool_ready(cls, timeout=120) -> None: + cls.use_process_pool() + if cls._ready_future is not None: + cls._ready_future.result(timeout=timeout) + + @classmethod + def submit(cls, task: Callable[..., Any]) -> Any: + if get_compile_threads() <= 1: + return task() + return cls.pool().submit(task) + + @classmethod + def use_process_pool(cls): + if get_compile_threads() <= 1 or not _process_pool_allowed(): + return False + + # Proton instrumentation backend requires compilation to happen in the main + # process so it can instrument the Triton IR during JIT compilation. + # Force synchronous compilation when proton profiling is enabled. + if config.triton.proton_profiling: + return False + + # Create a dummy job to check if the pool is ready. Submit it here instead of at + # pool creation so we don't launch the full pool of worker subprocesses until + # we're sure they're needed. + if not cls._ready_future: + cls._ready_future = cls.process_pool().submit(cls._get_ready) + return cls._ready_future.done() + + @classmethod + def wait_process_pool_ready(cls, timeout: float = 120) -> bool: + """Block (up to ``timeout`` s) until the process pool is ready, returning + whether it's usable. + + Like use_process_pool() but blocking. Use when a backend's serial + fallback is far costlier than the warmup wait -- e.g. NVGEMM subprocess + precompile, where skipping the pool forces ~15x-slower lazy compilation + at benchmark time. (use_process_pool()'s non-blocking readiness check can + race pool warmup when little other compilation precedes the decision.) + On timeout, degrade gracefully (return False -> serial) rather than hang + on a stuck worker. + """ + if get_compile_threads() <= 1 or not _process_pool_allowed(): + return False + if config.triton.proton_profiling: + return False + if not cls._ready_future: + cls._ready_future = cls.process_pool().submit(cls._get_ready) + try: + cls._ready_future.result(timeout=timeout) + except FuturesTimeoutError: + log.warning( + "Process pool not ready after %ss; falling back to serial", timeout + ) + return False + except (BrokenProcessPool, RuntimeError) as e: + # A warmup worker died or the pool was closed. The readiness probe + # failing must degrade to serial (the documented contract), not + # propagate and abort the caller's algorithm selection. + log.warning("Process pool unusable (%s); falling back to serial", e) + return False + return True + + @classmethod + def wakeup(cls) -> None: + """ + If using a SubprocPool, signal the sidecar process to start up its + ProcessPoolExecutor. + """ + if not cls.use_process_pool(): + return + pool = cls.process_pool() + if isinstance(pool, SubprocPool): + pool.wakeup() + + def triton(self, kernel_name: str, source_code: str, device_str: str = "cuda"): + """ + Async_compile.triton is more complicated than the other backends because + we're trying to optimize compile time as much as possible for this hot callsite. + + First of all, the function is cached by CompiledTritonKernels; if there's a kernel + already compiled, we grab it directly from the cache and return. + + Otherwise, if we have multiple compile threads, we kick off triton compilations on each + worker process by giving it a kernel and source code to compile. The worker initializes + a CachingAutotuner, runs triton compilation, and pickles the kernel back to us. + We use TritonCompileResult to represent the objects being pickled back to us by each + worker. + + Some maybe not obvious things that are pickled back to us: + - Most of the time, we can avoid sending back CachingAutotuner.fn and other metadata + and do not have to pay the cost of loading the triton kernel on the parent. But certain + cases, like coordesc tuning and dynamic_scale_rblock, require us to reload the function + in the parent lazily when we require it. + - The AutotuneCache, if enabled, is constructed on each worker per triton config + and pickled by to us via `CachingAutotuner.save_cache_hook`. + """ + load_kernel = functools.partial( + _load_triton_kernel_from_source, kernel_name, source_code + ) + + def reload_kernel_in_parent(): + # Benchmark how often this happens + with dynamo_timed("reload_kernel_in_parent"): + return load_kernel() + + counters["inductor"]["async_compile_cache_miss"] += 1 + + kernel_code_log.info("Triton Kernel:\n%s", source_code) + _compile_start() + + if os.environ.get("TRITON_INTERPRET", "0") == "1": + return getattr( + torch._inductor.codecache.PyCodeCache.load(source_code), kernel_name + ) + + is_parallel = self.use_process_pool() + set_feature_use("parallel_compile_post_warmup", is_parallel) + + compile_id = torch._guards.CompileContext.current_compile_id() + is_backward = getattr(V.graph, "is_backward", False) + + if (future := CompiledTritonKernels.get(source_code)) is not None: + counters["inductor"]["async_compile_cache_hit"] += 1 + # Set reload_kernel_from_src properly based on source_code + if isinstance(future, StaticAutotunerFuture): + # Remove the future now that we've cache hit + CompiledTritonKernels.remove_future(source_code) + future.reload_kernel_from_src = reload_kernel_in_parent + if is_parallel: + return future + else: + return future.result() + + # Cache miss + if is_parallel: + # Ensure libdevice path is set in os.environ before passing to workers + _set_triton_libdevice_path() + # We want to support changing these env vars after (and while) the + # process pool is running, so pass them to the subprocess to reset. + env_vars = [ + "TORCHINDUCTOR_CACHE_DIR", + "TRITON_CACHE_DIR", + "TRITON_LIBDEVICE_PATH", + ] + extra_env = {v: os.environ.get(v) for v in env_vars} + extra_config = { + "use_static_triton_launcher": torch._inductor.config.use_static_triton_launcher + } + + if len(torch._inductor.config.autotune_lookup_table) > 0: + m = size_hints_regex.search(source_code) + if m: + size_hints_str = m.group(1) + else: + size_hints_str = str(None) + + triton_src = source_code.split("@triton.jit\n")[1] + from torch._inductor.runtime.triton_heuristics import ( + generate_lookup_hash_from_source_code, + ) + + fn_hash = generate_lookup_hash_from_source_code( + size_hints_str, triton_src + ) + + if fn_hash in torch._inductor.config.autotune_lookup_table: + extra_config["autotune_lookup_table"] = { # type: ignore[assignment] + fn_hash: torch._inductor.config.autotune_lookup_table[fn_hash] + } + + task = self.process_pool().submit( + _worker_compile_triton, + load_kernel, + extra_env, + extra_config, + ) + + def get_result() -> CachingAutotuner: + try: + kernel, elapsed_us = task.result() + except SubprocException as e: + raise e.with_name(kernel_name) from e + + # Now that we've compiled, we should clear the future + # so it can't be used again + kernel.set_compile_info(compile_id, is_backward) + CompiledTritonKernels.remove_future(source_code) + + kernel.restore_after_unpickle(old_values=None) + + kernel.precompile( + warm_cache_only=False, + reload_kernel=reload_kernel_in_parent, + static_triton_bundle_key=CompiledTritonKernels.key(source_code), + ) + _emit_triton_kernel_compile_metric(kernel, kernel_name, elapsed_us) + return kernel + + future = LambdaFuture(get_result, future=task) + CompiledTritonKernels.save(source_code, future) + return future + else: + with dynamo_timed( + "async_compile.precompile", + log_pt2_compile_event=True, + dynamo_compile_column_us="triton_compile_time_us", + log_waitcounter=True, + waitcounter_name_override="compile_triton", + ): + fail = None + try: + start_ns = time_ns() + _set_triton_ptxas_path() + _set_triton_libdevice_path() + kernel = load_kernel() + kernel.set_compile_info(compile_id, is_backward) + kernel.precompile( + warm_cache_only=False, + static_triton_bundle_key=CompiledTritonKernels.key(source_code), + ) + elapsed_us = (time_ns() - start_ns) // 1000 + _emit_triton_kernel_compile_metric(kernel, kernel_name, elapsed_us) + return kernel + except Exception as e: + fail = str(e) + raise + finally: + log_triton_builds(fail=fail) + + def multi_kernel(self, *args, **kwargs) -> Any: + from torch._inductor.codegen.multi_kernel import MultiKernelCall + + # no need to call this in parallel since the sub-kernels are already parallel tasks + return MultiKernelCall(*args, **kwargs) + + def size_hint_multi_kernel(self, *args, **kwargs) -> Any: + from torch._inductor.codegen.multi_kernel import SizeHintMultiKernelCall + + return SizeHintMultiKernelCall(*args, **kwargs) + + def cpp(self, source_code: str): + kernel_code_log.info("CPP Kernel:\n%s", source_code) + if get_compile_threads() <= 1: + return CppCodeCache.load(source_code).kernel + else: + get_result = CppCodeCache.load_async(source_code, submit_fn=self.submit) + return LambdaFuture(lambda: get_result().kernel) + + def cpp_pybinding(self, argtypes: list[str], source_code: str): + kernel_code_log.info("CPP+Bindings Kernel:\n%s", source_code) + if get_compile_threads() <= 1: + return CppPythonBindingsCodeCache.load_pybinding(argtypes, source_code) + else: + get_result = CppPythonBindingsCodeCache.load_pybinding_async( + argtypes, source_code, submit_fn=self.submit + ) + return LambdaFuture(get_result) + + def cutlass(self, cache_cls, source_code, dst_file_ext, aot_compile=False): + def task(): + if aot_compile: + # We rely on JITInductor to compile the CUDA code, + # so that we can load it into AOTInductor. + output_path, *_ = cache_cls.compile(source_code, "o") + cache_cls.aot_kernels_o.append(output_path) + return cache_cls.load(source_code, dst_file_ext)[0] + + return self.submit(task) + + def cuda(self, source_code, dst_file_ext, aot_compile=False): + kernel_code_log.info("CUDA Kernel:\n%s", source_code) + return self.cutlass(CUDACodeCache, source_code, dst_file_ext, aot_compile) + + def xpu(self, source_code, dst_file_ext, aot_compile=False): + kernel_code_log.info("XPU Kernel:\n%s", source_code) + return self.cutlass(XPUCodeCache, source_code, dst_file_ext, aot_compile) + + def rocm( + self, + source_code, + dst_file_ext, + aot_compile=False, + ): + kernel_code_log.info("ROCm Kernel:\n%s", source_code) + + def task(): + if aot_compile: + output_path, *_ = ROCmCodeCache.compile(source_code, dst_file_ext="o") + ROCmCodeCache.aot_kernels_o.append(output_path) + if config.rocm.generate_test_runner: + _ = ROCmCodeCache.compile(source_code, dst_file_ext="exe") + return ROCmCodeCache.load(source_code, dst_file_ext)[0] + + return self.submit(task) + + def halide(self, meta: HalideMeta, source_code: str): + kernel_code_log.info("Halide Kernel:\n%r\n%s", meta, source_code) + if get_compile_threads() <= 1: + return HalideCodeCache.generate_halide(meta, source_code) + else: + get_result = HalideCodeCache.generate_halide_async( + meta, source_code, submit_fn=self.submit + ) + return LambdaFuture(get_result) + + def _load_kernel_wrapper(self, kernel_name, main_suffix, wrapper_cls, key, path): + """Reload a kernel module from PyCodeCache and wrap the entry point.""" + mod = torch._inductor.codecache.PyCodeCache.load_by_key_path(key, path) + main_func_name = f"{kernel_name}_{main_suffix}" + return wrapper_cls(getattr(mod, main_func_name), kernel_path=path) + + def cutedsl(self, kernel_name: str, source_code: str, precompile_metadata=None): + """ + Compile CuteDSL (CUTLASS Python DSL) kernels. + + Args: + kernel_name: Name of the kernel to be defined + source_code: Source code of the CuteDSL kernel, as a string + precompile_metadata: Optional dict with shapes/dtypes for triggering + real CuTe DSL compilation in the subprocess worker. + + Note: + CuteDSL currently requires source files to do its compilation, there we + use the PyCodeCache to write the source code to a file and load it. + """ + from torch._inductor.codegen.cutedsl.cutedsl_kernel import ( + CuteDSLKernelWrapper, + MAIN_SUFFIX, + ) + + kernel_code_log.info("CuteDSL Kernel:\n%s", source_code) + _compile_start() + + is_parallel = self.use_process_pool() + + if is_parallel: + extra_env = _pycodecache_kernel_compile_env() + + subprocess_task = self.process_pool().submit( + _worker_compile_pycodecache_kernel, + kernel_name, + source_code, + MAIN_SUFFIX, + extra_env, + precompile_metadata, + ) + + def get_result() -> CuteDSLKernelWrapper: + try: + key, path, elapsed_us = subprocess_task.result() + except SubprocException as e: + raise e.with_name(kernel_name) from e + log.debug( + "CuteDSL kernel %s compiled in subprocess in %dus", + kernel_name, + elapsed_us, + ) + return self._load_kernel_wrapper( + kernel_name, MAIN_SUFFIX, CuteDSLKernelWrapper, key, path + ) + + return LambdaFuture(get_result, future=subprocess_task) + else: + key, path = torch._inductor.codecache.PyCodeCache.write(source_code) + mod = torch._inductor.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 CuteDSL main kernel function '{main_func_name}'. Available callables: {available}" + ) + + return CuteDSLKernelWrapper(getattr(mod, main_func_name), kernel_path=path) + + def pallas(self, kernel_name: str, source_code: str): + """ + Compile Pallas (JAX experimental) kernels. + + Args: + kernel_name: Name of the kernel to be defined + source_code: Source code of the Pallas kernel, as a string + + Note: + Pallas kernels are Python code that uses JAX and Pallas APIs. + We use the PyCodeCache to write the source code to a file and load it. + """ + from torch._inductor.codegen.pallas import MAIN_SUFFIX, PallasKernelWrapper + + kernel_code_log.info("Pallas Kernel:\n%s", source_code) + + def task(): + key, path = torch._inductor.codecache.PyCodeCache.write(source_code) + mod = torch._inductor.codecache.PyCodeCache.load_by_key_path(key, path) + + # Find our special entry point named function + 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 Pallas main kernel function '{main_func_name}'. Available callables: {available}" + ) + + return PallasKernelWrapper(getattr(mod, main_func_name), kernel_path=path) + + if get_compile_threads() <= 1: + return task() + else: + future = self.submit(task) + return LambdaFuture(lambda: future.result()) + + def nv_universal_gemm( + self, kernel_name: str, source_code: str, precompile_metadata=None + ): + """ + Compile NVIDIA Universal GEMM kernels. + + Args: + kernel_name: Name of the kernel to be defined + source_code: Source code of the kernel, as a string + precompile_metadata: Optional dict with shapes/dtypes for triggering + real CuTe DSL compilation in the subprocess worker. + + Note: + NVIDIA Universal GEMM kernels are Python code that calls the cutlass.operators library. + We use the PyCodeCache to write the source code to a file and load it. + """ + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import ( + NVUniversalGemmKernelWrapper, + ) + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_scheduling import ( + MAIN_SUFFIX, + ) + + kernel_code_log.info("NVIDIA Universal GEMM Kernel:\n%s", source_code) + _compile_start() + + is_parallel = self.use_process_pool() + + if is_parallel: + extra_env = _pycodecache_kernel_compile_env() + + subprocess_task = self.process_pool().submit( + _worker_compile_pycodecache_kernel, + kernel_name, + source_code, + MAIN_SUFFIX, + extra_env, + precompile_metadata, + ) + + def get_result() -> NVUniversalGemmKernelWrapper: + try: + key, path, elapsed_us = subprocess_task.result() + except SubprocException as e: + raise e.with_name(kernel_name) from e + log.debug( + "NV Universal GEMM kernel %s compiled in subprocess in %dus", + kernel_name, + elapsed_us, + ) + return self._load_kernel_wrapper( + kernel_name, MAIN_SUFFIX, NVUniversalGemmKernelWrapper, key, path + ) + + return LambdaFuture(get_result, future=subprocess_task) + else: + key, path = torch._inductor.codecache.PyCodeCache.write(source_code) + mod = torch._inductor.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 NVIDIA Universal GEMM main kernel function " + f"'{main_func_name}'. Available callables: {available}" + ) + + return NVUniversalGemmKernelWrapper( + getattr(mod, main_func_name), kernel_path=path + ) + + def nvgemm_precompile( + self, + kernel_name, + variant_name, + accumulator_type, + input_tensor_meta, + output_tensor_meta, + cuda_ctx, + scale_type_a=None, + scale_type_b=None, + swizzle_type_a=None, + swizzle_type_b=None, + has_bias_epilogue=False, + swap_ab=False, + metadata=None, + ): + """Submit NVGEMM kernel precompilation to the subprocess pool. + + Compiles the CuTeDSL kernel artifact in a subprocess worker so the + thread-unsafe kernel.compile() call is process-isolated. The compiled + artifact is saved to the disk cache; the main process loads it on the + next cache lookup during benchmarking. + """ + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import ( + _worker_nvgemm_autotuning_precompile, + ) + + extra_env = _pycodecache_kernel_compile_env() + + return self.process_pool().submit( + _worker_nvgemm_autotuning_precompile, + kernel_name, + variant_name, + accumulator_type, + input_tensor_meta, + output_tensor_meta, + extra_env, + cuda_ctx, + scale_type_a, + scale_type_b, + swizzle_type_a, + swizzle_type_b, + has_bias_epilogue, + swap_ab, + metadata, + ) + + def metal(self, kernel_name: str, source: str, headers: list[str]) -> None: + """Register a Metal kernel body; wait() compiles all registered kernels into one library.""" + if self._metal_sources is None: + self._metal_sources = [] + self._metal_sources.append((kernel_name, source, headers)) + + def wait(self, scope: dict[str, Any]) -> None: + if get_compile_threads() > 1: + with dynamo_timed( + "async_compile.wait", + log_pt2_compile_event=True, + dynamo_compile_column_us="triton_compile_time_us", + log_waitcounter=True, + waitcounter_name_override="compile_triton", + ): + self._wait_futures(scope) + + if self._metal_sources: + from torch._inductor.runtime.runtime_utils import compile_mps_shaders + + scope.update(compile_mps_shaders(self._metal_sources)) + self._metal_sources.clear() + + _compile_end() + + def _wait_futures(self, scope: dict[str, Any]) -> None: + kernels = { + key: value + for key, value in scope.items() + if isinstance(value, (Future, CodeCacheFuture)) + } + pbar = tqdm( + total=len(kernels), + desc="Inductor Compilation", + disable=config.disable_progress, + delay=0, + ) + # compile_worker_wait_timeout=0 (default) means "wait forever"; map + # it to None so both Future.result() and CodeCacheFuture.result() + # receive the same "no timeout" sentinel. + wait_timeout = config.compile_worker_wait_timeout or None + for key, result in kernels.items(): + if config.verbose_progress and not isinstance(pbar, _Faketqdm): + pbar.set_postfix_str(key) + try: + kernel = result.result(timeout=wait_timeout) + scope[key] = kernel + except FuturesTimeoutError as e: + # concurrent.futures.TimeoutError became an alias of the + # builtin TimeoutError in Python 3.11; on 3.10 it is a + # distinct class, so catch it explicitly. + raise RuntimeError( + f"Inductor compile-worker future for {key!r} did not " + f"complete within {wait_timeout}s. Override with " + "TORCHINDUCTOR_COMPILE_WORKER_WAIT_TIMEOUT=." + ) from e + except BrokenProcessPool as e: + raise RuntimeError( + "A compilation subprocess exited unexpectedly. This " + "is likely due to a crash. To facilitate debugging, " + "you can re-run with TORCHINDUCTOR_COMPILE_THREADS=1 " + "to cause compilation to occur in the main process." + ) from e + pbar.update(1) + + +def maybe_warm_pool() -> None: + if ( + os.environ.get("TORCH_TNT_IN_USE", "0") == "1" + or os.environ.get("TORCH_WARM_POOL", "1") != "1" + # The subprocess pool is only used for the Triton backend + or not has_triton_package() + # Skip for fbcode. We have internal reports of usages inside multiprocessing + # pools that lead a multiplicative number of compile subprocesses. + or config.is_fbcode() + ): + return + + AsyncCompile.warm_pool() + # TODO: This starts the SubprocPool's internal process pool as early as possible at + # the expense of creating a bunch of worker processes that might not be needed. We + # could start them lazily if we're willing to lose a small amount of compile time. + AsyncCompile.wakeup() + + +# On exit give the workers a chance to clean themselves up. Without this the +# resource_tracker can complain about leaked semaphores coming from the +# ProcessPoolExecutor: +# UserWarning: resource_tracker: There appear to be 5 leaked semaphore objects +# to clean up at shutdown +atexit.register(shutdown_compile_workers) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/augmented_graph_helper.py b/.venv/lib/python3.12/site-packages/torch/_inductor/augmented_graph_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..63a19ede7786d16228864eeba0ca7a8b4f0badf4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/augmented_graph_helper.py @@ -0,0 +1,281 @@ +import logging +from collections import defaultdict + +import torch +import torch.fx as fx +from torch._inductor.fx_passes.utils import BitsetAncestors +from torch._logging import trace_structured +from torch.utils._ordered_set import OrderedSet + + +log = logging.getLogger(__name__) + + +class AugmentedGraphHelper: + """ + Graph helper that augments the original graph with additional + dependencies and uses, plus tracks node equivalences for coalescing. + + TODO: if this becomes too large of compile time, consider binding + graphcycles.cc + """ + + def __init__( + self, + graph: fx.Graph, + node_ancestors: BitsetAncestors | None = None, + ): + # Each node starts in its own singleton set + self.graph = graph + self.merge_sets = {node: OrderedSet([node]) for node in graph.nodes} + + # Extra dependencies: node depends on dep (dep must come before node) + self.extra_deps: dict[fx.Node, OrderedSet[fx.Node]] = defaultdict(OrderedSet) + # Extra uses: reverse of extra_deps (node is used by user) + self.extra_uses: dict[fx.Node, OrderedSet[fx.Node]] = defaultdict(OrderedSet) + # Note: only reflect original ancestors, not maintained through additional deps + # or merge sets + self.node_ancestors = node_ancestors + + def add_extra_dep(self, *, n: fx.Node, dep: fx.Node) -> None: + """Add extra dependency: node depends on dep.""" + self.extra_deps[n].add(dep) + self.extra_uses[dep].add(n) + + def remove_extra_dep(self, *, n: fx.Node, dep: fx.Node) -> None: + if dep in self.extra_deps[n]: + self.extra_deps[n].discard(dep) + self.extra_uses[dep].discard(n) + + def merge_to_set(self, existing_node: fx.Node, new_node: fx.Node) -> None: + """ + Merge new_node into existing_node's set. The new node must be a singleton set. + """ + existing_set = self.merge_sets[existing_node] + new_set = self.merge_sets[new_node] + if len(new_set) != 1: + raise AssertionError( + f"new_node must be a singleton set, got size {len(new_set)}" + ) + + # Add all nodes from new_set to existing_set + existing_set.update(new_set) + + # Update all nodes from new_set to point to existing_set + for node in new_set: + self.merge_sets[node] = existing_set + + def unmerge_node(self, node: fx.Node) -> None: + """Remove a node from its merge set, making it singleton.""" + old_set = self.merge_sets[node] + + # If already singleton, nothing to do + if len(old_set) == 1: + return + + # Remove from old set + old_set.remove(node) + + # Make node singleton + self.merge_sets[node] = OrderedSet([node]) + + def get_merged_deps(self, node: fx.Node) -> OrderedSet[fx.Node]: + """ + Get all dependencies of a node considering merges and extra deps. + Combines: + 1. Direct deps (all_input_nodes) of node and its merge equivalents + 2. Extra deps of node and its merge equivalents + """ + deps: OrderedSet[fx.Node] = OrderedSet() + + # For each node in the merge set + for merged_node in self.merge_sets[node]: + # Add direct dependencies from all_input_nodes + deps.update(merged_node.all_input_nodes) + # Add extra dependencies + deps.update(self.extra_deps[merged_node]) + + return deps + + def has_cycle(self) -> bool: + return torch._dynamo.graph_deduplication._has_cycle( + self.graph, self.get_all_extra_deps() + ) + + def _get_all_ancestors(self, node: fx.Node) -> OrderedSet[fx.Node]: + """Transitive ancestors through both data deps and extra deps.""" + ancestors: OrderedSet[fx.Node] = OrderedSet() + stack: list[fx.Node] = list(node.all_input_nodes) + stack.extend(self.extra_deps.get(node, ())) + while stack: + n = stack.pop() + if n not in ancestors: + ancestors.add(n) + stack.extend(n.all_input_nodes) + stack.extend(self.extra_deps.get(n, ())) + return ancestors + + def has_path(self, source: fx.Node, target: fx.Node) -> bool: + """Check if there's a path from source to target.""" + # we should not be checking path from node to itself + if self.merge_sets[source] is self.merge_sets[target]: + raise AssertionError("source and target must not be in the same merge set") + + # search backwards from target to source + visited: OrderedSet[fx.Node] = OrderedSet() + queue = [target] + visited.add(target) + + while queue: + current = queue.pop() + + for dep in self.get_merged_deps(current): + # Check if we reached source or its equivalent + if dep in self.merge_sets[source]: + return True + + if dep in visited: + continue + + # We are searching from target, so this node is necessarily an ancestor + # of target. + # If dep is an ancestor of source, any path through dep to source would imply a cycle + if self.node_ancestors: + source_set = self.merge_sets[source] + is_ancestor_of_source = any( + self.node_ancestors.is_ancestor(dep, s) for s in source_set + ) + # Add to visited to avoid recomputing this check if we see dep again + if is_ancestor_of_source: + visited.add(dep) + continue + + visited.add(dep) + queue.append(dep) + + return False + + def transfer_erased_node_deps( + self, erased_to_new: dict[fx.Node, fx.Node | None] + ) -> None: + """ + Transfer all extra dependencies from erased nodes to their replacements, handling + cross-dependencies between erased nodes correctly. + + Skips deps where both endpoints resolve to replacement nodes from the + same erasure batch — these are intra-bucket deps that would create + cycles (e.g. new_start <-> new_wait within the same bucket). + """ + erased_merge_sets: dict[fx.Node, fx.Node | None] = {} + + for replaced, new in erased_to_new.items(): + for equiv in self.merge_sets[replaced]: + erased_merge_sets[equiv] = new + + # Transfer dependencies + for old_node, new_node in erased_merge_sets.items(): + if new_node is None: + # Clean up references to removed node + for extra_use in list(self.extra_uses[old_node]): + updated_use = erased_merge_sets.get(extra_use, extra_use) + if updated_use is not None: + self.extra_deps[updated_use].discard(old_node) + for extra_dep in list(self.extra_deps[old_node]): + updated_dep = erased_merge_sets.get(extra_dep, extra_dep) + if updated_dep is not None: + self.extra_uses[updated_dep].discard(old_node) + else: + # Transfer dependencies FROM old_node (what old_node depended on) + for extra_dep in self.extra_deps[old_node]: + updated_dep = erased_merge_sets.get(extra_dep, extra_dep) + if updated_dep is not None and updated_dep != new_node: + # Skip if reverse dep already exists (extra or data) + if new_node in self.extra_deps.get( + updated_dep, () + ) or new_node in OrderedSet(updated_dep.all_input_nodes): + continue + self.extra_deps[new_node].add(updated_dep) + self.extra_uses[updated_dep].discard(old_node) + self.extra_uses[updated_dep].add(new_node) + + # Transfer dependencies TO old_node (what depended on old_node) + for extra_use in self.extra_uses[old_node]: + updated_use = erased_merge_sets.get(extra_use, extra_use) + if updated_use is not None and updated_use != new_node: + # Skip if reverse dep already exists (extra or data) + if updated_use in self.extra_deps.get( + new_node, () + ) or updated_use in OrderedSet(new_node.all_input_nodes): + continue + self.extra_deps[updated_use].discard(old_node) + self.extra_deps[updated_use].add(new_node) + self.extra_uses[new_node].add(updated_use) + + # Clean up erased nodes + for old_node in erased_merge_sets: + self.extra_deps[old_node].clear() + self.extra_uses[old_node].clear() + del self.merge_sets[old_node] + + def remove_erased_extra_deps(self) -> None: + """Remove extra deps referencing erased nodes.""" + for node in list(self.extra_deps): + if node._erased: + for dep in list(self.extra_deps[node]): + self.remove_extra_dep(n=node, dep=dep) + continue + for dep in list(self.extra_deps[node]): + if dep._erased: + self.remove_extra_dep(n=node, dep=dep) + + def check_and_maybe_autofix_cyclic_extra_deps( + self, *, autofix: bool = False + ) -> None: + """Check for and optionally remove extra deps that create cycles. + + Args: + autofix: If True, silently remove cyclic deps. If False (default), + raise an error so the root cause gets investigated. + """ + if not self.has_cycle(): + return + removed = [] + for node in list(self.extra_deps): + for dep in list(self.extra_deps[node]): + ancestors = self._get_all_ancestors(dep) + if node in ancestors: + removed.append((node.name, dep.name)) + self.remove_extra_dep(n=node, dep=dep) + if not removed: + return + msg = ( + f"Overlap scheduling: detected {len(removed)} cyclic extra " + f"dep(s): {removed}. Please report this to the overlap " + f"scheduling developers." + ) + log.warning(msg) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_overlap_cyclic_extra_deps", + "encoding": "string", + }, + payload_fn=lambda: msg, + ) + if not autofix: + raise RuntimeError( + f"{msg}\nTo unblock, set " + f"torch._inductor.config.aten_distributed_optimizations" + f".overlap_scheduling_autofix_cycles = True" + ) + + def get_all_extra_deps(self) -> dict[fx.Node, OrderedSet[fx.Node]]: + """ + Get all extra dependencies in a format suitable for topological sort. + Returns a copy to avoid external modifications. + """ + return { + node: OrderedSet(deps) + for node, deps in self.extra_deps.items() + if deps # Only include nodes with non-empty deps + } diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be6e909f56827a5dda201f035d6b7b591288aaa1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9879e3beeb625b50a28e1a08e075919cad966b93 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee0728ce8d22e7463c9ba64316dcb1d70bb668c3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/autoheuristic_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learned_heuristic_controller.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learned_heuristic_controller.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..966461ea1e8083482339bd03a34bb4c82326ef13 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learned_heuristic_controller.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learnedheuristic_interface.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learnedheuristic_interface.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bc903c4465a14d06ff20398331c3305fe274807 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/__pycache__/learnedheuristic_interface.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py new file mode 100644 index 0000000000000000000000000000000000000000..c87561d6eb3e40874dc10a2928c22b6aa8636345 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py @@ -0,0 +1,296 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mm/ +from typing import List, Optional, Tuple + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class MMRankingA100(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 166912 + and str(metadata.device_capa) == "(8, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.0 + + def get_choice(self, idx: int) -> str | None: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('extern_mm') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4') + + def get_name(self) -> str: + return 'mm' + + def get_best_choices(self, context: AHContext) -> list[tuple[float, int]] | None: + if context.get_value('arith_intensity') <= 52.6245059967041: + if context.get_value('n') <= 34.0: + if context.get_value('n') <= 18.0: + if context.get_value('k*n') <= 312.0: + return [(0.093, 12), (0.081, 16), (0.081, 148), (0.070, 10), (0.070, 17), (0.070, 149), (0.070, 151), (0.070, 150), (0.070, 14), (0.058, 11), (0.058, 15), (0.058, 13), (0.058, 122), (0.047, 121), (0.035, 123), (0.012, 92)] + else: + if context.get_value('k') <= 40.0: + return [(0.083, 42), (0.083, 46), (0.083, 44), (0.083, 40), (0.083, 128), (0.067, 45), (0.067, 43), (0.067, 41), (0.067, 169), (0.067, 171), (0.067, 168), (0.067, 129), (0.067, 170), (0.033, 103), (0.017, 121)] + else: + return [(0.112, 137), (0.104, 136), (0.101, 0), (0.081, 1), (0.073, 135), (0.069, 67), (0.066, 187), (0.058, 41), (0.050, 71), (0.046, 68), (0.046, 70), (0.031, 44), (0.027, 43), (0.027, 170), (0.019, 189), (0.019, 188), (0.015, 169), (0.015, 171), (0.012, 115), (0.012, 168), (0.012, 69), (0.004, 103)] + else: + if context.get_value('mat1_stride_0') <= 20.0: + return [(0.069, 0), (0.059, 157), (0.059, 22), (0.059, 153), (0.059, 155), (0.059, 25), (0.059, 23), (0.059, 19), (0.044, 21), (0.044, 18), (0.044, 152), (0.044, 158), (0.044, 154), (0.044, 156), (0.044, 20), (0.044, 124), (0.044, 24), (0.030, 125), (0.029, 126), (0.015, 97), (0.015, 95), (0.015, 96), (0.010, 2), (0.010, 75)] + else: + if context.get_value('k') <= 68.0: + return [(0.087, 72), (0.087, 74), (0.087, 73), (0.086, 76), (0.077, 75), (0.067, 192), (0.058, 190), (0.048, 47), (0.048, 193), (0.048, 49), (0.048, 51), (0.048, 191), (0.038, 53), (0.019, 133), (0.019, 50), (0.019, 175), (0.019, 172), (0.019, 48), (0.019, 174), (0.010, 173), (0.010, 177), (0.010, 52), (0.010, 54), (0.010, 178), (0.010, 176)] + else: + return [(0.154, 52), (0.154, 72), (0.102, 75), (0.087, 49), (0.087, 73), (0.086, 51), (0.057, 176), (0.045, 2), (0.038, 191), (0.038, 178), (0.038, 190), (0.029, 173), (0.029, 76), (0.026, 138), (0.013, 139), (0.013, 140), (0.003, 0)] + else: + if context.get_value('k') <= 35.0: + if context.get_value('k') <= 18.0: + if context.get_value('m*n') <= 19505152.0: + return [(0.151, 159), (0.140, 160), (0.129, 164), (0.055, 127), (0.051, 29), (0.044, 161), (0.044, 147), (0.040, 146), (0.040, 31), (0.037, 145), (0.026, 28), (0.022, 90), (0.022, 93), (0.022, 94), (0.022, 100), (0.022, 125), (0.022, 158), (0.022, 157), (0.011, 87), (0.011, 88), (0.011, 89), (0.011, 91), (0.011, 95), (0.011, 96), (0.011, 98), (0.011, 99)] + else: + return [(0.069, 7), (0.069, 5), (0.067, 147), (0.066, 8), (0.061, 145), (0.058, 146), (0.052, 124), (0.049, 29), (0.049, 159), (0.046, 31), (0.043, 157), (0.041, 9), (0.041, 4), (0.040, 6), (0.035, 164), (0.035, 160), (0.026, 158), (0.017, 125), (0.017, 28), (0.017, 32), (0.017, 162), (0.017, 27), (0.017, 30), (0.017, 161), (0.009, 33), (0.009, 26), (0.009, 163), (0.006, 0)] + else: + if context.get_value('n') <= 68.0: + return [(0.101, 182), (0.101, 59), (0.088, 57), (0.076, 184), (0.076, 61), (0.076, 179), (0.076, 62), (0.076, 58), (0.063, 180), (0.063, 60), (0.051, 56), (0.050, 181), (0.025, 130), (0.025, 177), (0.025, 183), (0.013, 178), (0.013, 55)] + else: + return [(0.089, 180), (0.079, 60), (0.066, 35), (0.066, 181), (0.066, 38), (0.066, 58), (0.066, 179), (0.066, 57), (0.062, 184), (0.053, 37), (0.044, 166), (0.040, 55), (0.040, 39), (0.040, 36), (0.040, 165), (0.040, 167), (0.027, 177), (0.027, 34), (0.022, 159)] + else: + if context.get_value('m*n') <= 309760.0: + return [(0.298, 0), (0.097, 140), (0.080, 83), (0.072, 86), (0.044, 84), (0.036, 178), (0.036, 117), (0.036, 82), (0.032, 120), (0.032, 85), (0.028, 119), (0.024, 130), (0.024, 109), (0.020, 108), (0.020, 118), (0.012, 104), (0.012, 116), (0.012, 141), (0.012, 144), (0.008, 105), (0.008, 106), (0.008, 111), (0.008, 114), (0.008, 107), (0.008, 132), (0.004, 101), (0.004, 102), (0.004, 110), (0.004, 112), (0.004, 113), (0.004, 131)] + else: + if context.get_value('n') <= 72.0: + return [(0.227, 77), (0.118, 78), (0.102, 194), (0.086, 80), (0.059, 57), (0.054, 81), (0.049, 196), (0.048, 197), (0.048, 59), (0.043, 79), (0.032, 195), (0.027, 180), (0.022, 3), (0.021, 141), (0.016, 60), (0.016, 142), (0.011, 183), (0.011, 0), (0.011, 144)] + else: + return [(0.140, 186), (0.132, 185), (0.109, 63), (0.085, 65), (0.078, 37), (0.077, 35), (0.062, 197), (0.047, 194), (0.046, 165), (0.046, 57), (0.039, 78), (0.039, 79), (0.039, 66), (0.039, 64), (0.016, 195), (0.008, 159)] + else: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('m*n') <= 815360.0: + if context.get_value('k') <= 1184.0: + return [(0.218, 140), (0.205, 0), (0.154, 144), (0.115, 141), (0.051, 185), (0.051, 104), (0.039, 78), (0.038, 116), (0.026, 165), (0.026, 130), (0.026, 178), (0.013, 57), (0.013, 195), (0.013, 167), (0.013, 186)] + else: + return [(0.901, 0), (0.030, 144), (0.030, 134), (0.016, 3), (0.006, 78), (0.006, 77), (0.002, 57), (0.002, 194), (0.002, 59), (0.002, 60), (0.002, 143)] + else: + if context.get_value('arith_intensity') <= 187.23922729492188: + if context.get_value('mat1_stride_0') <= 198.0: + return [(0.273, 63), (0.158, 37), (0.152, 35), (0.127, 57), (0.097, 165), (0.053, 185), (0.031, 0), (0.028, 64), (0.014, 60), (0.014, 78), (0.009, 55), (0.008, 134), (0.005, 34), (0.005, 167), (0.005, 179), (0.005, 65), (0.005, 66), (0.005, 186), (0.005, 194), (0.002, 166)] + else: + return [(0.296, 63), (0.235, 0), (0.132, 64), (0.074, 37), (0.069, 78), (0.051, 185), (0.051, 35), (0.030, 57), (0.020, 77), (0.016, 194), (0.008, 66), (0.007, 65), (0.003, 3), (0.003, 165), (0.003, 141), (0.001, 134), (0.001, 166)] + else: + return [(0.405, 0), (0.246, 37), (0.177, 63), (0.145, 35), (0.005, 185), (0.005, 65), (0.005, 64), (0.004, 57), (0.003, 66), (0.002, 165), (0.001, 78), (0.001, 55)] + else: + return [(0.357, 0), (0.112, 165), (0.101, 57), (0.094, 179), (0.086, 64), (0.074, 167), (0.067, 60), (0.064, 159), (0.033, 35), (0.007, 195), (0.002, 180), (0.001, 34), (0.001, 166), (0.001, 78)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingH100.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingH100.py new file mode 100644 index 0000000000000000000000000000000000000000..74812d9f0b404bbb5d7040d298e2bd597f9bba8e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingH100.py @@ -0,0 +1,321 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mm/ +from typing import List, Optional, Tuple + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class MMRankingH100(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 232448 + and str(metadata.device_capa) == "(9, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.0 + + def get_choice(self, idx: int) -> str | None: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('extern_mm') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=2_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=1') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=16_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4') + + def get_name(self) -> str: + return 'mm' + + def get_best_choices(self, context: AHContext) -> list[tuple[float, int]] | None: + if context.get_value('arith_intensity') <= 29.89772129058838: + if context.get_value('n') <= 34.0: + if context.get_value('n') <= 18.0: + if context.get_value('k*n') <= 432.0: + if context.get_value('arith_intensity') <= 7.8700292110443115: + return [(0.098, 128), (0.098, 129), (0.098, 127), (0.073, 14), (0.073, 16), (0.073, 12), (0.073, 154), (0.073, 156), (0.073, 157), (0.073, 155), (0.049, 10), (0.049, 94), (0.049, 95), (0.048, 96)] + else: + return [(0.091, 154), (0.073, 10), (0.073, 15), (0.073, 13), (0.073, 11), (0.073, 17), (0.073, 16), (0.073, 14), (0.073, 12), (0.055, 127), (0.054, 157), (0.054, 156), (0.054, 155), (0.036, 129), (0.036, 128), (0.018, 41), (0.018, 43)] + else: + if context.get_value('k') <= 40.0: + return [(0.070, 39), (0.069, 45), (0.069, 41), (0.069, 43), (0.069, 111), (0.069, 112), (0.056, 38), (0.056, 40), (0.056, 42), (0.056, 44), (0.056, 174), (0.056, 173), (0.056, 175), (0.056, 134), (0.056, 172), (0.056, 135), (0.014, 154), (0.014, 127)] + else: + return [(0.147, 144), (0.119, 143), (0.087, 142), (0.083, 0), (0.073, 191), (0.059, 69), (0.050, 67), (0.046, 70), (0.041, 1), (0.036, 174), (0.032, 43), (0.032, 123), (0.028, 40), (0.027, 42), (0.027, 173), (0.023, 175), (0.018, 66), (0.014, 192), (0.014, 193), (0.014, 139), (0.014, 68), (0.014, 127)] + else: + if context.get_value('mat1_stride_0') <= 40.0: + if context.get_value('mat1_stride_0') <= 20.0: + return [(0.109, 23), (0.109, 21), (0.109, 20), (0.088, 0), (0.087, 131), (0.066, 18), (0.065, 130), (0.065, 132), (0.065, 159), (0.065, 160), (0.065, 161), (0.065, 158), (0.022, 22), (0.022, 19)] + else: + return [(0.065, 46), (0.064, 52), (0.064, 50), (0.064, 48), (0.064, 51), (0.064, 49), (0.064, 47), (0.064, 53), (0.064, 181), (0.064, 177), (0.064, 179), (0.064, 176), (0.038, 130), (0.038, 136), (0.026, 182), (0.026, 178), (0.026, 180), (0.026, 137), (0.025, 158), (0.013, 114), (0.013, 113)] + else: + if context.get_value('mat1_stride_0') <= 68.0: + return [(0.138, 140), (0.125, 195), (0.100, 71), (0.100, 74), (0.100, 196), (0.100, 194), (0.100, 197), (0.075, 75), (0.062, 72), (0.062, 73), (0.012, 180), (0.012, 51), (0.012, 182)] + else: + return [(0.124, 180), (0.124, 182), (0.114, 75), (0.103, 74), (0.093, 51), (0.093, 71), (0.072, 72), (0.062, 194), (0.052, 145), (0.052, 195), (0.021, 48), (0.021, 50), (0.021, 47), (0.020, 124), (0.010, 147), (0.010, 146), (0.010, 46)] + else: + if context.get_value('k') <= 18.0: + if context.get_value('m*k') <= 528.0: + return [(0.097, 88), (0.087, 92), (0.077, 90), (0.058, 105), (0.058, 103), (0.058, 104), (0.058, 99), (0.058, 100), (0.058, 106), (0.058, 93), (0.057, 91), (0.057, 97), (0.057, 98), (0.057, 101), (0.048, 102), (0.029, 87), (0.029, 89)] + else: + if context.get_value('n') <= 80.0: + return [(0.057, 161), (0.057, 130), (0.057, 24), (0.056, 164), (0.056, 163), (0.056, 166), (0.056, 168), (0.056, 30), (0.056, 28), (0.056, 26), (0.056, 25), (0.056, 27), (0.056, 29), (0.056, 31), (0.042, 131), (0.028, 99), (0.028, 101), (0.028, 100), (0.028, 167), (0.028, 165), (0.028, 133)] + else: + return [(0.110, 164), (0.108, 163), (0.106, 168), (0.069, 161), (0.066, 151), (0.060, 152), (0.055, 165), (0.050, 27), (0.050, 29), (0.048, 131), (0.043, 153), (0.037, 133), (0.037, 130), (0.028, 8), (0.028, 5), (0.027, 7), (0.026, 26), (0.016, 162), (0.012, 9), (0.007, 4), (0.005, 100), (0.005, 6), (0.005, 24)] + else: + if context.get_value('k') <= 36.0: + if context.get_value('n') <= 68.0: + return [(0.097, 184), (0.097, 56), (0.086, 186), (0.086, 183), (0.086, 188), (0.086, 58), (0.086, 60), (0.065, 54), (0.043, 187), (0.043, 185), (0.043, 57), (0.043, 61), (0.032, 55), (0.032, 130), (0.032, 59), (0.011, 181), (0.011, 163), (0.011, 136), (0.011, 138)] + else: + return [(0.117, 184), (0.117, 170), (0.117, 169), (0.107, 183), (0.106, 188), (0.075, 181), (0.064, 130), (0.064, 56), (0.053, 171), (0.032, 57), (0.032, 59), (0.032, 185), (0.011, 163), (0.011, 32), (0.011, 37), (0.011, 34), (0.011, 33), (0.011, 35), (0.011, 36), (0.011, 54)] + else: + if context.get_value('mat2_stride_0') <= 384.0: + return [(0.244, 0), (0.061, 76), (0.061, 79), (0.030, 3), (0.030, 183), (0.030, 189), (0.030, 187), (0.030, 64), (0.030, 190), (0.030, 62), (0.030, 198), (0.030, 201), (0.030, 77), (0.030, 200), (0.030, 80), (0.030, 199), (0.030, 78), (0.030, 184), (0.020, 86), (0.020, 84), (0.020, 120), (0.020, 81), (0.020, 121), (0.020, 85), (0.020, 122), (0.010, 83), (0.010, 118), (0.010, 119), (0.010, 82)] + else: + return [(0.274, 83), (0.171, 86), (0.152, 0), (0.071, 85), (0.061, 125), (0.050, 84), (0.020, 109), (0.020, 117), (0.020, 81), (0.020, 118), (0.020, 121), (0.020, 108), (0.020, 115), (0.020, 116), (0.010, 110), (0.010, 120), (0.010, 103), (0.010, 107), (0.010, 119), (0.010, 122)] + else: + if context.get_value('arith_intensity') <= 56.995582580566406: + if context.get_value('n') <= 68.0: + if context.get_value('k*n') <= 4448.0: + if context.get_value('m*n') <= 29626368.0: + return [(0.107, 198), (0.107, 200), (0.107, 201), (0.107, 199), (0.106, 76), (0.106, 79), (0.064, 197), (0.063, 56), (0.043, 184), (0.043, 187), (0.042, 80), (0.042, 77), (0.042, 183), (0.021, 78)] + else: + return [(0.073, 201), (0.073, 198), (0.073, 200), (0.073, 199), (0.073, 197), (0.073, 56), (0.073, 58), (0.073, 79), (0.073, 76), (0.072, 59), (0.072, 78), (0.072, 77), (0.072, 80), (0.018, 184), (0.018, 55), (0.018, 54)] + else: + if context.get_value('k') <= 348.0: + return [(0.206, 76), (0.183, 77), (0.169, 198), (0.160, 199), (0.053, 59), (0.046, 56), (0.038, 3), (0.030, 148), (0.030, 58), (0.030, 187), (0.023, 184), (0.015, 0), (0.008, 55), (0.008, 54)] + else: + return [(0.146, 198), (0.145, 199), (0.145, 148), (0.126, 0), (0.084, 76), (0.084, 77), (0.042, 80), (0.042, 79), (0.021, 149), (0.021, 150), (0.021, 3), (0.014, 46), (0.014, 74), (0.014, 75), (0.014, 124), (0.014, 194), (0.014, 195), (0.007, 145), (0.007, 146), (0.007, 2), (0.007, 72), (0.007, 147), (0.007, 71)] + else: + if context.get_value('m') <= 3264.0: + return [(0.247, 147), (0.115, 197), (0.066, 199), (0.066, 201), (0.066, 198), (0.049, 0), (0.049, 169), (0.049, 171), (0.033, 140), (0.033, 125), (0.033, 114), (0.016, 126), (0.016, 183), (0.016, 184), (0.016, 185), (0.016, 182), (0.016, 188), (0.016, 78), (0.016, 148), (0.016, 138), (0.016, 77), (0.016, 56), (0.016, 59)] + else: + if context.get_value('k') <= 62.5: + return [(0.226, 190), (0.226, 189), (0.122, 62), (0.122, 64), (0.055, 77), (0.055, 78), (0.037, 198), (0.036, 201), (0.036, 33), (0.024, 163), (0.018, 56), (0.018, 35), (0.018, 169), (0.006, 171)] + else: + return [(0.162, 35), (0.118, 33), (0.096, 189), (0.096, 190), (0.088, 169), (0.074, 62), (0.073, 56), (0.066, 171), (0.051, 198), (0.051, 201), (0.044, 59), (0.037, 64), (0.029, 63), (0.007, 0), (0.007, 77)] + else: + if context.get_value('m*n') <= 1097728.0: + return [(0.403, 0), (0.179, 141), (0.134, 150), (0.086, 147), (0.051, 148), (0.048, 3), (0.024, 189), (0.020, 199), (0.017, 64), (0.010, 65), (0.010, 77), (0.007, 114), (0.003, 138), (0.003, 59), (0.003, 182)] + else: + if context.get_value('m*n') <= 3244032.0: + return [(0.295, 189), (0.176, 64), (0.157, 65), (0.090, 0), (0.069, 62), (0.059, 63), (0.046, 77), (0.039, 169), (0.023, 199), (0.020, 35), (0.013, 33), (0.010, 171), (0.003, 141)] + else: + if context.get_value('n') <= 136.0: + return [(0.197, 189), (0.197, 63), (0.161, 77), (0.157, 62), (0.061, 33), (0.044, 65), (0.039, 35), (0.039, 64), (0.030, 169), (0.026, 0), (0.017, 199), (0.017, 148), (0.009, 56), (0.004, 3)] + else: + return [(0.460, 0), (0.145, 62), (0.138, 63), (0.081, 35), (0.047, 33), (0.043, 189), (0.023, 64), (0.018, 77), (0.013, 169), (0.009, 65), (0.009, 56), (0.005, 32), (0.005, 59), (0.002, 183), (0.002, 163)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMA100.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMA100.py new file mode 100644 index 0000000000000000000000000000000000000000..a781767a3ce520a073f9630b834154f156a5fe5f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMA100.py @@ -0,0 +1,150 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mixed_mm/ +from typing import List, Optional, Tuple + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class MixedMMA100(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 166912 + and str(metadata.device_capa) == "(8, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.0 + + def get_choice(self, idx: int) -> str | None: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('extern_fallback_mixed_mm') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + + def get_name(self) -> str: + return 'mixed_mm' + + def get_best_choices(self, context: AHContext) -> list[tuple[float, int]] | None: + if str(context.get_value('1LEQmLEQ16')) != 'True': + if context.get_value('m') <= 32.5: + if context.get_value('n') <= 6976.0: + if context.get_value('n') <= 3520.0: + if context.get_value('m*n') <= 37632.0: + return None + else: + return [(1.000, 13)] + else: + if context.get_value('m*k') <= 452352.0: + return [(0.590, 13), (0.256, 8), (0.103, 7), (0.051, 11)] + else: + return [(0.778, 8), (0.222, 13)] + else: + if context.get_value('k*n') <= 102776832.0: + if context.get_value('n') <= 14656.0: + return [(1.000, 11)] + else: + return [(0.889, 11), (0.111, 13)] + else: + return [(1.000, 11)] + else: + if context.get_value('m*n') <= 446464.0: + if context.get_value('m*n') <= 223424.0: + if context.get_value('mat1_stride_0') <= 3968.0: + return None + else: + return None + else: + if context.get_value('m*n') <= 346112.0: + return [(0.960, 16), (0.040, 7)] + else: + return [(0.750, 16), (0.136, 14), (0.114, 7)] + else: + if str(context.get_value('33LEQmLEQ64')) != 'True': + if context.get_value('n') <= 6976.0: + return [(1.000, 14)] + else: + return [(0.753, 2), (0.222, 1), (0.015, 7), (0.007, 16), (0.004, 12)] + else: + if context.get_value('n') <= 13888.0: + return [(0.710, 14), (0.275, 21), (0.014, 12)] + else: + return [(0.374, 19), (0.339, 20), (0.106, 21), (0.101, 16), (0.066, 17), (0.009, 14), (0.004, 18)] + else: + if context.get_value('n') <= 3520.0: + if context.get_value('arith_intensity') <= 3.994754433631897: + if str(context.get_value('mat2_dtype')) != 'torch.uint8': + if context.get_value('m*k') <= 18944.0: + return [(0.577, 5), (0.423, 6)] + else: + return [(0.988, 5), (0.012, 6)] + else: + if context.get_value('arith_intensity') <= 2.9899919033050537: + return None + else: + return None + else: + if context.get_value('arith_intensity') <= 7.956453561782837: + if context.get_value('k*n') <= 9244032.0: + return [(0.822, 5), (0.178, 6)] + else: + return [(0.977, 5), (0.023, 0)] + else: + if context.get_value('m*k') <= 978944.0: + return [(1.000, 5)] + else: + return [(0.971, 5), (0.029, 0)] + else: + if context.get_value('n') <= 13632.0: + if context.get_value('n') <= 6976.0: + return [(1.000, 6)] + else: + if context.get_value('k') <= 3968.0: + return [(0.617, 3), (0.111, 5), (0.099, 7), (0.086, 9), (0.062, 6), (0.025, 8)] + else: + return [(0.779, 8), (0.119, 5), (0.053, 7), (0.035, 6), (0.013, 3)] + else: + if context.get_value('k*n') <= 39518208.0: + return [(0.385, 4), (0.327, 3), (0.192, 6), (0.038, 7), (0.038, 10), (0.019, 5)] + else: + if context.get_value('n') <= 20800.0: + return [(0.821, 6), (0.121, 7), (0.029, 4), (0.014, 5), (0.007, 3), (0.007, 8)] + else: + return [(0.530, 7), (0.386, 6), (0.046, 8), (0.021, 3), (0.015, 4), (0.002, 5)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMH100.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMH100.py new file mode 100644 index 0000000000000000000000000000000000000000..a149cc39d7f6c5c98c76961a2b250a667d1220f1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMH100.py @@ -0,0 +1,149 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mixed_mm/ +from typing import Optional + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class MixedMMH100(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 232448 + and str(metadata.device_capa) == "(9, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.0 + + def get_choice(self, idx: int) -> str | None: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('extern_fallback_mixed_mm') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4') + self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8') + + def get_name(self) -> str: + return 'mixed_mm' + + def get_best_choices(self, context: AHContext) -> list[tuple[float, int]] | None: + if context.get_value('arith_intensity') <= 15.988086223602295: + if context.get_value('n') <= 25280.0: + if context.get_value('n') <= 1344.0: + if context.get_value('mat1_stride_0') <= 7808.0: + return [(0.581, 7), (0.419, 6)] + else: + if context.get_value('m*n') <= 7680.0: + return [(0.875, 0), (0.125, 6)] + else: + return [(0.833, 0), (0.167, 7)] + else: + if context.get_value('n') <= 8512.0: + if str(context.get_value('mat2_dtype')) != 'torch.int8': + return [(0.763, 6), (0.237, 7)] + else: + return [(0.725, 7), (0.275, 6)] + else: + if str(context.get_value('mat1_dtype')) != 'torch.bfloat16': + return [(0.736, 7), (0.197, 9), (0.048, 6), (0.014, 8), (0.005, 10)] + else: + return [(0.473, 7), (0.398, 6), (0.097, 9), (0.032, 10)] + else: + if context.get_value('n') <= 42254.0: + if context.get_value('n') <= 33856.0: + if context.get_value('k*n') <= 68157440.0: + return [(0.370, 4), (0.370, 5), (0.074, 7), (0.074, 8), (0.074, 11), (0.037, 6)] + else: + return [(0.916, 8), (0.036, 7), (0.036, 9), (0.012, 4)] + else: + return [(0.659, 5), (0.341, 6)] + else: + if context.get_value('k*n') <= 326052992.0: + if context.get_value('n') <= 55232.0: + return [(0.571, 6), (0.321, 7), (0.036, 4), (0.036, 8), (0.036, 9)] + else: + return [(0.506, 6), (0.325, 8), (0.104, 7), (0.039, 5), (0.026, 9)] + else: + if context.get_value('n') <= 57024.0: + return [(0.462, 9), (0.385, 7), (0.115, 6), (0.038, 8)] + else: + return [(0.598, 8), (0.223, 9), (0.107, 6), (0.071, 7)] + else: + if context.get_value('m*n') <= 543936.0: + if str(context.get_value('17LEQmLEQ32')) != 'True': + if context.get_value('m*n') <= 262272.0: + if context.get_value('n') <= 1592.5: + return [(0.860, 0), (0.140, 9)] + else: + return None + else: + if context.get_value('m*k') <= 1294336.0: + return [(0.833, 17), (0.150, 18), (0.017, 15)] + else: + return [(0.917, 17), (0.083, 8)] + else: + if context.get_value('n') <= 12416.0: + if context.get_value('m*n') <= 43008.0: + return None + else: + return [(0.853, 14), (0.147, 9)] + else: + return [(0.625, 12), (0.375, 14)] + else: + if context.get_value('m') <= 32.5: + if context.get_value('mat2_stride_1') <= 6656.0: + if context.get_value('n') <= 69184.0: + return [(0.611, 12), (0.361, 14), (0.028, 13)] + else: + return [(1.000, 12)] + else: + if context.get_value('mat2_stride_1') <= 20864.0: + return [(1.000, 12)] + else: + return [(0.958, 12), (0.042, 9)] + else: + if context.get_value('m*n') <= 1085440.0: + if context.get_value('n') <= 9152.0: + return [(1.000, 18)] + else: + return [(0.780, 18), (0.160, 16), (0.060, 20)] + else: + if context.get_value('m') <= 67.0: + return [(0.650, 16), (0.203, 19), (0.122, 18), (0.016, 20), (0.008, 1)] + else: + return [(0.561, 3), (0.185, 16), (0.096, 20), (0.083, 19), (0.076, 2)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMA100.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMA100.py new file mode 100644 index 0000000000000000000000000000000000000000..c19817f98484acb745a1fa600e25e1e3f3586307 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMA100.py @@ -0,0 +1,265 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/pad_mm/ +from typing import Optional + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class PadMMA100(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 166912 + and str(metadata.device_capa) == "(8, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.9294871794871795 + + def get_choice(self, idx: int) -> Optional[str]: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('orig') + self.choices.append('pad') + + def get_name(self) -> str: + return 'pad_mm' + + def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]: + if str(context.get_value('mat1_innermost_needs_padding')) != 'False': + if context.get_value('arith_intensity') <= 880.0238037109375: + if str(context.get_value('m_multiple_2')) != 'True': + if context.get_value('n') <= 652.0: + if context.get_value('m') <= 2022.0: + if str(context.get_value('using_tf32')) != 'False': + return [(0.579, 1), (0.421, 0)] + else: + return [(1.000, 0)] + else: + return [(1.000, 0)] + else: + if context.get_value('m*k') <= 107278336.0: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('m') <= 23691.0: + return [(0.993, 1), (0.007, 0)] + else: + return [(0.840, 1), (0.160, 0)] + else: + if context.get_value('arith_intensity') <= 793.3185424804688: + return [(0.958, 0), (0.042, 1)] + else: + return [(0.792, 1), (0.208, 0)] + else: + if context.get_value('arith_intensity') <= 795.6242370605469: + if context.get_value('mat2_stride_1') <= 2048.5: + return [(0.929, 0), (0.071, 1)] + else: + return [(1.000, 1)] + else: + if context.get_value('arith_intensity') <= 796.3460388183594: + return [(0.957, 1), (0.043, 0)] + else: + return [(0.778, 0), (0.222, 1)] + else: + if context.get_value('mat2_stride_0') <= 2432.0: + if str(context.get_value('k_multiple_2')) != 'False': + if context.get_value('n') <= 1024.5: + if str(context.get_value('prepadded_mat1')) != 'False': + return [(0.580, 0), (0.420, 1)] + else: + return [(0.986, 0), (0.014, 1)] + else: + if context.get_value('mat1_stride_0') <= 5125.0: + return [(0.551, 0), (0.449, 1)] + else: + return [(0.916, 0), (0.084, 1)] + else: + if context.get_value('mat2_align_size') <= 6.0: + if str(context.get_value('using_tf32')) != 'True': + return [(1.000, 0)] + else: + return [(0.800, 0), (0.200, 1)] + else: + if context.get_value('mat2_stride_1') <= 3820.0: + return [(0.986, 1), (0.014, 0)] + else: + return [(0.532, 0), (0.468, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('m*n') <= 5244928.0: + if str(context.get_value('k_multiple_2')) != 'True': + return [(0.971, 1), (0.029, 0)] + else: + return [(0.646, 1), (0.354, 0)] + else: + if context.get_value('k/(m*n)') <= 9.468618827668251e-06: + return [(0.800, 1), (0.200, 0)] + else: + return [(1.000, 1)] + else: + if context.get_value('mat1_stride_1') <= 1288.0: + if context.get_value('k') <= 5717.0: + return [(0.983, 0), (0.017, 1)] + else: + return [(0.800, 0), (0.200, 1)] + else: + return [(0.588, 0), (0.412, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('n') <= 2640.0: + if context.get_value('m_padded_length') <= 1.5: + if context.get_value('mat2_stride_1') <= 6021.0: + return [(1.000, 1)] + else: + if context.get_value('mat2_stride_1') <= 6069.0: + return [(0.900, 1), (0.100, 0)] + else: + return [(1.000, 1)] + else: + if str(context.get_value('m_multiple_2')) != 'False': + if context.get_value('m*k') <= 24444928.0: + return [(0.593, 0), (0.407, 1)] + else: + return [(0.923, 0), (0.077, 1)] + else: + return [(1.000, 1)] + else: + if context.get_value('m*k') <= 404182016.0: + if str(context.get_value('mat2_innermost_needs_padding')) != 'False': + if context.get_value('m*k') <= 12328960.0: + return [(0.732, 1), (0.268, 0)] + else: + return [(0.989, 1), (0.011, 0)] + else: + if context.get_value('m*k') <= 389028864.0: + return [(0.998, 1), (0.002, 0)] + else: + return [(0.922, 1), (0.078, 0)] + else: + if context.get_value('m*n') <= 137631744.0: + if context.get_value('m*k') <= 405715968.0: + return [(0.611, 1), (0.389, 0)] + else: + return [(0.946, 1), (0.054, 0)] + else: + return [(0.714, 0), (0.286, 1)] + else: + if context.get_value('mat2_stride_0') <= 3902.5: + return [(0.941, 0), (0.059, 1)] + else: + return [(0.583, 1), (0.417, 0)] + else: + if context.get_value('n_padded_length') <= 0.5: + if str(context.get_value('mat2_innermost_needs_padding')) != 'False': + if str(context.get_value('k_multiple_2')) != 'True': + if context.get_value('arith_intensity') <= 884.5185852050781: + if context.get_value('arith_intensity') <= 743.931884765625: + return [(1.000, 0)] + else: + return [(0.583, 0), (0.417, 1)] + else: + return [(1.000, 1)] + else: + if context.get_value('k/(m*n)') <= 0.00023481580865336582: + return [(0.900, 0), (0.100, 1)] + else: + return [(1.000, 0)] + else: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('m*k') <= 93734912.0: + if context.get_value('mat1_stride_0') <= 1344.0: + if context.get_value('n') <= 7168.0: + return [(1.000, 0)] + else: + return [(0.970, 0), (0.030, 1)] + else: + if context.get_value('m') <= 22883.5: + return [(0.977, 0), (0.023, 1)] + else: + return [(0.800, 0), (0.200, 1)] + else: + if context.get_value('arith_intensity') <= 1914.3681030273438: + if str(context.get_value('prepadded_mat1')) != 'False': + return [(0.981, 0), (0.019, 1)] + else: + return [(0.995, 0), (0.005, 1)] + else: + return [(1.000, 0)] + else: + if str(context.get_value('prepadded_mat1')) != 'False': + if context.get_value('mat2_stride_1') <= 256.5: + if context.get_value('m') <= 5880.5: + return [(1.000, 0)] + else: + return [(0.800, 0), (0.200, 1)] + else: + if context.get_value('m*k') <= 6318080.0: + return [(0.618, 1), (0.382, 0)] + else: + return [(0.880, 0), (0.120, 1)] + else: + if context.get_value('k/(m*n)') <= 0.0009747986623551697: + if context.get_value('k/(m*n)') <= 0.0006397514371201396: + return [(0.951, 0), (0.049, 1)] + else: + return [(0.857, 0), (0.143, 1)] + else: + return [(1.000, 0)] + else: + if str(context.get_value('using_tf32')) != 'False': + if str(context.get_value('n_multiple_2')) != 'False': + if context.get_value('m') <= 2024.0: + if context.get_value('mat2_stride_0') <= 1629.0: + if context.get_value('k*n') <= 1288704.0: + return [(0.600, 0), (0.400, 1)] + else: + return [(0.982, 0), (0.018, 1)] + else: + if context.get_value('mat1_stride_0') <= 768.0: + return [(0.619, 0), (0.381, 1)] + else: + return [(0.812, 1), (0.188, 0)] + else: + if context.get_value('m*n') <= 5803008.0: + return [(0.500, 0), (0.500, 1)] + else: + if context.get_value('mat2_stride_1') <= 896.0: + return [(1.000, 1)] + else: + return [(0.818, 1), (0.182, 0)] + else: + if context.get_value('mat2_stride_1') <= 2560.0: + if context.get_value('num_dims_needs_padding') <= 1.5: + if context.get_value('mat2_stride_1') <= 896.0: + return [(1.000, 1)] + else: + return [(0.857, 1), (0.143, 0)] + else: + return [(0.727, 1), (0.273, 0)] + else: + return [(0.667, 1), (0.333, 0)] + else: + if context.get_value('k/(m*n)') <= 0.00015462777810171247: + return [(0.857, 0), (0.143, 1)] + else: + if context.get_value('k/(m*n)') <= 0.0019917909521609545: + return [(1.000, 0)] + else: + return [(0.900, 0), (0.100, 1)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMH200.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMH200.py new file mode 100644 index 0000000000000000000000000000000000000000..1527b02319c105579be9b5aae81716142a9bf2ee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMH200.py @@ -0,0 +1,175 @@ +# flake8: noqa: B950 +# fmt: off +# This file was generated by AutoHeuristic. Do not modify it manually! +# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/pad_mm/ +from typing import Optional + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import ( + LearnedHeuristicDecision, +) + + +class PadMMH200(LearnedHeuristicDecision): + + def __init__(self) -> None: + self.choices: list[Choice] = [] + self.fill_choices() + + def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool: + return ( + metadata.name == self.get_name() + and metadata.shared_memory == 232448 + and str(metadata.device_capa) == "(9, 0)" + ) + + def get_confidence_threshold(self) -> float: + return 0.7710651828298887 + + def get_choice(self, idx: int) -> Optional[str]: + if idx < len(self.choices): + return self.choices[idx] + return None + + def fill_choices(self) -> None: + self.choices.append('orig') + self.choices.append('pad') + + def get_name(self) -> str: + return 'pad_mm' + + def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]: + if str(context.get_value('mat1_innermost_needs_padding')) != 'True': + if str(context.get_value('mat2_innermost_needs_padding')) != 'True': + if context.get_value('n_padded_length') <= 0.5: + if str(context.get_value('prepadded_mat1')) != 'True': + if str(context.get_value('using_tf32')) != 'False': + return [(1.000, 0)] + else: + if context.get_value('mat1_stride_0') <= 3584.0: + return [(1.000, 0)] + else: + if context.get_value('mat2_stride_0') <= 3584.0: + return [(1.000, 0)] + else: + return [(0.528, 0), (0.472, 1)] + else: + if context.get_value('n') <= 2304.0: + if context.get_value('m*k') <= 25198592.0: + if context.get_value('arith_intensity') <= 1103.9319458007812: + return [(1.000, 0)] + else: + return [(0.885, 0), (0.115, 1)] + else: + if context.get_value('m*k') <= 25688064.0: + return [(1.000, 1)] + else: + return [(0.771, 0), (0.229, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('m') <= 27825.0: + return [(0.948, 0), (0.052, 1)] + else: + return [(0.855, 0), (0.145, 1)] + else: + if context.get_value('mat2_stride_0') <= 3584.0: + return [(1.000, 0)] + else: + return [(0.917, 1), (0.083, 0)] + else: + if context.get_value('m') <= 1823.5: + if str(context.get_value('n_multiple_2')) != 'False': + if context.get_value('k*n') <= 7859200.0: + return [(0.600, 0), (0.400, 1)] + else: + return [(1.000, 0)] + else: + if context.get_value('k/(m*n)') <= 0.00040277576772496104: + return [(1.000, 1)] + else: + return [(0.800, 1), (0.200, 0)] + else: + if context.get_value('n') <= 3602.0: + return [(0.800, 1), (0.200, 0)] + else: + return [(1.000, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + if str(context.get_value('n_multiple_16')) != 'False': + if str(context.get_value('k_multiple_2')) != 'True': + if context.get_value('arith_intensity') <= 744.8332214355469: + return [(0.600, 0), (0.400, 1)] + else: + return [(1.000, 1)] + else: + if context.get_value('m*n') <= 8912896.0: + if context.get_value('m*k') <= 5934080.0: + return [(0.800, 0), (0.200, 1)] + else: + return [(1.000, 0)] + else: + return [(1.000, 1)] + else: + return [(1.000, 1)] + else: + return [(1.000, 0)] + else: + if context.get_value('arith_intensity') <= 895.8767395019531: + if str(context.get_value('m_multiple_2')) != 'False': + if context.get_value('mat1_stride_1') <= 3421.0: + if str(context.get_value('using_tf32')) != 'False': + if context.get_value('mat2_stride_1') <= 10706.5: + if context.get_value('mat2_stride_0') <= 1024.5: + return [(0.816, 1), (0.184, 0)] + else: + return [(1.000, 1)] + else: + if str(context.get_value('k_multiple_2')) != 'True': + return [(0.905, 1), (0.095, 0)] + else: + return [(1.000, 0)] + else: + if str(context.get_value('prepadded_mat2')) != 'True': + if str(context.get_value('mat2_innermost_needs_padding')) != 'False': + return [(1.000, 0)] + else: + return [(0.932, 0), (0.068, 1)] + else: + if context.get_value('arith_intensity') <= 742.1241760253906: + return [(0.889, 0), (0.111, 1)] + else: + return [(0.765, 1), (0.235, 0)] + else: + if context.get_value('n') <= 1216.0: + if str(context.get_value('using_tf32')) != 'True': + if context.get_value('mat1_stride_1') <= 5567.0: + return [(0.896, 0), (0.104, 1)] + else: + return [(0.999, 0), (0.001, 1)] + else: + return [(1.000, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + return [(1.000, 1)] + else: + return [(1.000, 0)] + else: + if str(context.get_value('using_tf32')) != 'False': + return [(1.000, 1)] + else: + if context.get_value('mat2_stride_1') <= 2688.0: + return [(1.000, 0)] + else: + return [(0.500, 0), (0.500, 1)] + else: + if str(context.get_value('using_tf32')) != 'False': + return [(1.000, 1)] + else: + if str(context.get_value('mat2_innermost_needs_padding')) != 'True': + return [(1.000, 0)] + else: + return [(0.800, 0), (0.200, 1)] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingA100.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingA100.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e12f044406d9347d1f26471e3b3e7733c7c29b06 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingA100.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingH100.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingH100.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35aa76709bf0acc79ca43bb4f482d888f1e69981 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingH100.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMA100.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMA100.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0319b4d5509c60aac40cb4b81b9d4a1dd8827c5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMA100.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMH100.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMH100.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f268466335d27165504ec741b7ab60889465b69 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMH100.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMA100.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMA100.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12ebcaf1fa1ff58151f6a9d49126aab7ce88dcf7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMA100.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMH200.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMH200.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5526b80090990fb48d114a6a492b67a60d77ab70 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMH200.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b8a52cb52a7713b9b81e8fa2837620628368426 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/artifacts/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b97a026d4fe622eacaad74bdd3a808e03379c2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic.py @@ -0,0 +1,320 @@ +import json +import os +from collections.abc import Callable +from functools import partial +from typing import Any + +import torch +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + AHOperation, + Choice, + CHOICE_COL, + Feedback, + FEEDBACK_COL, + get_metadata_str_from_log, +) +from torch._inductor.autoheuristic.learned_heuristic_controller import ( + LearnedHeuristicController, +) +from torch._inductor.ir import ChoiceCaller +from torch._inductor.runtime.runtime_utils import cache_dir +from torch._inductor.utils import get_gpu_shared_memory + + +class LocalFeedback: + """ + To be able to collect data for a choice, a function providing feedback given a choice has to be provided. + LocalFeedback can be used when AutoHeuristic should immediately run the function to collect feedback for each choice + (see pad_mm.py, where the autotuning happens locally, for an example). + """ + + def __init__(self, feedback_fn: Callable[[Choice], Feedback]) -> None: + self.feedback_fn = feedback_fn + + def __call__(self, choice: Choice) -> Feedback: + return self.feedback_fn(choice) + + +class InconsistentMetadata(Exception): + """ + Exception that is thrown when AutoHeuristic tries to log data to a file where the metadata stored in the file does + not match the metadata it would store if the file didn't exist. + """ + + +class AutoHeuristic: + """ + AutoHeuristic is a framework that allows one to collect data, learn a heuristic (i.e. a regression tree) and + generate the heuristic to code. This class allows one to collect data. The collected data can then be used to train + a heuristic (see torchgen/autoheuristic/). + """ + + collected_feedback: dict[Choice, Feedback] + + def __init__( + self, + fallback: Callable[[], Choice], + choices: list[Choice], + feedback: LocalFeedback | None, + context: AHContext, + name: str, + augment_context: list[AHOperation] | None = None, + precondition: Callable[[AHMetadata, AHContext], bool] | None = None, + ) -> None: + """ + Initializes an instance of the AutoHeuristic class. + + Args: + fallback: A callable that returns a Choice when the heuristic is unsure which choice to make, or + AutoHeuristic is in data collection mode. + choices: A list of possible choices the heuristic can make. + feedback: An instance of LocalFeedback that provides feedback for a given choice. + context: Context to store with each choice and feedback. + name: A string that identifies the heuristic. + augment_context: An optional list of AHOperation instances that augment the context. + precondition: A callable that returns a boolean indicating whether AutoHeuristic should run. + """ + self.fallback = fallback + self.choices = choices + self.feedback = feedback + self.context = context + self.name = name + self.collected_feedback = {} + self.augment_context = augment_context + self.metadata = AHMetadata( + get_gpu_shared_memory(), + torch.cuda.get_device_capability() if torch.cuda.is_available() else (0, 0), + self.choices, + self.name, + ) + self.precondition = precondition + + if not self.satisfies_precondition(): + return + + if torch._inductor.config.autoheuristic_log_path == "DEFAULT": + self.log_path = self.get_default_log_path() + else: + self.log_path = torch._inductor.config.autoheuristic_log_path + + if torch._inductor.config.collect_autoheuristic(self.name): + if self.feedback is not None: + for choice in self.choices: + feedback_val = self.feedback(choice) + self.save_data(choice, feedback_val) + + def satisfies_precondition(self) -> bool: + return self.precondition is None or self.precondition( + self.metadata, self.context + ) + + def get_choice(self) -> Choice: + """ + Returns the chosen option based on the value of autoheuristic_use. + If self.name is one of the comma separated strings in autoheuristic_use, + it queries a learned heuristic to make a decision. Otherwise, it returns the fallback option. + """ + + if not self.satisfies_precondition(): + return self.fallback() + + if torch._inductor.config.use_autoheuristic(self.name): + if self.augment_context is not None: + self.context.apply_operations(self.augment_context) + controller = LearnedHeuristicController( + self.metadata, + self.context, + ) + decision = controller.get_decision() + if decision not in self.choices: + # TODO(AlnisM): We might want to allow this in the future + return self.fallback() + if decision is not None: + return decision + return self.fallback() + + def get_top_k_choices( + self, top_k: int, always_included: list[str] | None = None + ) -> list[Choice] | None: + if not self.satisfies_precondition(): + return None + if torch._inductor.config.use_autoheuristic(self.name): + if self.augment_context is not None: + self.context.apply_operations(self.augment_context) + controller = LearnedHeuristicController( + self.metadata, + self.context, + ) + choices = controller.get_decisions_ranked(top_k) + if choices is None: + return None + if always_included is not None: + for choice in always_included: + if choice not in choices: + choices.append(choice) + return choices + return None + + def get_collected_feedback(self, choice: Choice) -> Any: + return self.collected_feedback.get(choice, None) + + @staticmethod + def get_device_identifier() -> str: + # a heuristic might work well for one GPU, but not for another + # we store the collected data per GPU model and learn a heuristic per GPU model + + # TODO(AlnisM): just using the device name for now, but the same GPU model can have different names + if torch.cuda.is_available(): + device_name = torch.cuda.get_device_name().replace(" ", "_") + return device_name + return "non_cuda_device" + + def get_default_log_path(self) -> str: + device_name = self.get_device_identifier() + path = f"{cache_dir()}/autoheuristic/{device_name}/" + os.makedirs(path, exist_ok=True) + path += f"{self.name}.txt" + return path + + def serialize_metadata(self) -> str: + metadata_dict = self.metadata.to_dict() + ( + num_features, + cat_features, + ) = self.context.get_numerical_and_categorical_features() + metadata_dict["numerical_features"] = num_features + metadata_dict["categorical_features"] = cat_features + return json.dumps(metadata_dict) + + def save_data(self, choice: Choice, feedback_val: Feedback) -> None: + self.collected_feedback[choice] = feedback_val + log_path = self.log_path + + lines = [] + log_exists = os.path.exists(log_path) + if log_exists: + # if log already exists, make sure it is consistent + metadata = self.serialize_metadata() + existing_metadata = get_metadata_str_from_log(self.log_path) + if existing_metadata != metadata: + raise InconsistentMetadata( + "Given metadata does not match existing metadata" + ) + else: + lines.append(self.serialize_metadata()) + feature_header = self.context.get_feature_names_csv() + header = feature_header + "," + CHOICE_COL + "," + FEEDBACK_COL + lines.append(header) + + line = "" + feature_values = self.context.get_feature_values_csv() + line += feature_values + "," + choice + "," + str(feedback_val) + lines.append(line) + + with open(log_path, "a") as f: + f.write("\n".join(lines) + "\n") + + +class AutoHeuristicSelectAlgorithm(AutoHeuristic): + """ + AutoHeuristicSelectAlgorithm is a subclass of AutoHeuristic that allows one to collect data and learn a heuristic + when one wants to use AutoHeuristic for kernel choice selection. + """ + + def __init__( + self, + fallback: Callable[[], ChoiceCaller | None], + choices: list[ChoiceCaller], + input_nodes: list[Any], + context: AHContext, + name: str, + augment_context: list[AHOperation] | None = None, + precondition: Callable[[AHMetadata, AHContext], bool] | None = None, + ) -> None: + """ + The arguments choices, input_nodes and name have to match the ones used in the call to + autotune_select_algorithm(), e.g. if the following call is made + autotune_select_algorithm(name, choices, input_nodes, layout), the same name, choices and input_nodes + have to be used here. + """ + self.input_nodes = input_nodes + self.choicestr2choice: dict[str, ChoiceCaller] = {} + for choice in choices: + self.choicestr2choice[choice.autoheuristic_id()] = choice + choices_str = list(self.choicestr2choice.keys()) + + def fallback_str() -> str: + fallback_choice = fallback() + if fallback_choice is None: + # TODO: Find a nicer way to handle this + return "unsure" + return fallback_choice.autoheuristic_id() + + super().__init__( + fallback_str, + choices_str, + None, + context, + name, + augment_context, + precondition, + ) + + if ( + torch._inductor.config.collect_autoheuristic(self.name) + and self.satisfies_precondition() + ): + self.register_global_feedback(input_nodes, choices) + + def register_global_feedback( + self, input_nodes: list[Any], choices: list[ChoiceCaller] + ) -> None: + """ + Registers a callback in select_algorithm, which is called with the timing of each choice. + """ + + from torch._inductor.select_algorithm import ( + add_feedback_saver, + create_inputs_key, + create_precompile_key, + ) + + def store_global_feedback( + ah_inputs_key: str, + ah_precompile_key: str, + timings: dict[ChoiceCaller, float], + name: str, + input_nodes: list[Any], + choices: list[ChoiceCaller], + profiled_time: Callable[[], dict[ChoiceCaller, float]], + precompile_times: dict[ChoiceCaller, float], + ) -> None: + current_inputs_key = create_inputs_key(input_nodes) + if current_inputs_key != ah_inputs_key: + return + current_precompile_key = create_precompile_key( + name, current_inputs_key, choices + ) + if current_precompile_key != ah_precompile_key: + return + for choice, time in timings.items(): + self.save_data(choice.autoheuristic_id(), time) + + inputs_key = create_inputs_key(input_nodes) + precompile_key = create_precompile_key(self.name, inputs_key, choices) + feedback_saver = partial(store_global_feedback, inputs_key, precompile_key) + add_feedback_saver(feedback_saver) + + def get_choice_caller(self) -> ChoiceCaller | None: + choice = self.get_choice() + return self.choicestr2choice.get(choice, None) + + def get_top_k_choices_caller( + self, top_k: int, always_included: list[str] | None = None + ) -> list[ChoiceCaller] | None: + choices = self.get_top_k_choices(top_k, always_included) + if choices is None: + return None + return [self.choicestr2choice[choice] for choice in choices] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bcdf48cae094bc22d20ebf2f87d07311725664db --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/autoheuristic_utils.py @@ -0,0 +1,340 @@ +import functools +from collections.abc import Callable +from typing import Any + +import torch + + +Feedback = float +Choice = str +Value = Any + +CHOICE_COL = "choice" +FEEDBACK_COL = "feedback" + + +class AHFeature: + """ + The context, that AutoHeuristic stores, is a list of features. AutoHeuristic needs to know whether a feature is + categorical (i.e., not a continuous variable) to learn a machine learning model. + """ + + def __init__(self, name: str, value: Value, is_categorical: bool = False) -> None: + self.name = name + self.value = value + self.is_categorical = is_categorical + + +class AHOperation: + """ + AHOperation can be used to augment the data collected by AutoHeuristic. + One might for example store features like m, k, n, but also want to use + features like m*n, or k*n, to learn a heuristic. Instead of storing features + that can be created from the collected data, one can use AHOperation to + create new features from the collected data. + """ + + def __init__( + self, name: str, func: Callable[[Any], Value], is_categorical: bool = False + ) -> None: + self.name = name + self.func = func + self.is_categorical = is_categorical + + def apply_operation(self, data: Any) -> None: + data[self.name] = self.func(data) + + +class AHContext: + """ + This class is used to specify which information AutoHeuristic should store. For each choice, AutoHeuristic will + store the context and the collected feedback. The context could be something like the shape of a tensor, i.e., + information that will help to learn a heuristic. + """ + + features: list[AHFeature] + context_dict: dict[str, Value] + + def __init__(self) -> None: + self.features = [] + self.context_dict = {} + + def add_feature( + self, name: str, value: Value, is_categorical: bool = False + ) -> None: + self.features.append(AHFeature(name, value, is_categorical=is_categorical)) + self.context_dict[name] = value + + def get_numerical_and_categorical_features(self) -> tuple[list[str], list[str]]: + numerical_features = [] + categorical_features = [] + for feature in self.features: + if feature.is_categorical: + categorical_features.append(feature.name) + else: + numerical_features.append(feature.name) + + return numerical_features, categorical_features + + def get_feature_names_csv(self) -> str: + return ",".join(feature.name for feature in self.features) + + def get_feature_values_csv(self) -> str: + return ",".join(str(feature.value) for feature in self.features) + + def get_value(self, name: str) -> Value: + return self.context_dict[name] + + def apply_operations(self, operations: list[AHOperation]) -> None: + for op in operations: + op.apply_operation(self.context_dict) + + +class AHMetadata: + def __init__( + self, + shared_memory: Any, + device_capa: tuple[int, int], + choices: list[Choice], + name: str, + ) -> None: + # use amount of shared_memory and device_capability to identify GPU + # TODO(AlnisM): there might be a better way to do this + self.shared_memory = shared_memory + self.device_capa = device_capa + self.choices = choices + self.name = name + + def to_dict(self) -> dict[str, Value]: + return { + "shared_memory": self.shared_memory, + "device_capa": self.device_capa, + "name": self.name, + } + + +def get_metadata_str_from_log(log_path: str) -> str: + with open(log_path, newline="") as file: + json_string = file.readline().strip() + return json_string + + +def check_minsize(context: AHContext, minsize: int) -> bool: + return ( + context.get_value("m") >= minsize + and context.get_value("k") >= minsize + and context.get_value("n") >= minsize + ) + + +def pad_mm_precondition(metadata: AHMetadata, context: AHContext) -> bool: + if metadata.shared_memory == 166912 and metadata.device_capa == (8, 0): + # A100 precondition + return check_minsize(context, 512) + elif metadata.shared_memory == 232448 and metadata.device_capa == (9, 0): + # H100 precondition + return check_minsize(context, 768) + return True + + +def get_mixedmm_precondition(metadata: AHMetadata, context: AHContext) -> bool: + m = context.get_value("m") + k = context.get_value("k") + n = context.get_value("n") + if m > 128 or k < 1024 or n < 1024: + return False + mat1_iscontig = context.get_value("mat1_iscontig") + mat2_iscontig = context.get_value("mat2_iscontig") + return mat1_iscontig and not mat2_iscontig + + +def get_mult_dims_ops() -> list[AHOperation]: + m_times_k_op = AHOperation("m*k", lambda data: data["m"] * data["k"]) + m_times_n_op = AHOperation("m*n", lambda data: data["m"] * data["n"]) + k_times_n_op = AHOperation("k*n", lambda data: data["k"] * data["n"]) + return [m_times_k_op, m_times_n_op, k_times_n_op] + + +def get_arith_intensity(data: Any) -> float: + m = data["m"] + k = data["k"] + n = data["n"] + if m == 0 or k == 0 or n == 0: + return 0.0 + return m * k * n / (m * k + k * n + m * n) + + +def pad_mm_operations() -> list[AHOperation]: + mult_dims_ops = get_mult_dims_ops() + k_div_m_times_n_op = AHOperation( + "k/(m*n)", lambda data: data["k"] / (data["m"] * data["n"]) + ) + + def bfloat_perf_hit(data: Any) -> bool: + m = data["m"] + k = data["k"] + n = data["n"] + is_bfloat = str(data["mat1_dtype"]) == "torch.bfloat16" + return k > (m * 1024) and k > (n * 1024) and is_bfloat + + bfloat_perf_hit_op = AHOperation( + "bfloat_perf_hit", bfloat_perf_hit, is_categorical=True + ) + + arith_intensity_op = AHOperation("arith_intensity", get_arith_intensity) + dims_need_padding_ops = get_dims_need_padding_ops() + dims_multiple_ops = get_dims_multiple_ops() + is_contig_ops = get_is_contig_ops() + + ah_operations = mult_dims_ops + [ + k_div_m_times_n_op, + bfloat_perf_hit_op, + arith_intensity_op, + ] + ah_operations.extend(dims_need_padding_ops) + ah_operations.extend(dims_multiple_ops) + ah_operations.extend(is_contig_ops) + return ah_operations + + +def between_op(data: Any, dim: str, lower: int, upper: int) -> bool: + return data[dim] >= lower and data[dim] <= upper + + +def between_ops() -> list[AHOperation]: + dims = ["m", "k", "n"] + limits = [(1, 16), (17, 32), (33, 64), (65, 128), (129, 256)] + ah_operations = [] + for dim in dims: + for lower, upper in limits: + between_op_fn = functools.partial( + between_op, dim=dim, lower=lower, upper=upper + ) + # using 'LEQ' instead of '<=' because '<=' cannot be exported to dot + between_op_name = f"{lower}LEQ{dim}LEQ{upper}" + ah_operations.append( + AHOperation(between_op_name, between_op_fn, is_categorical=True) + ) + return ah_operations + + +def pow2_op(data: Any, dim: str, exponent: int) -> bool: + return data[dim] == 2**exponent + + +def mm_operations() -> list[AHOperation]: + mult_dims_ops = get_mult_dims_ops() + arith_intensity_op = AHOperation("arith_intensity", get_arith_intensity) + return mult_dims_ops + [arith_intensity_op] + + +def mixed_mm_operations() -> list[AHOperation]: + return mm_operations() + between_ops() + + +def is_multiple(data: Any, dim: str, mult: int) -> bool: + return data[dim] % mult == 0 + + +def get_dims_multiple_ops() -> list[AHOperation]: + multiples = [2, 4, 8, 16, 32] + dims = ["m", "k", "n"] + dims_multiple_ops = [] + for dim in dims: + for mult in multiples: + is_multiple_fn = functools.partial(is_multiple, dim=dim, mult=mult) + dims_multiple_op = AHOperation( + f"{dim}_multiple_{mult}", is_multiple_fn, is_categorical=True + ) + dims_multiple_ops.append(dims_multiple_op) + return dims_multiple_ops + + +def get_dims_need_padding_ops() -> list[AHOperation]: + def mat1_innermost_needs_padding_fn(data: Any) -> bool: + mat1_stride_0 = data["mat1_stride_0"] + mat1_stride_1 = data["mat1_stride_1"] + m_padded_length = data["m_padded_length"] + k_padded_length = data["k_padded_length"] + mat1_innermost_needs_padding = False + if mat1_stride_0 == 1 and m_padded_length != 0: + mat1_innermost_needs_padding = True + if mat1_stride_1 == 1 and k_padded_length != 0: + mat1_innermost_needs_padding = True + return mat1_innermost_needs_padding + + mat1_innermost_op = AHOperation( + "mat1_innermost_needs_padding", + mat1_innermost_needs_padding_fn, + is_categorical=True, + ) + + def mat2_innermost_needs_padding_fn(data: Any) -> bool: + mat2_stride_0 = data["mat2_stride_0"] + mat2_stride_1 = data["mat2_stride_1"] + k_padded_length = data["k_padded_length"] + n_padded_length = data["n_padded_length"] + mat2_innermost_needs_padding = False + if mat2_stride_0 == 1 and k_padded_length != 0: + mat2_innermost_needs_padding = True + if mat2_stride_1 == 1 and n_padded_length != 0: + mat2_innermost_needs_padding = True + return mat2_innermost_needs_padding + + mat2_innermost_op = AHOperation( + "mat2_innermost_needs_padding", + mat2_innermost_needs_padding_fn, + is_categorical=True, + ) + + def num_dims_needs_padding_fn(data: Any) -> int: + m_padded_length = data["m_padded_length"] + k_padded_length = data["k_padded_length"] + n_padded_length = data["n_padded_length"] + num_dims_needs_padding = 0 + if m_padded_length != 0: + num_dims_needs_padding += 1 + if k_padded_length != 0: + num_dims_needs_padding += 1 + if n_padded_length != 0: + num_dims_needs_padding += 1 + return num_dims_needs_padding + + num_dims_op = AHOperation("num_dims_needs_padding", num_dims_needs_padding_fn) + return [mat1_innermost_op, mat2_innermost_op, num_dims_op] + + +def get_is_contig_ops() -> list[AHOperation]: + def mat1_is_contig_fn(data: Any) -> bool: + stride_0 = data["mat1_stride_0"] + stride_1 = data["mat1_stride_1"] + k = data["k"] + return stride_0 == k and stride_1 == 1 + + mat1_is_contig_op = AHOperation( + "mat1_iscontig", mat1_is_contig_fn, is_categorical=True + ) + + def mat2_is_contig_fn(data: Any) -> bool: + stride_0 = data["mat2_stride_0"] + stride_1 = data["mat2_stride_1"] + n = data["n"] + return stride_0 == n and stride_1 == 1 + + mat2_is_contig_op = AHOperation( + "mat2_iscontig", mat2_is_contig_fn, is_categorical=True + ) + + return [mat1_is_contig_op, mat2_is_contig_op] + + +def context_add_strides(context: AHContext, name: str, stride: tuple[int, ...]) -> None: + for i, s in enumerate(stride): + context.add_feature(f"{name}_stride_{i}", s) + + +def context_add_using_tf32(context: AHContext, dtype: torch.dtype) -> None: + using_tf32 = "not_float_32" + if dtype == torch.float32: + using_tf32 = torch.backends.cuda.matmul.fp32_precision == "tf32" + context.add_feature("using_tf32", using_tf32, is_categorical=True) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learned_heuristic_controller.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learned_heuristic_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..26f03e3838c33b3a2bdf3b1a325ffa6bce19ff2e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learned_heuristic_controller.py @@ -0,0 +1,119 @@ +import importlib +import inspect +import pkgutil +from collections import defaultdict +from typing import Any + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) +from torch._inductor.autoheuristic.learnedheuristic_interface import LearnedHeuristic + + +def find_and_instantiate_subclasses( + package_name: str, base_class: Any +) -> list[LearnedHeuristic]: + instances = [] + + package = importlib.import_module(package_name) + for _, module_name, _ in pkgutil.walk_packages( + package.__path__, package.__name__ + "." + ): + try: + module_basename = module_name.split(".")[-1] + if not module_basename.startswith("_"): + # learned heuristics start with an underscore + continue + module = importlib.import_module(module_name) + + # look for classes that are subclasses of base_class + for _name, obj in inspect.getmembers(module): + if ( + inspect.isclass(obj) + and issubclass(obj, base_class) + and obj != base_class + ): + instance = obj() + instances.append(instance) + except Exception as e: + print(f"Error processing module {module_name}: {e}") + + return instances + + +class LearnedHeuristicController: + """ + Class that finds and instantiates all learned heuristics. It also provides + a way to get the decision of a learned heuristic. + """ + + existing_heuristics: dict[str, list[LearnedHeuristic]] = defaultdict(list) + """ + A dictionary that stores all the learned heuristics for each optimization. + The key is the optimization name, and the value is a list of LearnedHeuristic objects. + """ + + heuristics_initialized: bool = False + """ + A flag that indicates whether the learned heuristics have been initialized. + Set to true when the get_decision() function is called for the first time. + """ + + def __init__( + self, + metadata: AHMetadata, + context: AHContext, + ) -> None: + self.metadata = metadata + self.context = context + + def get_heuristics(self, name: str) -> list[LearnedHeuristic]: + """ + Returns a list of learned heuristics for the given optimization name. + """ + + if not LearnedHeuristicController.heuristics_initialized: + # learned heuristics are generated into the following package + learned_heuristics_package = "torch._inductor.autoheuristic.artifacts" + + # learned heuristics have to be of type LearnedHeuristic + base_class = LearnedHeuristic + found_heuristics = find_and_instantiate_subclasses( + learned_heuristics_package, base_class + ) + + for learned_heuristic in found_heuristics: + opt_name = learned_heuristic.get_name() + LearnedHeuristicController.existing_heuristics[opt_name].append( + learned_heuristic + ) + LearnedHeuristicController.heuristics_initialized = True + + return LearnedHeuristicController.existing_heuristics[name] + + def get_decision(self) -> Choice | None: + """ + Returns the decision made by the learned heuristic or None if no heuristic was found or the heuristic is unsure + which choice to make. + """ + + heuristics = self.get_heuristics(self.metadata.name) + for heuristic in heuristics: + if heuristic.check_precondition(self.metadata, self.context): + return heuristic.get_decision(self.context, self.metadata.choices) + return None + + def get_decisions_ranked(self, top_k: int) -> list[Choice] | None: + heuristics = self.get_heuristics(self.metadata.name) + for heuristic in heuristics: + if heuristic.check_precondition(self.metadata, self.context): + choices = heuristic.get_decisions_ranked(self.context) + if choices is None: + return None + avail_choices = [ + choice for choice in choices if choice in self.metadata.choices + ] + return avail_choices[:top_k] + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learnedheuristic_interface.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learnedheuristic_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..85558cf8e488c7f56fa99c4f59b6150eb37ff592 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autoheuristic/learnedheuristic_interface.py @@ -0,0 +1,82 @@ +import operator + +from torch._inductor.autoheuristic.autoheuristic_utils import ( + AHContext, + AHMetadata, + Choice, +) + + +class LearnedHeuristic: + """ + LearnedHeuristic is a base class for all learned heuristics. + """ + + def __init__(self) -> None: + pass + + def check_precondition( + self, + metadata: AHMetadata, + context: AHContext, + ) -> bool: + return True + + def get_decision(self, context: AHContext, choices: list[Choice]) -> Choice | None: + return None + + def get_confidence_threshold(self) -> float: + return 1.0 + + def get_name(self) -> str: + return "" + + def get_decisions_ranked(self, context: AHContext) -> list[str] | None: + return None + + +class LearnedHeuristicRegression(LearnedHeuristic): + def get_feedback(self, context: AHContext, choice: Choice) -> float: + return 1.0 + + def get_decision(self, context: AHContext, choices: list[Choice]) -> Choice | None: + choice2feedback = {} + for choice in choices: + predicted_feedback = self.get_feedback(context, choice) + choice2feedback[choice] = predicted_feedback + sorted_choices_feedback = sorted( + choice2feedback.items(), key=operator.itemgetter(1) + ) + highest_feedback = sorted_choices_feedback[-1][1] + second_highest_feedback = sorted_choices_feedback[-2][1] + if highest_feedback / second_highest_feedback > self.get_confidence_threshold(): + return sorted_choices_feedback[-1][0] + # We are not sure which choice is the best one + return None + + +class LearnedHeuristicDecision(LearnedHeuristic): + def get_choice(self, idx: int) -> str | None: + return None + + def get_decision(self, context: AHContext, choices: list[Choice]) -> Choice | None: + best_choices = self.get_best_choices(context) + if not best_choices: + return None + (best_choice_proba, best_choice_idx) = best_choices[0] + if best_choice_proba <= self.get_confidence_threshold(): + return None + return self.get_choice(best_choice_idx) + + def get_decisions_ranked(self, context: AHContext) -> list[str] | None: + feedback_idx_list = self.get_best_choices(context) + if feedback_idx_list is None: + return None + choices = [ + self.get_choice(feedback_idx[1]) for feedback_idx in feedback_idx_list + ] + choices = [choice for choice in choices if choice is not None] + return choices + + def get_best_choices(self, context: AHContext) -> list[tuple[float, int]] | None: + return [] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autotune_process.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autotune_process.py new file mode 100644 index 0000000000000000000000000000000000000000..e65dc3f67cbbcfc677c5add90c610e8680dd0768 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autotune_process.py @@ -0,0 +1,1685 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import atexit +import contextvars +import ctypes +import dataclasses +import functools +import logging +import multiprocessing as mp +import os +import pickle +import queue +import selectors +import subprocess +import sys +import threading +import time +import warnings +from collections.abc import Callable, Iterable, Sequence +from concurrent.futures import Future, ProcessPoolExecutor, ThreadPoolExecutor +from ctypes import byref, c_size_t, c_void_p, CDLL +from typing import Any, IO, TYPE_CHECKING +from typing_extensions import override + +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._inductor import ir +from torch._inductor.codecache import ( + CppCodeCache, + CUDACodeCache, + DLLWrapper, + get_hash, + PyCodeCache, + write, + XPUCodeCache, +) +from torch._inductor.compile_worker.timer import Timer +from torch._inductor.utils import ( + apply_subprocess_env, + clear_caches, + clear_on_fresh_cache, + do_bench_using_profiling, + get_gpu_type, + get_ld_library_path, + is_gpu, + python_subprocess_env, +) +from torch._logging import getArtifactLogger +from torch.utils._ordered_set import OrderedSet + + +# Inactivity timeout for AutotuneProcessPool in seconds. +# Default: 600 seconds (10 minutes). Set to 0 to disable. +AUTOTUNE_POOL_INACTIVITY_TIMEOUT = int( + os.environ.get("TORCHINDUCTOR_AUTOTUNE_POOL_INACTIVITY_TIMEOUT", "600") +) + +if TYPE_CHECKING: + from types import ModuleType + + from torch._inductor.select_algorithm import ( + ChoiceCaller, + PartialRender, + TritonTemplateCaller, + ) + +from . import config +from .runtime.benchmarking import benchmarker +from .virtualized import V + + +CUDA_VISIBLE_DEVICES = "CUDA_VISIBLE_DEVICES" + + +_visible_device_env_var_maps = { + "cuda": "CUDA_VISIBLE_DEVICES", + "xpu": "ZE_AFFINITY_MASK", +} + + +def get_visible_devices_env_var(gpu_type: str | None = None) -> str: + if gpu_type is None: + gpu_type = get_gpu_type() + if gpu_type not in _visible_device_env_var_maps: + raise ValueError(f"Unsupported gpu_type: {gpu_type}") + return _visible_device_env_var_maps[gpu_type] + + +autotuning_log = getArtifactLogger(__name__, "autotuning") + + +class NonzeroWorkspaceNotSupportedError(Exception): + pass + + +def _cache_env_for_subprocess() -> dict[str, str | None]: + env_vars = ["TORCHINDUCTOR_CACHE_DIR", "TRITON_CACHE_DIR"] + return {v: os.environ.get(v) for v in env_vars} + + +_last_applied_cache_env: dict[str, str | None] | None = None + + +def _apply_subprocess_env_and_clear_caches( + extra_env: dict[str, str | None] | None, +) -> None: + global _last_applied_cache_env + + if extra_env is None: + return + + if extra_env != _last_applied_cache_env: + clear_caches() + _last_applied_cache_env = extra_env.copy() + apply_subprocess_env(extra_env) + + +def _run_with_subprocess_env( + fn: Callable[..., Any], + extra_env: dict[str, str | None], + *args: Any, + **kwargs: Any, +) -> Any: + _apply_subprocess_env_and_clear_caches(extra_env) + return fn(*args, **kwargs) + + +class TuningProcess: + """ + Class to launch and interact with a benchmarking subprocess. + """ + + @staticmethod + def process_main(read_pipe: IO[bytes], write_pipe: IO[bytes]) -> None: + """ + Entry point for the child process. + """ + autotuning_log.debug( + "Started autotune subprocess %s. Visible devices: %s", + os.getpid(), + os.environ.get(get_visible_devices_env_var()), + ) + + def workloop(): + while True: + job, extra_env = TuningProcess.recv(read_pipe) + if job is None: + # None is a sentinel for the child to shut down + break + try: + _apply_subprocess_env_and_clear_caches(extra_env) + result = job() + except Exception as e: + result = e + TuningProcess.send(result, write_pipe) + + try: + workloop() + except EOFError: + # The parent closed the pipe + pass + + @staticmethod + def send( + obj: Any, write_pipe: IO[bytes], extra_env: dict[str, str | None] | None = None + ) -> None: + pickle.dump((obj, extra_env), write_pipe) + write_pipe.flush() + + @staticmethod + def recv(read_pipe: IO[bytes]) -> Any: + return pickle.load(read_pipe) + + def __init__(self, device: int | None): + self.device = device + self.start() + + def start(self): + """ + Start the benchmarking subprocess. + """ + entry = os.path.join(os.path.dirname(__file__), "__autotune_main__.py") + + 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") + + self.selector = selectors.DefaultSelector() + self.selector.register(self.read_pipe, selectors.EVENT_READ) + + cmd = [ + sys.executable, + entry, + f"--parent={os.getpid()}", + f"--read-fd={str(subproc_read_fd)}", + f"--write-fd={str(subproc_write_fd)}", + ] + env = { + **python_subprocess_env(), + # We shouldn't be using the Triton async compile subprocess pool, + # but as a precaution set the env var that disables its creation. + "TORCH_WARM_POOL": "0", + # Some internal usages need a modified LD_LIBRARY_PATH. + "LD_LIBRARY_PATH": get_ld_library_path(), + # This will cause the subprocs to profile using the profiler. + "TORCHINDUCTOR_PROFILE_WITH_DO_BENCH_USING_PROFILING": "1" + if config.profile_bandwidth_with_do_bench_using_profiling + else "0", + } + if self.device is not None: + env[get_visible_devices_env_var()] = str(self.device) + self.process = subprocess.Popen( + cmd, + env=env, + pass_fds=(subproc_read_fd, subproc_write_fd), + ) + os.close(subproc_read_fd) + os.close(subproc_write_fd) + + self.running = True + + def alive(self) -> bool: + """ + True if the subprocess is still running. + """ + return self.running and self.process.poll() is None + + def put(self, req: Any, extra_env: dict[str, str | None] | None = None) -> None: + """ + Push a work item to the child process. + """ + if not self.alive(): + self.start() + TuningProcess.send(req, self.write_pipe, extra_env=extra_env) + + def get(self, timeout: float = 120.0) -> Any: + """ + Get a response from the child process. Raises TimeoutError on timeout; + raises EOFError if the subprocess crashes. + """ + try: + if not self.selector.select(timeout): + raise TimeoutError(f"Timeout in autotune subprocess {self.process.pid}") + result, _ = TuningProcess.recv(self.read_pipe) + except TimeoutError: + self.kill() + raise + except EOFError: + # The subprocess crashed + self.close() + raise + except Exception: + autotuning_log.exception( + "Unexpected exception in autotune subprocess %s", self.process.pid + ) + self.kill() + raise + + if isinstance(result, Exception): + raise result + return result + + def shutdown(self, wait: bool = True) -> None: + """ + Signal the child process to shut down gracefully. + """ + if self.alive(): + TuningProcess.send(None, self.write_pipe) + if wait: + self.wait() + + def wait(self) -> None: + """ + Wait for the child process to exit. + """ + if self.alive(): + self.process.wait() + self.close() + + def close(self) -> None: + """ + Close resources. + """ + self.selector.close() + self.read_pipe.close() + self.write_pipe.close() + self.running = False + + def kill(self) -> None: + """ + Send a SIGKILL to the child process. + """ + if self.alive(): + autotuning_log.error( + "Sending SIGKILL to autotune subprocess %d", + self.process.pid, + ) + self.process.kill() + self.close() + + def restart(self) -> None: + """ + Gracefully restarts the child process. + """ + self.shutdown(wait=True) + self.start() + + +class TuningProcessPool: + """ + Maintains a pool of TuningProcesses to benchmark kernels in parallel + across devices. By default, we create one TuningProcess per device and + set the sub-process environment to make only that device visible. + """ + + def __init__(self) -> None: + """ + Start the child processes. + """ + devices = self.get_device_list() + autotuning_log.debug("Sub-process autotune device list: %s", devices) + + # Launch the child processes. + self.processes = [TuningProcess(device=device) for device in devices] + + self.process_queue: queue.Queue[TuningProcess] = queue.Queue() + for p in self.processes: + self.process_queue.put(p) + + # Use a thread pool to manage distributing work to the subprocesses. + # Threads block on an available process, so it makes sense to match + # the number of threads with the number of devices. + self.executor = ThreadPoolExecutor(max_workers=len(devices)) + + @staticmethod + def get_device_list() -> Sequence[int | None]: + """ + Gather the list of devices to be used in the pool. + """ + if not config.autotune_multi_device: + # Don't use multiple devices + return [None] + + gpu_type = get_gpu_type() + device_interface = get_interface_for_device(gpu_type) + count = device_interface.device_count() + visible_devices_env_var = get_visible_devices_env_var(gpu_type) + + # If the user specified the visible devices in the env, use those. + if visible_devices_env_var in os.environ: + devices = [int(d) for d in os.environ[visible_devices_env_var].split(",")] + if not len(devices) <= count: + raise AssertionError( + f"{visible_devices_env_var} specifies {len(devices)} devices, " + f"but only {count} devices are available" + ) + return devices + + return list(range(count)) + + def shutdown(self) -> None: + """ + Signal all child processes to exit. + """ + self.executor.shutdown() + + for p in self.processes: + p.shutdown(wait=False) + for p in self.processes: + p.wait() + + def target(self, choice: TritonTemplateCaller) -> float: + """ + Entry point for the thread-pool helper threads: Wait for an open TuningProcess, + remove it from the queue, execute the benchmark in that subprocess, and return + the TuningProcess to the queue. + """ + if choice.bmreq is None: + raise AssertionError( + f"Expected choice.bmreq to be set, but got None for choice '{choice}'" + ) + + extra_env = _cache_env_for_subprocess() + process = self.process_queue.get() + process.put(choice.bmreq.benchmark, extra_env=extra_env) + try: + return process.get( + config.max_autotune_subproc_result_timeout_seconds, + ) + except TimeoutError: + warnings.warn( + f"Timed out benchmarking choice '{choice}'. It will be ignored. " + "Please debug the root cause in case the choice can bring perf gains." + ) + # Set to INF so this choice will be ignored + return float("inf") + except Exception as process_exception: + warnings.warn( + f"Failed to benchmark choice '{choice}'. It will be ignored. " + "Please debug the root cause in case the choice can bring perf gains." + ) + # Sticky CUDA errors corrupt the context, making it unrecoverable. + # The process must be restarted to restore CUDA functionality. + error_msg = str(process_exception) + if ( + "cudaErrorLaunchFailure" in error_msg + or "cudaErrorIllegalAddress" in error_msg + ): + process.restart() + # Set to INF so this choice will be ignored + return float("inf") + finally: + self.process_queue.put(process) + + def benchmark( + self, + choices: list[TritonTemplateCaller], + ) -> dict[TritonTemplateCaller, float]: + """ + Benchmark each choice in a separate process. + """ + + # Use a ThreadExecutorPool to spread the work across the subprocesses and + # to grab subprocesses as soon as they're free. + results = dict(zip(choices, self.executor.map(self.target, choices))) + + return results + + +LayoutOrBuffer = ir.Layout | ir.Buffer + + +@dataclasses.dataclass +class TensorMeta: + device: torch.device + dtype: torch.dtype + sizes: torch._prims_common.ShapeType + strides: torch._prims_common.StrideType + offset: int + name: str | None = None + + @classmethod + def from_irnodes( + cls, irnodes: LayoutOrBuffer | Sequence[LayoutOrBuffer] + ) -> TensorMeta | list[TensorMeta]: + from torch._inductor.select_algorithm import get_strides_with_layout_constraints + + if isinstance(irnodes, Sequence): + result: list[Any] = [cls.from_irnodes(x) for x in irnodes] + if not all(isinstance(x, TensorMeta) for x in result): + raise AssertionError( + f"Expected all elements to be TensorMeta, got types: " + f"{[type(x) for x in result if not isinstance(x, TensorMeta)]}" + ) + return result + + node = irnodes + if isinstance(node, ir.Layout): + node = ir.Buffer(name="fake", layout=node) + + dtype = node.get_dtype() + if dtype is None: + raise AssertionError( + f"Expected node to have a dtype, but get_dtype() returned None for node '{node}'" + ) + device = node.get_device() + if device is None: + raise AssertionError( + f"Expected node to have a device, but get_device() returned None for node '{node}'" + ) + + return TensorMeta( + device=device, + dtype=dtype, + sizes=V.graph.sizevars.optimization_hints(node.get_size()), + strides=V.graph.sizevars.optimization_hints( + get_strides_with_layout_constraints(node) + ), + offset=V.graph.sizevars.optimization_hint(node.get_layout().offset), + name=node.get_name(), + ) + + def to_tensor(self) -> torch.Tensor: + return rand_strided( + self.sizes, + self.strides, + device=self.device, + dtype=self.dtype, + extra_size=self.offset, + ) + + +@dataclasses.dataclass +class BenchmarkRequest: + """ + Only handle triton template benchmark for now. The extern kernel benchmark + can be done inside the same process since they usually don't cause crash. + + Important: Instances of this class and subclasses 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], + ) -> None: + # the kernel name defined in the module + self.kernel_name = kernel_name + + if isinstance(input_tensor_meta, TensorMeta): + self.input_tensor_meta: list[TensorMeta] = [input_tensor_meta] + else: + self.input_tensor_meta: list[TensorMeta] = input_tensor_meta + + if output_tensor_meta and isinstance(output_tensor_meta, (tuple, list)): + if len(output_tensor_meta) > 1: + # Each output with same meta for Grouped GEMM + if not all( + getattr(output_tensor_meta[0], attr) == getattr(x, attr) + for x in output_tensor_meta + for attr in ["device", "dtype", "sizes", "strides", "offset"] + ): + raise AssertionError( + "All output tensor metas in a Grouped GEMM must have matching " + "device, dtype, sizes, strides, and offset" + ) + self.output_tensor_meta = output_tensor_meta[0] + else: + # pyrefly: ignore [bad-assignment] + self.output_tensor_meta: TensorMeta = output_tensor_meta + + self.extra_args = extra_args + self.benchmark_with_cudagraphs = False + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + raise NotImplementedError + + def cleanup_run_fn(self) -> None: + pass + + def do_bench( + self, + fn, + *input_tensors: torch.Tensor, + out: torch.Tensor | None = None, + ) -> float: + raise NotImplementedError + + def benchmark( + self, + *input_tensors: torch.Tensor, + out: torch.Tensor | None = None, + ) -> float: + debug = autotuning_log.isEnabledFor(logging.DEBUG) + if debug: + start_ts = time.time() + + # create args and out tensor + if out is None: + if not (self.input_tensor_meta and self.output_tensor_meta): + raise AssertionError( + "Input and output tensor meta must be populated when input_tensors is empty" + ) + if not len(input_tensors) == 0: + raise AssertionError( + f"Expected no input_tensors when out is None, but got {len(input_tensors)}" + ) + input_tensors = tuple(x.to_tensor() for x in self.input_tensor_meta) + out = self.output_tensor_meta.to_tensor() + + if debug: + create_tensor_elapse = time.time() - start_ts # type: ignore[possibly-undefined] + start_ts = time.time() + try: + try: + fn = self.make_run_fn(*input_tensors, out=out) + except NonzeroWorkspaceNotSupportedError: + # Skipping all ops with nonzero workspace requirements + autotuning_log.info("Skipping op due to nonzero workspace requirement") + return float("inf") + + if debug: + load_elapse = time.time() - start_ts # type: ignore[possibly-undefined] + start_ts = time.time() + + if self.benchmark_with_cudagraphs: + res = benchmarker.benchmark_gpu_with_cuda_graph(fn) + else: + res = self.do_bench(fn, *input_tensors, out) + + if debug: + bench_elapse = time.time() - start_ts # type: ignore[possibly-undefined] + autotuning_log.debug( + "InChildProcess %s: load %f, create tensor %f, bench %f", + self, + load_elapse, # type: ignore[possibly-undefined] + create_tensor_elapse, # type: ignore[possibly-undefined] + bench_elapse, + ) + return res + finally: + self.cleanup_run_fn() + + +class _TestBenchmarkRequest(BenchmarkRequest): + """ + Supports unit testing. Defined in this file instead of the test file so the + TuningProcess sub-process can unpickle these objects. + """ + + def __init__( + self, + result: float = 0.0, + device: int | None = None, + sleep: float | None = None, + exc: Exception | None = None, + crash: bool = False, + ): + self.result = result + self.device = device + self.sleep = sleep + self.exc = exc + self.crash = crash + + def benchmark( + self, *input_tensors: torch.Tensor, out: torch.Tensor | None = None + ) -> float: + if self.device is not None: + visible_devices_env_var = get_visible_devices_env_var() + if os.environ.get(visible_devices_env_var, None) != str(self.device): + raise AssertionError( + f"Expected {visible_devices_env_var}='{self.device}', " + f"but got '{os.environ.get(visible_devices_env_var, None)}'" + ) + if self.sleep: + time.sleep(self.sleep) + if self.exc: + raise self.exc + if self.crash: + sys.exit(1) + return self.result + + +class _TestEnvBenchmarkRequest: + """ + Supports unit testing subprocess environment propagation. + """ + + def __init__(self, key: str): + self.key = key + + def benchmark( + self, *input_tensors: torch.Tensor, out: torch.Tensor | None = None + ) -> str | None: + return os.environ.get(self.key) + + +@clear_on_fresh_cache +class _TestCodeCache: + @classmethod + def cache_clear(cls) -> None: + cls.write.cache_clear() + + @classmethod + @functools.lru_cache(None) + def write(cls, source_code: str) -> tuple[str, str]: + return write(source_code, "txt") + + +class _TestCodeCacheBenchmarkRequest: + """ + Supports unit testing subprocess codecache resets. + """ + + source_code = "test codecache contents\n" + + def benchmark( + self, *input_tensors: torch.Tensor, out: torch.Tensor | None = None + ) -> str: + _, input_path = _TestCodeCache.write(self.source_code) + return input_path + + +class GPUDeviceBenchmarkMixin: + def do_bench( + self, + fn, + *input_tensors: torch.Tensor, + out: torch.Tensor | None = None, + ) -> float: + device_idx_set = OrderedSet( + tensor.device.index + for tensor in [*input_tensors, out] + if isinstance(tensor, torch.Tensor) + and is_gpu(tensor.device.type) + and tensor.device.index is not None + ) + if not len(device_idx_set) <= 1: + raise AssertionError(f"Can not mix devices {device_idx_set}") + device_type = next( + ( + tensor.device.type + for tensor in input_tensors + if is_gpu(tensor.device.type) + ), + "cuda", + ) + device_interface = get_interface_for_device(device_type) + if len(device_idx_set) == 1: + device_idx = next(iter(device_idx_set)) + else: + device_idx = device_interface.current_device() + with device_interface.device(device_idx): # type: ignore[attr-defined] + res = benchmarker.benchmark(fn, device=device_type) + device_interface.synchronize() # shake out any CUDA errors + + return res + + +class CPUDeviceBenchmarkMixin: + def do_bench( + self, + fn, + *input_tensors: torch.Tensor, + out: torch.Tensor | None = None, + ) -> float: + return benchmarker.benchmark_cpu(fn) + + +class TritonBenchmarkRequest(BenchmarkRequest): + """ + Represents a standalone benchmark request for a Triton Template. + + 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], + module_path: str, # the path of the module defining the triton kernel + module_cache_key: str, + num_stages: int, + num_warps: int, + num_consumer_groups: int = 0, + num_buffers_warp_spec: int = 0, + matrix_instr_nonkdim: int = 0, # only used for hip to choose the shape of mfma instruction. + waves_per_eu: int = 0, # only used for hip to schedule waves per execution unit + kpack: int = 0, # ROCm specific gemm parameter + workspace_size: int | None = None, # size of workspace buffer in bytes + workspace_zero_fill: bool = False, # whether to zero-fill workspace + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args) + self.module_path = module_path + self.module_cache_key = module_cache_key + 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.matrix_instr_nonkdim = matrix_instr_nonkdim + self.waves_per_eu = waves_per_eu + self.kpack = kpack + self.workspace_size = workspace_size + self.workspace_zero_fill = workspace_zero_fill + self._benchmark_module: Any | None = None + + @override + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + mod = PyCodeCache.load_by_key_path( + self.module_cache_key, + self.module_path, + set_sys_modules=False, + ) + self._benchmark_module = mod + autotuning_log.debug( + "benchmark module key: %s, path: %s", + self.module_cache_key, + self.module_path, + ) + + run_method = getattr(mod, self.kernel_name).run + extra_args = list(self.extra_args) + + # Recreate workspace tensor if needed (for TMA templates) + # The workspace tensor couldn't be pickled, so we recreate it here + # It should be inserted before the grid values (last 3 elements) + if self.workspace_size is not None: + from torch._inductor.select_algorithm import WORKSPACE_ARG_PLACEHOLDER + + workspace_tensor = torch.empty( + (self.workspace_size,), + dtype=torch.uint8, + device=out.device, + ) + if self.workspace_zero_fill: + workspace_tensor.zero_() + workspace_index = extra_args.index(WORKSPACE_ARG_PLACEHOLDER) + extra_args[workspace_index] = workspace_tensor + + run_method.__self__.with_bandwidth_info = False + + # Newer version of triton add warmup argument to JITFunction.run. + # This code handles backward-compatibility. + warmup_arg = {} + import inspect + + if "warmup" in inspect.signature(run_method).parameters: + warmup_arg["warmup"] = False + + if out.device.type == "cpu": + device_interface = None + device_index = 0 + else: + device_type = out.device.type + device_interface = get_interface_for_device(device_type) + device_index = self.output_tensor_meta.device.index + + is_debug_autotuner = isinstance( + getattr(mod, self.kernel_name), + torch._inductor.runtime.triton_heuristics.DebugAutotuner, + ) + + # Resolve the stream at call time (not at closure-creation time) so that + # CUDA graph capture on a different stream works correctly. + def run_fn() -> None: + stream = ( + 0 + if device_interface is None + else device_interface.get_raw_stream(device_index) + ) + if is_debug_autotuner: + run_method( + *input_tensors, + out, + *extra_args, + **warmup_arg, + stream=stream, + ) + else: + run_method( + *input_tensors, + out, + *extra_args, + **warmup_arg, + stream=stream, + benchmark_run=True, + ) + + return run_fn + + def cleanup_run_fn(self) -> None: + # Authoritative cleanup for one benchmark module load. Higher-level + # finally blocks may call this again as safety nets, so keep it idempotent. + mod = self._benchmark_module + self._benchmark_module = None + + cached_mod = PyCodeCache.modules_no_attr.pop(self.module_path, None) + if mod is None: + mod = cached_mod + + if mod is not None: + kernel = getattr(mod, self.kernel_name, None) + release_benchmark_artifacts = getattr( + kernel, "release_benchmark_artifacts", None + ) + if release_benchmark_artifacts is not None: + release_benchmark_artifacts() + release_static_launchers = getattr( + kernel, "_release_static_launchers_except", None + ) + if ( + release_benchmark_artifacts is None + and release_static_launchers is not None + ): + release_static_launchers(None) + elif release_benchmark_artifacts is None: + for launcher in getattr(kernel, "launchers", ()) or (): + close = getattr(getattr(launcher, "__self__", None), "close", None) + if close is not None: + close() + for compile_result in getattr(kernel, "compile_results", ()) or (): + close = getattr( + getattr(compile_result, "kernel", None), "close", None + ) + if close is not None: + close() + + PyCodeCache.modules[:] = [ + module + for module in PyCodeCache.modules + if getattr(module, "__file__", None) != self.module_path + ] + PyCodeCache.linemaps.pop(self.module_path, None) + + def precompile(self): + try: + mod = PyCodeCache.load_by_key_path( + self.module_cache_key, + self.module_path, + set_sys_modules=False, + ) + self._benchmark_module = mod + kernel = getattr(mod, self.kernel_name) + kernel.precompile() + + self.n_regs = kernel.launchers[0].n_regs + finally: + self.cleanup_run_fn() + + def __str__(self) -> str: + return f"{self.kernel_name=}, {self.module_path=}, {self.module_cache_key=}" + + +class TritonGPUBenchmarkRequest(GPUDeviceBenchmarkMixin, TritonBenchmarkRequest): + pass + + +class TritonCPUBenchmarkRequest(CPUDeviceBenchmarkMixin, TritonBenchmarkRequest): + pass + + +class ExternKernelBenchmarkRequest(BenchmarkRequest): + """ + A class to handle extern kernel benchmark requests. This allows extern kernels + (like aten::mm) to be benchmarked in a subprocess, similar to Triton kernels. + + 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], + callable_path: str, # Module path to the callable (e.g., "extern_kernels.mm") + kwargs: dict[str, Any] | None = None, + has_out_variant: bool = True, + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args) + self.callable_path = callable_path + self.kwargs = kwargs or {} + self.has_out_variant = has_out_variant + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + fn = self.to_callable() + if self.has_out_variant: + # For out=variant, pass output as keyword arg + return functools.partial(fn, *input_tensors, out=out) + else: + # For non-out variant, just call with inputs + return functools.partial(fn, *input_tensors) + + def benchmark(self, *input_tensors: torch.Tensor, out: torch.Tensor | None = None): + if out is not None and out.numel() == 0: + # no need to run the kernel or do benchmarking + return 0.0 + if self.has_out_variant or len(input_tensors) == 0: + return super().benchmark(*input_tensors, out=out) + else: + algo = self.to_callable() + out_new = algo(*input_tensors) + if out is not None: + torch._C._dynamo.guards.assert_size_stride( + out_new, tuple(out.size()), tuple(out.stride()) + ) + out.copy_(out_new) # for correctness checking + if self.benchmark_with_cudagraphs: + return benchmarker.benchmark_gpu_with_cuda_graph( + lambda: algo(*input_tensors) + ) + if config.profile_bandwidth_with_do_bench_using_profiling: + return do_bench_using_profiling(lambda: algo(*input_tensors)) + return benchmarker.benchmark(algo, input_tensors, {}) + + def precompile(self) -> None: + # Extern kernels don't need precompilation - they're already compiled + pass + + def to_callable(self): + # While ExternKernelChoice also has a to_callable method, + # we avoid calling the ExternKernelChoice version here to make sure + # this is picklable + from torch._inductor.select_algorithm import extern_kernels + + fn = getattr(extern_kernels, self.kernel_name) + if self.kwargs: + return functools.partial(fn, **self.kwargs) + + return fn + + def __str__(self) -> str: + return f"ExternKernelBenchmarkRequest({self.callable_path})" + + +class ExternKernelGPUBenchmarkRequest( + GPUDeviceBenchmarkMixin, ExternKernelBenchmarkRequest +): + pass + + +class ExternKernelCPUBenchmarkRequest( + CPUDeviceBenchmarkMixin, ExternKernelBenchmarkRequest +): + pass + + +class SubgraphBenchmarkRequest(BenchmarkRequest): + """ + Benchmark request for subgraph choices. + + Pre-compiles the subgraph in the main process and stores + the module path/cache key for loading in subprocess. + """ + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + extra_args: Iterable[Any], + module_path: str, + module_cache_key: str, + sym_input_values: list[int], + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args) + self.module_path = module_path + self.module_cache_key = module_cache_key + self.sym_input_values = sym_input_values + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + mod = PyCodeCache.load_by_key_path( + self.module_cache_key, + self.module_path, + set_sys_modules=False, + ) + sym_input_values = self.sym_input_values + # Create a new list each call since mod.call does args.clear() + return lambda: mod.call([*sym_input_values, *input_tensors]) + + def precompile(self) -> None: + # Module is already compiled in main process, no precompilation needed + pass + + def __str__(self) -> str: + return f"SubgraphBenchmarkRequest({self.kernel_name}, {self.module_path})" + + +class SubgraphGPUBenchmarkRequest(GPUDeviceBenchmarkMixin, SubgraphBenchmarkRequest): + pass + + +class SubgraphCPUBenchmarkRequest(CPUDeviceBenchmarkMixin, SubgraphBenchmarkRequest): + pass + + +class CUTLASSBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest): + """ + A class to handle CUDA (CUTLASS) benchmark requests. This class is for + managing the lifecycle of a CUDA kernel benchmark, including compiling + the source code, managing workspace memory, and executing the kernel. + + 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, + device_type: str = "cuda", + ) -> 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.device_type = device_type + self.codecache_cls = XPUCodeCache if device_type == "xpu" else CUDACodeCache + self.device_interface = get_interface_for_device(device_type) + self.hash_key, self.source_file = self.codecache_cls.write( + self.source_code, "so" + ) + + def precompile(self): + """ + Precompile the CUDA source code to populate the CUDACodeCache. + This may happen in a separate thread pool. + """ + autotuning_log.debug("Precompiling %s", self) + self.codecache_cls.compile(self.source_code, "so") + autotuning_log.debug("Done precompiling %s", self) + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + """ + Create a function to run the CUDA/XPU kernel with the given input and output tensors. + """ + + self.ensure_dll_loaded() + self.update_workspace_size() + args = [c_void_p(tensor.data_ptr()) for tensor in list(input_tensors) + [out]] + autotuning_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( + self.device_interface.get_raw_stream(self.device_interface.current_device()) + ) + 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. + ret = functools.partial( + run_method, + *args, + *self.extra_args, + None, # null workspace size ptr + workspace_ptr, # set workspace ptr, + stream_ptr, + ) + + # sanity check to make sure we cleanup run fn properly + try: + ret() + except RuntimeError as e: + err_msg = str(e) + + def raise_runtime_error(): + raise RuntimeError(err_msg) + + self.cleanup_run_fn() + return raise_runtime_error + + return ret + + 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( + self.device_interface.get_raw_stream(self.device_interface.current_device()) + ) + + run_method = getattr(self.DLL, self.kernel_name) + # Retrieve workspace_size and initialize workspace. + c_workspace_size = c_size_t() + run_method( + *args, # input ptrs and output ptrs + *self.extra_args, + byref( + c_workspace_size + ), # set workspace size ptr to retrieve workspace size + None, # null workspace ptr + stream_ptr, + ) + self.device_interface.synchronize() # shake out any device errors + self.workspace_size = c_workspace_size.value + autotuning_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 = self.codecache_cls.load( + self.source_code, "so" + ) + self.DLL.open() + + def cleanup_run_fn(self) -> None: + if self.DLL is not None: + self.DLL.close() + self.DLL = None + self.workspace = None + + def __str__(self) -> str: + return f"{self.kernel_name=}, {self.source_file=}, {self.hash_key=}" + + def __getstate__(self) -> dict[str, Any]: + state = self.__dict__.copy() + state["DLL"] = None + state["workspace"] = None + state["_workspace_size_updated"] = False + return state + + def __setstate__(self, state: dict[str, Any]) -> None: + self.__dict__.update(state) + + +class CppBenchmarkRequest(CPUDeviceBenchmarkMixin, BenchmarkRequest): + # Important: Instances of this class have to be serializable + # across process boundaries. Do not put 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.hash_key = get_hash(source_code) + self.DLL: CDLL | ModuleType | None = None + + def precompile(self): + # Prepopulate CppCodeCache + # may happen in separate Threadpool + autotuning_log.debug("Precompiling %s", self) + CppCodeCache.load(self.source_code, device_type="cpu") + autotuning_log.debug("Done precompiling %s", self) + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + # TODO(jgong5): use CppPythonBindingsCodeCache for better binding perf + self.DLL = CppCodeCache.load(self.source_code, device_type="cpu") + args = [tensor.data_ptr() for tensor in list(input_tensors) + [out]] + autotuning_log.debug( + "make_run_fn: self.kernel_name=%s, self.DLL=%s, args=%s, self.extra_args=%s", + self.kernel_name, + self.DLL, + args, + self.extra_args, + ) + run_method = getattr(self.DLL, self.kernel_name) + # Assume only size with type ctypes.c_ulonglong in extra_args + if not all(isinstance(arg, ctypes.c_ulonglong) for arg in self.extra_args): + raise AssertionError( + f"Expected all extra_args to be ctypes.c_ulonglong, got types: " + f"{[type(arg) for arg in self.extra_args if not isinstance(arg, ctypes.c_ulonglong)]}" + ) + run_method.argtypes = [ctypes.c_ulonglong] * ( + len(args) + len(list(self.extra_args)) + ) + + # Generate partial function. + return functools.partial( + run_method, + *args, + *self.extra_args, + ) + + def __str__(self) -> str: + return f"{self.kernel_name=}" + + +class CuteDSLBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest): + """Benchmark request for CuteDSL (CUTLASS Python DSL) kernels.""" + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + extra_args: tuple[Any, ...], + source_code: PartialRender, + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args) + + # Template-specific precompile hooks reuse the finalized module source in subprocesses. + self.source_code = source_code.finalize_all() + self.module_cache_key, self.module_path = PyCodeCache.write(self.source_code) + + def make_run_fn( + self, *input_tensors: torch.Tensor, out: torch.Tensor + ) -> Callable[[], None]: + """ + Create a function to run the CuteDSL kernel with the given input and output tensors. + Similar to TritonBenchmarkRequest.make_run_fn but for CuteDSL kernels. + """ + mod = PyCodeCache.load_by_key_path( + self.module_cache_key, + self.module_path, + set_sys_modules=False, + ) + + # Logic replicated async_compile + from .codegen.cutedsl.cutedsl_kernel import MAIN_SUFFIX + + main_func_name = f"{self.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 CuteDSL main kernel function '{main_func_name}'. Available callables: {available}" + ) + + kernel_func = getattr(mod, main_func_name) + + def run_kernel(): + device_interface = get_interface_for_device("cuda") + stream = device_interface.get_raw_stream(out.device.index) + return kernel_func(*input_tensors, out, *self.extra_args, stream=stream) + + return run_kernel + + +@functools.cache +def get_tuning_process_pool() -> TuningProcessPool: + pool = TuningProcessPool() + atexit.register(pool.shutdown) + return pool + + +def benchmark_in_sub_process( + choices: list[TritonTemplateCaller], +) -> dict[TritonTemplateCaller, float]: + """ + Do benchmarking in a subprocess and return the perf number (latency). + """ + return get_tuning_process_pool().benchmark(choices) + + +class AutotuneProcessPool: + """ + Singleton pool manager for running autotuning (precompilation + benchmarking) + in a separate process. + """ + + _instance: AutotuneProcessPool | None = None + _lock: threading.Lock = threading.Lock() + _shutdown_for_inactivity: bool = False + + def __init__(self): + self._pool: ProcessPoolExecutor | None = self._init_pool() + self._warmup_future: Future[Any] | None = None + self._warmup_start_time: float | None = None + self._timer: Timer | None = self._init_timer() + + @classmethod + def get_instance(cls): + """Get or create the singleton pool instance.""" + if cls._instance is None: + with cls._lock: + if cls._instance is None: + # num_workers=1 to avoid GPU contention during benchmarking + cls._instance = cls() + return cls._instance + + @property + def pool(self): + """Get the process pool.""" + if not config.pipeline_max_autotune_gemm: + raise AssertionError( + "To use AutotuneProcessPool, pipeline_max_autotune_gemm must be enabled" + ) + if self._pool is None: + self._pool = self._init_pool() + self._timer = self._init_timer() + return self._pool + + def _init_timer(self) -> Timer | None: + if AUTOTUNE_POOL_INACTIVITY_TIMEOUT > 0: + return Timer(AUTOTUNE_POOL_INACTIVITY_TIMEOUT, self._on_inactivity_timeout) + return None + + def _record_activity(self) -> None: + if self._timer is not None: + self._timer.record_call() + + def _on_inactivity_timeout(self) -> None: + autotuning_log.info( + "AutotuneProcessPool shutting down due to inactivity (timeout=%ds)", + AUTOTUNE_POOL_INACTIVITY_TIMEOUT, + ) + + with self._lock: + if self._pool is not None: + self._pool.shutdown(wait=False) + self._pool = None + self._timer = None + + # Mark that the pool was shut down for inactivity. + # This prevents the pool from being recreated on recompiles + # which likely do not require large amounts of autotuning. + AutotuneProcessPool._shutdown_for_inactivity = True + + def _init_pool(self): + """ + Get or create the process pool. + + Uses ProcessPoolExecutor with 'spawn' context for CUDA safety. + ProcessPoolExecutor is lazily initialized - workers are not spawned + until the first submit() call, making this property non-blocking. + """ + # Use 'spawn' context to avoid CUDA fork issues + # Workers are spawned lazily on first submit(), not here + ctx = mp.get_context("spawn") + pool = ProcessPoolExecutor( + max_workers=1, + mp_context=ctx, + ) + atexit.register(self._shutdown) + autotuning_log.info("AutotuneProcessPool created (workers spawn lazily)") + + return pool + + def warm_up(self) -> Future[Any]: + """ + Submit a warmup job to eagerly spawn workers and initialize CUDA. + + This is optional - call it early to hide spawn latency. + Returns the warmup future which can be ignored or awaited. + """ + if self._warmup_future is None: + with self._lock: + if self._warmup_future is None: + self._warmup_start_time = time.perf_counter() + self._warmup_future = self.submit( + _init_autotune_subprocess, + fp32_precision=torch.backends.cuda.matmul.fp32_precision, + ) + self._warmup_future.add_done_callback(self._on_warmup_complete) + autotuning_log.info("Warmup job submitted") + # pyrefly: ignore[bad-return] + return self._warmup_future + + def _on_warmup_complete(self, future: Future[Any]) -> None: + """Callback invoked when the warmup job completes.""" + warmup_elapsed_time = None + if self._warmup_start_time is not None: + warmup_elapsed_time = time.perf_counter() - self._warmup_start_time + + try: + result = future.result() + autotuning_log.info( + "AutotuneProcessPool warmup completed successfully in %.4f seconds: %s", + warmup_elapsed_time, + result, + ) + self._record_activity() + except Exception as e: + autotuning_log.error( + "AutotuneProcessPool warmup failed after %.4f seconds", + warmup_elapsed_time, + ) + raise e + + def submit(self, fn, *args, **kwargs) -> Future[Any]: + """Submit a job to the pool and return a Future.""" + future = self.pool.submit( + _run_with_subprocess_env, + fn, + _cache_env_for_subprocess(), + *args, + **kwargs, + ) + if self._timer is not None: + future.add_done_callback(lambda _: self._record_activity()) + return future + + def _shutdown(self): + """Shutdown the pool on exit.""" + if self._timer is not None: + self._timer.quit() + self._timer = None + if self._pool is not None: + self._pool.shutdown(wait=False) + self._pool = None + + @classmethod + def shutdown_instance(cls): + """Explicitly shutdown the singleton instance.""" + if cls._instance is not None: + with cls._lock: + if cls._instance is not None: + cls._instance._shutdown() + cls._instance = None + + +def use_pipelined_autotuning() -> bool: + return ( + config.pipeline_max_autotune_gemm + and not AutotuneProcessPool._shutdown_for_inactivity + ) + + +def _init_autotune_subprocess(fp32_precision: str) -> bool: + """ + Warmup function run in the autotune subprocess. + """ + import torch + + # Initialize dummy tensor for CUDA context + if torch.cuda.is_available(): + torch.zeros(1, device="cuda") + + torch.backends.cuda.matmul.fp32_precision = fp32_precision + + return True + + +def run_autotune_in_subprocess( + benchmark_request: BenchmarkRequest, +) -> float: + """ + Run autotuning benchmarks in a subprocess. + + This function is submitted to AutotuneProcessPool and runs in isolation + to prevent GPU contention with the main compilation process. + + Args: + picklable_choices: List of picklable choice information + + Returns: + timing + """ + + try: + # Run the benchmark directly - bmreq is already a BenchmarkRequest + timing = benchmark_request.benchmark() + + return timing + + except Exception: + autotuning_log.warning( + "Failed to benchmark choice %s", + benchmark_request, + exc_info=True, + ) + # Use infinity for failed benchmarks so they're not selected + return float("inf") + + +class PrecompileThreadPool: + """ + Thread pool for running precompilation asynchronously. + + This allows the main compilation process to continue while + precompilation happens in background threads. + """ + + _instance: PrecompileThreadPool | None = None + _lock = threading.Lock() + + def __init__(self, max_workers: int = 4): + self._executor = ThreadPoolExecutor(max_workers=max_workers) + + @classmethod + def get_instance(cls) -> PrecompileThreadPool: + from torch._inductor.select_algorithm import get_num_workers + + if cls._instance is None: + with cls._lock: + if cls._instance is None: + cls._instance = cls(get_num_workers()) + return cls._instance + + def submit(self, fn, *args, **kwargs): + ctx = contextvars.copy_context() + # Need to copy context so workers have access to the correct config settings + fn = functools.partial(ctx.run, fn) + return self._executor.submit(fn, *args, **kwargs) + + def _shutdown(self, wait: bool = False): + return self._executor.shutdown(wait=wait) + + @classmethod + def shutdown_instance(cls) -> None: + if cls._instance is not None: + with cls._lock: + if cls._instance is not None: + cls._instance._shutdown(wait=False) + cls._instance = None + + +class AsyncAutotuner: + """ + Handles asynchronous autotuning of kernel choices in a separate process. + + This class manages the lifecycle of autotuning: + 1. Accepts precompiled choices from the main process + 2. Submits benchmarking work to AutotuneProcessPool + 3. Returns results via a Future + + Usage: + autotuner = AsyncAutotuner(choices) + autotuner.start() # Kicks off async benchmarking + timings = autotuner.get_results() # Blocks until complete + """ + + choice_hash_to_future = {} + + @staticmethod + def get_choice_hash(choice: ChoiceCaller, inputs_key: str) -> str: + return choice.hash_key() + inputs_key + + @classmethod + def start(cls, choices: list[ChoiceCaller], inputs_key: str): + """ + Start asynchronous autotuning in a subprocess. + + This method: + 1. Extracts picklable benchmark requests from choices + 2. Submits benchmarking work to AutotuneProcessPool + 3. Returns immediately (non-blocking) + """ + + for choice in choices: + choice_hash = AsyncAutotuner.get_choice_hash(choice, inputs_key) + + if choice_hash in AsyncAutotuner.choice_hash_to_future: + continue + + if not getattr(choice, "bmreq", None) is not None: + raise AssertionError("bmreq is None for choice") + + autotune_future = AutotuneProcessPool.get_instance().submit( + run_autotune_in_subprocess, + choice.bmreq, + ) + + AsyncAutotuner.choice_hash_to_future[choice_hash] = autotune_future + + @classmethod + def get_results( + cls, choices: list[ChoiceCaller], inputs_key: str + ) -> dict[ChoiceCaller, float]: + """ + Get autotuning results, blocking until complete. + + Args: + timeout: Maximum time to wait in seconds. None means wait forever. + + Returns: + Dict mapping ChoiceCaller to benchmark timing + """ + + timings = {} + for choice in choices: + choice_hash = AsyncAutotuner.get_choice_hash(choice, inputs_key) + timings[choice] = AsyncAutotuner.choice_hash_to_future[choice_hash].result() + return timings diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/autows_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/autows_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7b5fec2ee801e5034347194feeaea675a7e5c419 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/autows_utils.py @@ -0,0 +1,24 @@ +"""Utils for Meta Triton autoWS.""" + +from __future__ import annotations + +import functools + + +@functools.cache +def has_meta_ws() -> bool: + """Whether Meta Triton autoWS is available.""" + try: + from triton import knobs + except ImportError: + return False + return hasattr(getattr(knobs, "nvidia", None), "use_meta_ws") + + +def meta_ws_enabled() -> bool: + """Whether Meta Triton autoWS is available and enabled via its knob.""" + if not has_meta_ws(): + return False + from triton import knobs + + return bool(knobs.nvidia.use_meta_ws) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/await_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/await_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fcb4549066eddb64b80947179bbf4016cbfa483a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/await_utils.py @@ -0,0 +1,178 @@ +import asyncio +import sys +import weakref +from asyncio import AbstractEventLoop, Future +from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterator +from contextlib import contextmanager, ExitStack +from contextvars import Context +from typing import Any, Protocol, TypeVar + +from torch.utils._ordered_set import OrderedSet + + +T = TypeVar("T") +TCoro = Generator[Any, None, T] + +if sys.version_info >= (3, 11): + + class TaskFactory(Protocol): + def __call__( + self, + __loop: AbstractEventLoop, + __factory: Coroutine[None, None, object] | Generator[None, None, object], + __context: Context | None = None, + /, + ) -> asyncio.futures.Future[object]: ... + + TaskFactoryType = TaskFactory +else: + TaskFactoryType = Callable[[AbstractEventLoop, Generator[TCoro, None, T]], Future] # type: ignore[valid-type] + + +def await_sync(awaitable: Awaitable[T]) -> T: + with get_loop() as loop: + return loop.run_until_complete(awaitable) + + +@contextmanager +def get_loop( + always_create_new_loop: bool = False, +) -> Iterator[AbstractEventLoop]: + try: + loop = asyncio.get_event_loop() + except RuntimeError as re: + if "There is no current event loop in thread" in str(re): + with _new_loop() as loop: + yield loop + return + else: + raise + + @contextmanager + def _restore_loop( + loop: asyncio.AbstractEventLoop, + ) -> Iterator[None]: + try: + yield + finally: + asyncio.set_event_loop(loop) + + @contextmanager + def _restore_running_loop() -> Iterator[None]: + loop_from_events = asyncio.events._get_running_loop() + asyncio.events._set_running_loop(None) + try: + yield + finally: + asyncio.events._set_running_loop(loop_from_events) + + with ExitStack() as stack: + if loop.is_running(): + stack.enter_context(_restore_running_loop()) + stack.enter_context(_restore_loop(loop=loop)) + loop = stack.enter_context(_new_loop(loop.get_task_factory())) # type: ignore[arg-type] + elif loop.is_closed(): + loop = stack.enter_context(_new_loop()) # type: ignore[arg-type] + elif always_create_new_loop: + stack.enter_context(_restore_loop(loop=loop)) + loop = stack.enter_context(_new_loop()) # type: ignore[arg-type] + yield loop + + +@contextmanager +def _new_loop( + task_factory: TaskFactoryType | None = None, +) -> Iterator[asyncio.AbstractEventLoop]: + loop = asyncio.new_event_loop() + tasks = _patch_loop(loop) + + if task_factory: + # pyre-ignore[6] + loop.set_task_factory(task_factory) # type: ignore[arg-type] + + asyncio.set_event_loop(loop) + try: + yield loop + finally: + try: + _cancel_all_tasks(loop, tasks) + finally: + asyncio.set_event_loop(None) + loop.close() + + +def _cancel_all_tasks( + loop: AbstractEventLoop, + tasks: OrderedSet[Future], # type: ignore[type-arg] +) -> None: + to_cancel = [task for task in tasks if not task.done()] + + if not to_cancel: + return + + # pyre-fixme[1001]: Awaitable assigned to `task` is never awaited. + for task in to_cancel: + task.cancel() + + # pyrefly: ignore [bad-argument-type] + loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True)) + + for task in to_cancel: + if task.cancelled(): + continue + if task.exception() is not None: + loop.call_exception_handler( + { + "message": "unhandled exception during asyncio.run() shutdown", + "exception": task.exception(), + "task": task, + } + ) + + +def _patch_loop(loop: AbstractEventLoop) -> OrderedSet[Future]: # type: ignore[type-arg] + tasks: weakref.WeakSet[Future] = weakref.WeakSet() # type: ignore[type-arg] + + task_factories: list[TaskFactoryType | None] = [None] + + def _set_task_factory(factory: TaskFactoryType | None) -> None: + task_factories[0] = factory + + def _get_task_factory() -> TaskFactoryType | None: + return task_factories[0] + + def _safe_task_factory( + loop: AbstractEventLoop, + coro: TCoro, # type: ignore[type-arg] + *, + context: Context | None = None, + ) -> asyncio.Future: # type: ignore[valid-type, type-arg] + task_factory = task_factories[0] + if task_factory is None: + if sys.version_info >= (3, 11): + # pyrefly: ignore [bad-argument-type] + task = asyncio.Task(coro, loop=loop, context=context) + else: + task = asyncio.Task(coro, loop=loop) + # pyre-ignore[16]: `Task` has no attribute `_source_traceback`. + if task._source_traceback: # type: ignore[attr-defined] + del task._source_traceback[ # type: ignore[attr-defined] + -1 + ] # pragma: no cover # type: ignore[attr-defined] + else: + if sys.version_info >= (3, 11): + task = task_factory(loop, coro, context=context) # type: ignore[arg-type, call-arg, assignment] + else: + task = task_factory(loop, coro) # type: ignore[arg-type] + # `Union[Task[Any], Future[Any]]`. + tasks.add(task) + return task + + # pyre-ignore[6] + loop.set_task_factory(_safe_task_factory) # type: ignore[method-assign, arg-type] + # pyre-ignore[8] + loop.set_task_factory = _set_task_factory # type: ignore[method-assign, assignment] + # pyre-ignore[8] + loop.get_task_factory = _get_task_factory # type: ignore[method-assign, assignment] + + return tasks # type: ignore[return-value] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/bounds.py b/.venv/lib/python3.12/site-packages/torch/_inductor/bounds.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c7e36d2c422ec5f3630b6b0f056934bd0c5010 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/bounds.py @@ -0,0 +1,273 @@ +import logging +import operator +from collections.abc import Callable +from functools import partial +from typing import Any + +import sympy +from sympy import Expr + +import torch +from torch.utils._sympy.value_ranges import ( + bound_sympy, + SymPyValueRangeAnalysis, + ValueRanges, +) + +from ..utils._sympy.functions import PowByNatural +from ..utils._sympy.numbers import int_oo +from .loop_body import InterpreterShim, LoopBody, LoopBodyBlock +from .ops_handler import DefaultHandler, ReductionType, StoreMode +from .utils import cache_on_self, dominated_nodes +from .virtualized import V + + +log = logging.getLogger(__name__) + + +class BoundVars: + """ + Performs Value Range Analysis on LoopBody's fx graph by calling BoundVars.run() + It exposes the ranges of the nodes in the `bounds` variable + + Note. A current limitation of this analysis is that it just works on a per-loop basis. + We should be able to propagate the bounds between across the whole graph. This may benefit + the case a bounded variable is returned by a kernel and fed into another. + """ + + def __init__(self, loop_body: LoopBody) -> None: + def upper_bound(v: Expr | int) -> int: + return bound_sympy(v).upper if isinstance(v, Expr) else v + + self.loop_body = loop_body + self.replacement_vals = { + k: ValueRanges[Expr](0, upper_bound(v) - 1) + for k, v in loop_body.var_ranges.items() + } + # avoid computing these values, pessimistically assume that they are unbounded + self.unbounded_vars = dominated_nodes( + node + for node in self.loop_body.get_nodes() + if node.target in ["load", "reduction", operator.getitem] + or "masked_subblock" in node.target + ) + # To access this variable call `get_bounds()` + self._bounds: dict[torch.fx.Node, ValueRanges[Expr]] = {} + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(" + f"loop_body={self.loop_body},\n " + f"replacement_vals={self.replacement_vals}, \n" + f"unbounded_vars={self.unbounded_vars}, \n" + f"_bounds={self._bounds})" + ) + + @cache_on_self + def get_bounds(self) -> dict[torch.fx.Node, ValueRanges[Expr]]: + submodules = self.swap_submodules(self.loop_body.submodules) + + # Initialize the environment with the unbounded variables + for node in self.unbounded_vars: + # we need to evaluate masked_subblock to recurse, and we need to set indirect values + if not isinstance(node.target, str) or ( + "masked_subblock" not in node.target + and "set_indirect" not in node.target + ): + self._bounds[node] = ValueRanges[Expr].unknown() + + with V.set_ops_handler(ValueRangeAnalysis()): + interpreter = InterpreterShim(self.loop_body.root_block.graph, submodules) + log.debug("get_bounds:\n%s", self.loop_body.root_block.graph) + interpreter.run(V.get_ops_handler(), initial_env=self._bounds) + return self._bounds + + def swap_submodules( + self, submodules: dict[str, Callable[..., Any]] + ) -> dict[str, Callable[..., ValueRanges[Expr]]]: + result: dict[str, Callable[..., ValueRanges[Expr]]] = {} + for key in submodules: + if key == "get_index": + result[key] = self.get_index + elif "masked_subblock" in key: + subblock = self.loop_body.subblocks[key] + # The result within the lambda will reference to the final + # set of modules at the end of the for-loop as it stores a reference to it + + # bind subblock in a function because python lambdas close over by reference + # moving the lambda out of make_fn would close over the reference to subblock, + # so all lambdas would have the same subblock reference that is the final + # subblock in the loop + def make_fn( + subblock: LoopBodyBlock, + ) -> Callable[[Any, Any], ValueRanges[Expr]]: + return lambda mask, value: self.masked_subblock( + subblock, self._bounds, mask, value, result + ) + + result[key] = make_fn(subblock) + elif "set_indirect" in key: + idx = int(key[len("set_indirect") :]) + var = self.loop_body.indirect_vars[idx] + indirect = partial(self.set_indirect, var) + result[key] = indirect + else: + if "scan" not in key: + raise AssertionError( + f"expected 'scan' in submodule key, got {key!r}" + ) + result[key] = submodules[key] + + return result + + def masked_subblock( + self, + subblock: LoopBodyBlock, + env: dict[torch.fx.Node, ValueRanges[Expr]], + mask: Any, + value: Any, + submodules: dict[str, Callable[..., Any]], + ) -> ValueRanges[Expr]: + interp = InterpreterShim(subblock.graph, submodules) + interp.run(V.get_ops_handler(), initial_env=env) + output = [node for node in subblock.graph.nodes if node.target == "output"] + if len(output) != 1: + raise AssertionError(f"expected exactly 1 output node, got {len(output)}") + # don't bother unioning with value since the load from buffer will be + # pessimistically assumed to be inf anyway + return interp.env[output[0]] + + def set_indirect(self, old: Expr, new: ValueRanges[Expr]) -> ValueRanges[Expr]: + if not isinstance(new, ValueRanges): + raise AssertionError(f"expected ValueRanges, got {type(new)}") + self.replacement_vals[old] = new + return new + + def get_index(self, name: str) -> ValueRanges[Expr]: + expr = self.loop_body.indexing_exprs[name] + bound = self.replacement_vals.get(expr) + if bound is None: + bound = bound_sympy(expr, self.replacement_vals) + # The following assertion is true at the time of this writing + # We don't assert is as to not execute bound_sympy when bound is not None + # assert bound is None or bound == bound_sympy(expr, self.replacement_vals) + self.replacement_vals[name] = bound + return bound + + +class ValueRangeAnalysis(SymPyValueRangeAnalysis, DefaultHandler): + def __init__(self) -> None: + self.name = "ValueRangeAnalysis" + boolean_operators = ( + "xor", + "logical_and", + "logical_or", + "logical_not", + ) + for op in boolean_operators: + setattr(self, op, self.bool_handler) + + @staticmethod + def bool_handler(*args: Any, **kwargs: Any) -> ValueRanges[Any]: + # just assuming bools can have both values + return ValueRanges(sympy.false, sympy.true) # type: ignore[arg-type] + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + # many ops are unlikely to show up in optimizable indexing compute, + # so we don't have full coverage + return ValueRanges.unknown() + + def load(self, name: str, index: sympy.Expr) -> ValueRanges[Any]: + return ValueRanges.unknown() + + def store( + self, name: str, index: sympy.Expr, value: Any, mode: StoreMode = None + ) -> None: + return + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: Any, + ) -> ValueRanges[Any]: + return ValueRanges.unknown() + + @classmethod + def index_expr(cls, index: Any, dtype: torch.dtype) -> ValueRanges[Any]: + if not isinstance(index, ValueRanges): + raise AssertionError(f"expected ValueRanges, got {type(index)}") + return cls.to_dtype(index, dtype) + + @classmethod + def value_expr(cls, index: Any, dtype: torch.dtype) -> ValueRanges[Any]: + return cls.index_expr(index, dtype) + + @staticmethod + # pyrefly: ignore [bad-override] + def to_dtype( + x: Any, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types: bool = True, + ) -> ValueRanges[Any]: + x = ValueRanges.wrap(x) + + if dtype == torch.bool: + if x.is_singleton(): + return ValueRanges.wrap(x.lower != 0) + elif x.is_bool: + return x + elif 0 not in x: + return ValueRanges.wrap(sympy.true) + else: + return ValueRanges(sympy.false, sympy.true) + + def cast(x: Any, dtype: torch.dtype) -> sympy.Expr: + # dtype is int or float + if dtype.is_floating_point: + return sympy.Float(x) + else: + if x in (int_oo, -int_oo): + return x + try: + return sympy.Integer(x) + except TypeError: + # inf cannot be cast to Integer + return x + + if x.is_bool: + if x.is_singleton(): + val = 1 if x.lower else 0 + return ValueRanges.wrap(cast(val, dtype)) + else: + return ValueRanges(cast(0, dtype), cast(1, dtype)) + else: + # int to float or float to int + return ValueRanges(cast(x.lower, dtype), cast(x.upper, dtype)) + + @staticmethod + # pyrefly: ignore [bad-override] + def square(x: Any) -> ValueRanges[Any]: + return ValueRanges.convex_min_zero_map(x, lambda y: PowByNatural(y, 2)) + + @staticmethod + # pyrefly: ignore [bad-override] + def neg(x: Any) -> ValueRanges[Any]: + return ValueRanges.decreasing_map(x, operator.neg) + + # TODO: this is slightly inaccurate because truncdiv operates at integer + # precision, but we're going through float truediv which means we can + # potentially lose precision on the bounds + @classmethod + def truncdiv(cls, a: Any, b: Any) -> ValueRanges[Any]: + x = cls.truediv(a, b) + if x == ValueRanges.unknown(): + return x + + return cls.trunc(x) + + @classmethod + def sub(cls, a: Any, b: Any) -> ValueRanges[Any]: + return cls.add(a, cls.neg(b)) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/cache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..118bbf2828799d8fd63a96427b5e88573d6adf19 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/cache.py @@ -0,0 +1,419 @@ +from __future__ import annotations + +import pickle +from abc import ABC, abstractmethod +from ast import literal_eval +from functools import cached_property +from hashlib import sha256 +from os import getenv +from pathlib import Path +from tempfile import gettempdir +from threading import Lock +from typing import Any, Generic, TYPE_CHECKING, TypeVar +from typing_extensions import assert_never, override, Self + +from torch.utils._filelock import FileLock + + +if TYPE_CHECKING: + from concurrent.futures import Future, ThreadPoolExecutor + + +# TypeVars can't be recursive, so generic types that fall within +# Key or Value can't be bound properly; for example, Key should +# only take tuples of other Key types: tuple[Key, ...]. this is +# a known shortcoming of torch's typing +Key = TypeVar("Key", str, int, tuple[Any, ...]) +Value = TypeVar("Value", str, int, tuple[Any, ...], bytes, dict[Any, Any], list[Any]) + + +class CacheError(ValueError): + """ + Exception raised for errors encountered during cache operations. + """ + + +class Cache(ABC, Generic[Key, Value]): + """ + Abstract base class for cache implementations. + Provides the interface for cache operations. + """ + + @abstractmethod + def get(self: Self, key: Key) -> Value | None: + """ + Retrieve a value from the cache. + Args: + key (Key): The key to look up. + Returns: + Value | None: The cached value if present, else None. + """ + + @abstractmethod + def insert(self: Self, key: Key, value: Value) -> bool: + """ + Insert a value into the cache. + Args: + key (Key): The key to insert. + value (Value): The value to associate with the key. + Returns: + bool: True if the value was inserted, False if the key already exists. + """ + + +class InMemoryCache(Cache[Key, Value]): + """ + In-memory cache implementation using a dictionary and thread lock. + """ + + def __init__(self: Self) -> None: + """ + Initialize an empty in-memory cache. + """ + self._cache: dict[Key, Value] = {} + self._lock: Lock = Lock() + + def get(self: Self, key: Key) -> Value | None: + """ + Retrieve a value from the cache. + Args: + key (Key): The key to look up. + Returns: + Value | None: The cached value if present, else None. + """ + with self._lock: + if (value := self._cache.get(key)) is not None: + return value + return None + + def insert(self: Self, key: Key, value: Value) -> bool: + """ + Insert a value into the cache. + Args: + key (Key): The key to insert. + value (Value): The value to associate with the key. + Returns: + bool: True if the value was inserted, False if the key already exists. + """ + with self._lock: + if key in self._cache: + # no overwrites for insert! + return False + self._cache[key] = value + return True + + @classmethod + def from_env_var(cls, env_var: str) -> Self: + """ + Create an in-memory cache from an environment variable. + Args: + env_var (str): Name of the environment variable containing cache data. + Returns: + InMemoryCache: An instance populated from the environment variable. + Raises: + CacheError: If the environment variable is malformed or contains invalid data. + """ + cache = cls() + + if (env_val := getenv(env_var)) is None: + # env_var doesn't exist = empty cache + return cache + + for kv_pair in env_val.split(";"): + # ignore whitespace prefix/suffix + kv_pair = kv_pair.strip() + + if not kv_pair: + # kv_pair could be '' if env_val is '' or has ; suffix + continue + + try: + # keys and values should be comma separated + key_bytes_repr, value_bytes_repr = kv_pair.split(",", 1) + except ValueError as err: + raise CacheError( + f"Malformed kv_pair {kv_pair!r} from env_var {env_var!r}, likely missing comma separator." + ) from err + + # ignore whitespace prefix/suffix, again + key_bytes_repr, value_bytes_repr = ( + key_bytes_repr.strip(), + value_bytes_repr.strip(), + ) + + try: + # check that key_bytes_str is an actual, legitimate encoding + key_bytes = literal_eval(key_bytes_repr) + except (ValueError, SyntaxError) as err: + raise CacheError( + f"Malformed key_bytes_repr {key_bytes_repr!r} in kv_pair {kv_pair!r}, encoding is invalid." + ) from err + try: + # check that value_bytes_str is an actual, legitimate encoding + value_bytes = literal_eval(value_bytes_repr) + except (ValueError, SyntaxError) as err: + raise CacheError( + f"Malformed value_bytes_repr {value_bytes_repr!r} in kv_pair {kv_pair!r}, encoding is invalid." + ) from err + + try: + key = pickle.loads(key_bytes) + except pickle.UnpicklingError as err: + raise CacheError( + f"Malformed key_bytes_repr {key_bytes_repr!r} in kv_pair {kv_pair!r}, not un-pickle-able." + ) from err + try: + value = pickle.loads(value_bytes) + except pickle.UnpicklingError as err: + raise CacheError( + f"Malformed value_bytes_repr {value_bytes_repr!r} in kv_pair {kv_pair!r}, not un-pickle-able." + ) from err + + # true duplicates, i.e. multiple occurrences of the same key => value + # mapping are ok and treated as a no-op; key duplicates with differing + # values, i.e. key => value_1 and key => value_2 where value_1 != value_2, + # are not okay since we don't allow overwriting cached values (it's bad regardless) + if (not cache.insert(key, value)) and (cache.get(key) != value): + raise CacheError( + f"Multiple values for key {key!r} found, got {cache.get(key)!r} and {value!r}." + ) + + return cache + + @classmethod + def from_file_path(cls, fpath: Path) -> Self: + """ + Create an in-memory cache from a file path. + Args: + fpath (Path): Path to the file containing pickled cache data. + Returns: + InMemoryCache: An instance populated from the file. + Raises: + CacheError: If the file is not a valid pickled dictionary. + """ + cache = cls() + + if not fpath.is_file(): + # fpath doesn't exit = empty cache + return cache + + try: + with open(fpath, "rb") as fp: + cache._cache = pickle.load(fp) + except pickle.UnpicklingError as err: + raise CacheError( + f"Failed to create cache from file path {fpath}, file contents are un-pickle-able." + ) from err + + if not isinstance(cache._cache, dict): + raise CacheError( + f"Failed to create cache from file path {fpath}, file contents not pickled dict[Key, Value]." + ) + + return cache + + +class AsyncCache(Cache[Key, Value]): + """ + Asynchronous cache implementation using ThreadPoolExecutor. + """ + + def get_async( + self: Self, key: Key, executor: ThreadPoolExecutor + ) -> Future[Value | None]: + """ + Retrieve a value from the cache asynchronously. + Args: + key (Key): The key to look up. + executor (ThreadPoolExecutor): Executor for async execution. + Returns: + Future[Value | None]: Future for the cached value or None. + """ + return executor.submit(self.get, key) + + def insert_async( + self: Self, key: Key, value: Value, executor: ThreadPoolExecutor + ) -> Future[bool]: + """ + Insert a value into the cache asynchronously. + Args: + key (Key): The key to insert. + value (Value): The value to associate with the key. + executor (ThreadPoolExecutor): Executor for async execution. + Returns: + Future[bool]: Future for the result of insertion. + """ + return executor.submit(self.insert, key, value) + + +class OnDiskCache(AsyncCache[Key, Value]): + """ + On-disk cache implementation using files and file locks. + Stores cache data in files on disk, with atomic operations and versioning. + Supports custom cache directory names. + Attributes: + version (int): The version used for cache versioning. + name (str): The name of the cache directory. + """ + + version: int = 0 + + def __init__(self: Self, name: str | None = None) -> None: + """ + Initialize an on-disk cache instance. + Args: + name (str | None, optional): The name of the cache directory. If None, + defaults to "on_disk_cache". + """ + self.name = name or "on_disk_cache" + + @cached_property + def base_dir(self: Self) -> Path: + """ + Get the base directory for the cache. + Returns: + Path: The base directory path for storing cache files. + """ + return Path(gettempdir()) / "cache" / self.name + + def _fpath_from_key(self: Self, key: Key) -> Path: + """ + Get the file path for a given key. + Args: + key (Key): The key to convert to a file path. + Returns: + Path: The file path for the key. + Raises: + CacheError: If the key is not pickle-able. + """ + try: + return self.base_dir / sha256(pickle.dumps(key)).hexdigest()[:32] + except (AttributeError, pickle.PicklingError) as err: + raise CacheError( + f"Failed to get fpath for key {key!r}, key is not pickle-able." + ) from err + # pyrefly: ignore [bad-argument-type] + assert_never(key) + + def _flock_from_fpath(self: Self, fpath: Path) -> FileLock: + """ + Get a file lock for a given file path. + Args: + fpath (Path): The file path. + Returns: + FileLock: The file lock for the path. + """ + # fpath.name is a hex digest, meaning there are 16^4 potential values + # for fpath.name[:4]; this is more than enough unique locks to not + # cause additional overhead from shared locks and it also saves our + # cache dir from becoming 50 percent locks + # pyrefly: ignore [bad-return] + return FileLock(str(fpath.parent / "locks" / fpath.name[:4]) + ".lock") + + @property + def version_prefix(self: Self) -> bytes: + """ + Get the version prefix for the cache. + Returns: + bytes: The version prefix as bytes, derived from the cache version string. + """ + return sha256(str(OnDiskCache.version).encode()).digest()[:4] + + @override + def get(self: Self, key: Key) -> Value | None: + """ + Retrieve a value from the cache. + Args: + key (Key): The key to look up. + Returns: + Value | None: The cached value if present and version matches, else None. + Raises: + CacheError: If the value is corrupted or cannot be unpickled. + Side Effects: + Removes stale cache files if the version prefix does not match. + """ + fpath = self._fpath_from_key(key) + flock = self._flock_from_fpath(fpath) + + with flock: + if not fpath.is_file(): + return None + + value_bytes = None + prefix_length = len(self.version_prefix) + with open(fpath, "rb") as fp: + if fp.read(prefix_length) == self.version_prefix: + value_bytes = fp.read() + + if value_bytes is None: + # version_prefix did not match, so we can't read the stale + # cached value; we should also remove the stale cached value, + # so that key can be re-cached by the newer version + fpath.unlink() + return None + + try: + value = pickle.loads(value_bytes) + except pickle.UnpicklingError as err: + raise CacheError( + f"Failed to get key {key!r}, value is potentially corrupted (value is not un-pickle-able)." + ) from err + + return value + + @override + def insert(self: Self, key: Key, value: Value) -> bool: + """ + Insert a value into the cache. + Args: + key (Key): The key to insert. + value (Value): The value to associate with the key. + Returns: + bool: True if the value was inserted, False if the key already exists. + Raises: + CacheError: If the value is not pickle-able. + Side Effects: + Creates the cache directory if it does not exist. + """ + fpath = self._fpath_from_key(key) + flock = self._flock_from_fpath(fpath) + fpath.parent.mkdir(parents=True, exist_ok=True) + try: + # "x" mode is exclusive creation, meaning the file will be created + # iff the file does not already exist (atomic w/o overwrite); use + # flock for added atomicity guarantee and to prevent partial writes + with flock as _, open(fpath, "xb") as fp: + fp.write(self.version_prefix) + pickle.dump(value, fp) + except pickle.PicklingError as err: + raise CacheError( + f"Failed to insert key {key!r} with value {value!r}, value is not pickle-able." + ) from err + except FileExistsError: + return False + return True + + +class InductorOnDiskCache(OnDiskCache[Key, Value]): + """ + Inductor-specific on-disk cache implementation. + Uses a custom base directory for Inductor cache files. + """ + + def __init__(self: Self) -> None: + """ + Initialize an inductor on-disk cache instance. + Sets the cache directory name to "inductor_on_disk_cache". + """ + super().__init__("inductor_on_disk_cache") + + @cached_property + def base_dir(self: Self) -> Path: + """ + Get the base directory for the Inductor cache. + Returns: + Path: The base directory path for Inductor cache files. + """ + from torch._inductor.runtime.runtime_utils import default_cache_dir + + return Path(default_cache_dir(), "cache", self.name) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/cache_key.py b/.venv/lib/python3.12/site-packages/torch/_inductor/cache_key.py new file mode 100644 index 0000000000000000000000000000000000000000..cfef4170a15b4557afaef0f1298bae1098e9f82c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/cache_key.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import base64 +import dataclasses +import hashlib +import json +from typing import Any, Literal, Protocol +from typing_extensions import assert_never + + +CacheKeyComponent = str | bytes | bytearray | memoryview + + +class _HashLike(Protocol): + def update(self, data: bytes, /) -> None: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + + +@dataclasses.dataclass(frozen=True) +class CacheKeyStrategy: + """ + Describes how an Inductor cache turns stable components into a cache key. + + Different caches intentionally use different key formats for compatibility + with existing on-disk and remote cache layouts. Keeping those choices in + named strategies makes the composition explicit at the call site. + """ + + # Human-readable label for repr/debugging; it is not part of the cache key. + name: str + digest_format: Literal["base32", "hex"] + prefix: str = "" + separator: bytes | None = None + base32_length: int = 51 + + @staticmethod + def _to_bytes(component: CacheKeyComponent) -> bytes: + if isinstance(component, str): + return component.encode("utf-8") + if isinstance(component, bytes): + return component + if isinstance(component, bytearray): + return bytes(component) + if isinstance(component, memoryview): + return component.tobytes() + raise TypeError(f"Unsupported cache key component: {type(component)!r}") + + def _hasher(self, components: tuple[CacheKeyComponent, ...]) -> _HashLike: + hasher = hashlib.sha256() + for idx, component in enumerate(components): + if idx > 0 and self.separator is not None: + hasher.update(self.separator) + hasher.update(self._to_bytes(component)) + return hasher + + def digest(self, *components: CacheKeyComponent) -> str: + hasher = self._hasher(components) + if self.digest_format == "hex": + return hasher.hexdigest() + if self.digest_format == "base32": + # [:51] strips the "Q====" suffix common to every SHA256 base32 digest. + return ( + base64.b32encode(hasher.digest())[: self.base32_length] + .decode("utf-8") + .lower() + ) + assert_never(self.digest_format) + + def key(self, *components: CacheKeyComponent) -> str: + return f"{self.prefix}{self.digest(*components)}" + + def key_from_json(self, value: Any, *, sort_keys: bool = True) -> str: + return self.key(json.dumps(value, sort_keys=sort_keys)) + + +COMPACT_CACHE_KEY_STRATEGY = CacheKeyStrategy( + name="compact", + digest_format="base32", +) + +CODE_CACHE_KEY_STRATEGY = CacheKeyStrategy( + name="code", + digest_format="base32", + prefix="c", + separator=b"||", +) + +FX_GRAPH_CACHE_KEY_STRATEGY = CacheKeyStrategy( + name="fx_graph", + digest_format="base32", + prefix="f", +) + +SYSTEM_CACHE_KEY_STRATEGY = CacheKeyStrategy( + name="system", + digest_format="hex", +) + +AUTOTUNE_CACHE_KEY_STRATEGY = CacheKeyStrategy( + name="autotune", + digest_format="hex", + # Preserve the existing autotune cache format, which concatenates components. + separator=None, +) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/choices.py b/.venv/lib/python3.12/site-packages/torch/_inductor/choices.py new file mode 100644 index 0000000000000000000000000000000000000000..3f11e59acb3c02ec265f27be113eb7d7ba359533 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/choices.py @@ -0,0 +1,787 @@ +from __future__ import annotations + +import dataclasses +import typing +from typing import Any, TYPE_CHECKING + +import sympy + +import torch +from torch._inductor.runtime.runtime_utils import next_power_of_2 +from torch._inductor.scheduler import MixOrderReduction +from torch.utils._sympy.value_ranges import bound_sympy + +from . import config +from .codecache import write_text +from .heuristics.template import get_template_heuristic +from .heuristics.template.triton import ( + _origami_enabled, + BaseConfigHeuristic, + CPUConfigHeuristic, + CUDAConfigHeuristic, + IS_ROCM, + MTIAConfigHeuristic, + ROCmConfigHeuristic, + XPUConfigHeuristic, +) +from .kernel_inputs import KernelInputs, MMKernelInputs +from .kernel_template_choice import make_ktc_generator +from .metrics import get_metric_table, is_metric_table_enabled +from .runtime.hints import DeviceProperties, ReductionHint +from .scheduler import BaseSchedulerNode, Scheduler, WhyNoFuse +from .select_algorithm import ExternKernelChoice +from .utils import _use_autotune_backend +from .virtualized import V + + +if TYPE_CHECKING: + from collections.abc import Generator + from functools import partial + + from triton import Config as TritonConfig + + from .codegen.common import KernelTemplate + from .codegen.simd_kernel_features import SIMDKernelFeatures + from .codegen.triton import TritonKernel + from .ir import ChoiceCaller + from .kernel_template_choice import KernelTemplateChoice + + from torch.utils._ordered_set import OrderedSet # isort: skip + + +if TYPE_CHECKING or not config.is_fbcode(): + + def _maybe_log_inductor_mm_shape( + kernel_inputs: KernelInputs, + op_name: str, + context_fn: Any = None, + ) -> None: + return + +else: + from torch._inductor.fb.shape_logging import ( + log_inductor_mm_shape as _maybe_log_inductor_mm_shape, + ) + + +class Sortable(typing.Protocol): + """Anything that can be used as a list.sort() key (int/tuple/etc)""" + + def __lt__(self, other: typing.Self) -> bool: ... + + +@dataclasses.dataclass +class FusionScore: + template_score: int + node_type_score: int + memory_score: int + buffer_overlap_score: int + proximity_score: int + + def __lt__(self, other): + """ + node_type_score orders same-kind fusions above mixed-kind fusions unless + the memory_score differs too much. Nested reduction candidates use -1 + so they rank below ordinary mixed-kind fusions; mix-order reductions + are still scored through memory_score. + + buffer_overlap_score is prioritized below memory_score so that + strict global memory savings (exact dep matches) are preferred + over buffer overlap scoring (same buffer, different indexing). + """ + threshold = 16 + if self.template_score != other.template_score: + return self.template_score < other.template_score + + if ( + max(self.memory_score, other.memory_score) + > min(self.memory_score, other.memory_score) * threshold + ): + return self.memory_score < other.memory_score + + return ( + self.node_type_score, + self.memory_score, + self.buffer_overlap_score, + self.proximity_score, + ) < ( + other.node_type_score, + other.memory_score, + other.buffer_overlap_score, + other.proximity_score, + ) + + +class InductorChoices: + """ + This class contains a collection of default heuristics that affect performance of our generated + code. We try to not put correctness requirements in this file. + + You can override the choices made here by doing: + + class MyHeuristics(InductorChoices): + ... + + torch._inductor.virtualized.V.set_choices_handler(MyHeuristics()) + + Subclasses used with inductor_choices_class must implement uuid() for + cache key computation. + """ + + def get_config_heuristics( + self, device_type: str | None = "cuda" + ) -> BaseConfigHeuristic: + if device_type == "cuda": + if torch.version.hip is None: + return CUDAConfigHeuristic() + else: + return ROCmConfigHeuristic() + elif device_type == "xpu": + return XPUConfigHeuristic() + elif device_type == "cpu": + return CPUConfigHeuristic() + elif device_type == "mtia": + return MTIAConfigHeuristic() + else: + return BaseConfigHeuristic() + + # Conv configs + def get_conv_configs( + self, device_type: str | None = "cuda" + ) -> partial[Generator[TritonConfig, None, None]]: + conv_heuristics = self.get_config_heuristics(device_type) + return conv_heuristics.get_conv_configs() + + def get_depthwise_conv_configs(self, device_type: str | None = "cuda") -> list[Any]: + heuristics = self.get_config_heuristics(device_type) + return heuristics.get_depthwise_conv_configs() + + # Flex attention configs + # TODO(coconutruben): break out flexattention/decode configs into the new retrieval mechanism + def get_flex_attention_fwd_configs( + self, + head_dim: int, + seq_len: sympy.Expr, + dtype: torch.dtype, + device_type: str | None = "cuda", + ) -> list[Any]: + flex_heuristics = self.get_config_heuristics(device_type) + return flex_heuristics.get_flex_attn_fwd_configs(head_dim, seq_len, dtype) + + def get_flex_attention_bwd_configs( + self, head_dim: int, dtype: torch.dtype, device_type: str | None = "cuda" + ) -> list[Any]: + flex_heuristics = self.get_config_heuristics(device_type) + return flex_heuristics.get_flex_attn_bwd_configs(head_dim, dtype) + + def get_flex_decode_configs( + self, head_dim: int, dtype: torch.dtype, device_type: str | None = "cuda" + ) -> list[Any]: + flex_heuristics = self.get_config_heuristics(device_type) + return flex_heuristics.get_flex_decode_configs(head_dim, dtype) + + def append_flex_attention_choices( + self, + choices: list[Any], + configs: list[Any], + input_nodes: list[Any], + subgraphs: list[Any], + layout: Any, + kernel_options: dict[str, Any], + sparse_q_block_size: int, + sparse_kv_block_size: int, + ) -> list[Any]: + """Append backend-specific flex-attention template choices. + + Default is a no-op. Subclasses may override to inject additional + autotuning candidates (e.g. TLX templates in fbcode). + """ + return choices + + def _logging_context(self) -> dict[str, Any]: + """Extra fields for the per-shape log row. Subclasses may override.""" + return {} + + 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]: + """ + This method can be subclassed to perform any override/modification of the choices. + The incoming parameters are cheap (generators), so you can do any overrides without + incurring too much cost. Override this method to customize the kernel template choices + before they are converted to ChoiceCaller objects, which is expensive on template codegen. + + The full list of arguments are here to facilitate any overrides you may want to do, + as they can be used to start from scratch for each template if so desired. + + Args: + template_choices: Dictionary mapping template UIDs to generators of KernelTemplateChoice objects + kernel_inputs: MMKernelInputs containing input tensor nodes and matrix indices + templates: List of template objects (KernelTemplate or ExternKernelChoice) in use + op_name: Operation name (e.g., "bmm", "baddbmm", "addmm") + kwarg_overrides: Optional dict of kwargs to override for each template heuristic + + Returns: + Flattened list of KernelTemplateChoice objects across all templates + """ + if isinstance(kernel_inputs, MMKernelInputs): + _maybe_log_inductor_mm_shape( + kernel_inputs, op_name, context_fn=self._logging_context + ) + choices: list[KernelTemplateChoice] = [] + for choice_gen in template_choices.values(): + choices.extend(choice_gen) + return choices + + def get_ktc( + self, + kernel_inputs: KernelInputs, + template: KernelTemplate | ExternKernelChoice, + op_name: str, + kwarg_overrides: dict[str, Any] | None = None, + ) -> Generator[KernelTemplateChoice, None, None]: + """ + Utility to get the KernelTemplateChoice generator for a specific input. + + This is a per template/op call, whereas get_template_configs is an op wide call (all templates). + Consider when overriding/using at which level you need to make decisions + """ + # Extract device_type from kernel_inputs + device_type = kernel_inputs.device_type + if device_type is None: + raise AssertionError("get_ktc requires a valid device type") + # Extract template_name from the template object + template_name = template.uid + + # Get the appropriate template-specific heuristic + heuristic = get_template_heuristic(template_name, device_type, op_name) + cs = heuristic.get_template_configs( + kernel_inputs, + op_name, + ) + # adjust the kernel inputs to the template-specific heuristic, if needed + # default here is to just return the kernel_inputs as is + inputs_val = heuristic.adjust_kernel_inputs(kernel_inputs, op_name) + extra_kwargs = heuristic.get_extra_kwargs(kernel_inputs, op_name) + # Create KernelTemplateChoice generator using the moved function + overrides = kwarg_overrides or {} + return make_ktc_generator( + template=template, + cs=cs, + extra_kwargs=extra_kwargs, + overrides=overrides, + layout=kernel_inputs.output_layout(), + inputs=inputs_val, + ) + + def _need_to_fix_layout( + self, + adjusted_choices: list[KernelTemplateChoice], + op_name: str, + ) -> bool: + """Return True if any active backend requires fixed (non-flexible) tensor layouts.""" + # TODO: debug and fix + # NOTE: on mps, we see issues with flexible layouts on baddmm. This check just makes sure + # that for mps, everything stays as it was before this optimization + if len(adjusted_choices) > 0: + if adjusted_choices[0].inputs.device_type == "mps" and op_name not in [ + "mm", + "addmm", + ]: + return True + + # Origami requires fixed layouts (grid/workgroup mappings depend on exact + # strides). Gate on IS_ROCM so a stray TORCHINDUCTOR_ORIGAMI=1 on CUDA + # doesn't disable flexible layouts unnecessarily. Also gate on max-autotune: + # origami only contributes Triton GEMM configs under autotuning, so with it + # off there is nothing that needs fixed strides and flexible layouts should + # be preserved (matches non-origami behavior). + if ( + _origami_enabled() + and IS_ROCM + and (config.max_autotune or config.max_autotune_gemm) + ): + return True + # Since the following backends are not using get_mm_configs yet through the singular call, + if not (config.max_autotune or config.max_autotune_gemm): + # no danger of using other backends than ATEN + if not config.max_autotune_allow_flexible_layouts and op_name not in [ + # The historical implementation for mm and addmm allowed had flexible layouts in the + # not max-autotune world + "mm", + "addmm", + ]: + # TODO: deprecate this by migrating users to the new behavior + return True + return False + + if not config.max_autotune_allow_flexible_layouts: + # we always need to fix the layout + return True + + # Since the following backends are not using get_template_configs yet through the singular call, + # we don't know if they are a valid choice or not. Instead, just skip the optimization + # defensively. + # TODO(coconutruben): remove this once CPP,CK,CUTLASS are supported + if _use_autotune_backend("CUTLASS"): + return True + if _use_autotune_backend("CK") or _use_autotune_backend("CKTILE"): + return True + if _use_autotune_backend("CPP"): + return True + return any( + not isinstance(ktc.template, ExternKernelChoice) for ktc in adjusted_choices + ) + + def get_template_configs( + self, + kernel_inputs: KernelInputs, + templates: list[KernelTemplate | ExternKernelChoice], + op_name: str, + kwarg_overrides: dict[str, dict[str, Any]] | None = None, + ) -> list[ChoiceCaller]: + """ + Get list of ChoiceCallers for MM templates using template-specific heuristics. + + Args: + kernel_inputs: MMKernelInputs containing input tensor nodes and matrix indices + layout: Output layout + templates: List of template objects (KernelTemplate or ExternKernelChoice) + op_name: Operation name (e.g., "bmm", "baddbmm", "addmm", "mm_plus_mm") + kwarg_overrides: Optional dict of kwargs to override for each template heuristic, + indexed by template.uid. These only override the per config kwargs, not the extra kwargs + Returns: + List of ChoiceCaller objects from the templates + """ + if kwarg_overrides is None: + kwarg_overrides = {} + input_tensors = kernel_inputs.nodes() + if len(input_tensors) < 2: + raise ValueError(f"Need at least 2 input tensors, got {len(input_tensors)}") + layout = kernel_inputs.output_layout() + # First pass: Create dict of template.uid to generator of KernelTemplateChoice objects + template_choices = {} + for template in templates: + template_choices[template.uid] = self.get_ktc( + kernel_inputs, + template, + op_name, + kwarg_overrides.get(template.uid, {}), + ) + + # Second pass: Adjust the template choices + adjusted_choices = self._finalize_template_configs( + template_choices, + kernel_inputs, + templates, + op_name, + kwarg_overrides, + ) + # Layout optimization: if all choices are ExternKernelChoice and layout is FixedLayout, convert to FlexibleLayout + if self._need_to_fix_layout(adjusted_choices, op_name): + layout = kernel_inputs.output_layout(flexible=False) + for ktc in adjusted_choices: + ktc.layout = layout + # for good measure, delete the cached ChoiceCaller from the ktc if it existed. + # ExternKernelChoice are cheap to generate + if hasattr(ktc, "_choice"): + del ktc._choice + # Third pass: Convert to ChoiceCaller objects + return [ktc.choice for ktc in adjusted_choices if ktc.choice is not None] + + def triton_kernel_kwargs( + self, + kernel_cls: type[TritonKernel], + features: SIMDKernelFeatures, + groups: list[sympy.Expr], + kernel_kwargs: dict[str, Any], + ) -> dict[str, Any]: + """Hook to change the kwargs passed to TritonKernel, used to apply fixed configurations""" + return kernel_kwargs + + def override_best_choice( + self, + best_choice: ChoiceCaller, + timings: dict[ChoiceCaller, float], + ) -> ChoiceCaller: + """Hook to override the autotuning best choice after benchmarking.""" + return best_choice + + def customize_fused_kernel_name(self, fused_name: str, src_code: str) -> str: + """Hook to transform fused kernel names during codegen""" + return fused_name + + @staticmethod + def should_use_cooperative_reduction( + device: torch.device, numel: sympy.Expr, reduction_numel: sympy.Expr + ) -> bool: + """Heuristic to decide if a cooperative reduction should be used.""" + if config.triton.force_cooperative_reductions: + return True + if not config.triton.cooperative_reductions or device.type == "cpu": + return False + + xhint = V.graph.sizevars.optimization_hint(numel, fallback=2) + if xhint <= 8: + threshold = 32768 * xhint + elif xhint <= 16: + threshold = 2097152 + else: + return False + # TODO(jansel): should this default on for dynamic shapes? + # TODO(laith) What if hint(reduction_numel) >= threshold ? + # shall we compare hints instead + return V.graph.sizevars.statically_known_geq(reduction_numel, threshold) + + @staticmethod + def should_use_persistent_reduction( + features: SIMDKernelFeatures, + cooperative_reduction: bool, + ) -> bool: + """ + Heuristic to decide if a persistent reduction should be used. + """ + if not config.triton.persistent_reductions: + return False + reduction_hint = features.get_reduction_hint() + rblock = features.strict_sum_rblock() + if rblock is not None and not features.has_strict_sum_multirow_reduction(): + if not ( + V.graph.sizevars.statically_known_geq(rblock, features.reduction_numel) + ): + return False + threshold = { + ReductionHint.INNER: 1024, + }.get(reduction_hint, 64) + + if reduction_hint not in ( + ReductionHint.INNER, + ReductionHint.OUTER_TINY, + ): + bounds = bound_sympy(features.reduction_numel) + lower = bounds.lower + upper = bounds.upper + + if not all( + ( + (isinstance(bound, int) or bound.is_constant()) + and not torch.utils._sympy.numbers.is_infinite(bound) + ) + for bound in (lower, upper) + ): + return False + + lower = next_power_of_2(int(lower)) + upper = next_power_of_2(int(upper)) + + # If we are coalescing on xblock (not ReductionHint.INNER) and this is not a tiny kernel + # (not ReductionHint.OUTER_TINY), do not use persistent reduction if it induces tile + # quantization. Persistent reduction forces rblock == rnumel, if the bounds between lower + # and upper are large, for the lower values we will be masking off large % of read/writes, + # when we could expand the coalescing xblock instead. + if lower != upper: + return False + + if cooperative_reduction: + # The RSPLIT of cooperative reductions means each thread block is operating on fewer elements + # The default fallback will be used if optimizations hint is not provided. The default fallback + # is >> 32. + threshold *= 32 // min( + V.graph.sizevars.optimization_hint(features.numel), 32 + ) + + # If multi_kernel is enabled, we do more aggressive persistent reduction. + # This may result in some persistent reductions slower than the + # corresponding non-persistent reductions. MultiKernel will do benchmarking + # to pick the faster one. + if config.triton.multi_kernel: + threshold *= 16 + + return V.graph.sizevars.statically_known_leq( + features.reduction_numel, threshold + ) # type: ignore[arg-types] + + def _inner_reduction_no_split_threshold( + self, + props: DeviceProperties, + xnumel: int, + num_sm: int, + ) -> int: + # Benchmark results from two scenarios: + # (1) Standalone ops/small models: CPU wall time measures end-to-end + # latency and generally prefers a large no-split threshold. + # (2) Sections inside large compiled models: kernel/device time is the + # local codegen signal and prefers the smaller xnumel-dependent + # threshold. Kernel launch overhead is amortized by cuda-graph. + # Benchmarked ops: sum, entropy, RMSNorm, Welford, GroupNorm(+SiLU), + # plus Stable Diffusion v1.5 UNet batch-1/8 validation. + # Chosen GB200 thresholds: 32768 for xnumel < num_sm, otherwise 40960. + # Reducing these thresholds further did not improve scenario (2), but + # hurts scenario (1). + if props.major is not None and props.major >= 10: + if xnumel < num_sm: + return 32768 + return 40960 + return 8192 + + def reduction_split_factor( + self, + device: torch.device, + reduction_numel_hint: int, + numel_hint: int, + inner_reduction: bool, + ) -> int: + """Heuristic to decide the RSPLIT used for split reductions. + When a reduction has a small number of outputs there is not enough parallelism, + so we will do the reduction in two phases.""" + props = DeviceProperties.create(device) + num_sm = props.multi_processor_count + warp_size = props.warp_size_or_default + max_threads_per_sm = ( + props.max_threads_per_multi_processor + if props.max_threads_per_multi_processor is not None + else 2048 + ) + min_elements_per_thread = warp_size + max_elements_per_thread = 512 + threads_per_sm = max_threads_per_sm + min_elements_per_device = min_elements_per_thread * num_sm * threads_per_sm + max_elements_per_device = max_elements_per_thread * num_sm * threads_per_sm + num_warps = 8 + num_threads = warp_size * num_warps + + if inner_reduction: + # do heuristics that's close to eager mode for split inner reduction + # we leak reduction autotune configs here, and will need to refactor to avoid this later + if numel_hint >= 2 * num_sm: # don't split if there are enough outputs + return 1 + no_split_threshold = self._inner_reduction_no_split_threshold( + props, numel_hint, num_sm + ) + if reduction_numel_hint <= no_split_threshold: + return 1 + if reduction_numel_hint * numel_hint <= min_elements_per_device: + split_size = min_elements_per_thread + elif reduction_numel_hint * numel_hint < max_elements_per_device: + target_blocks = num_sm * threads_per_sm // (2 * num_threads) + blocks_per_output = (target_blocks + numel_hint - 1) // numel_hint + tmp_split_size = ( + reduction_numel_hint + num_threads * blocks_per_output - 1 + ) // (num_threads * blocks_per_output) + divisors = sympy.divisors(reduction_numel_hint) + closest = min(divisors, key=lambda x: abs(x - tmp_split_size)) + if abs(closest - tmp_split_size) < 30: + # prefer even splits, but never smaller than min_elements_per_thread + split_size = max(closest, min_elements_per_thread) + else: + split_size = tmp_split_size + else: + divisors = sympy.divisors(reduction_numel_hint) + closest = min(divisors, key=lambda x: abs(x - max_elements_per_thread)) + if abs(closest - max_elements_per_thread) < 50: + # prefer even splits + split_size = closest + else: + split_size = max_elements_per_thread + return (reduction_numel_hint + split_size * num_threads - 1) // ( + split_size * num_threads + ) + else: + # TODO the best heuristic currently has XBLOCK (corresponding to numel_hint) 128 + # extend to even smaller number of outputs + rvals_per_thread = 4 # comes from heuristics, refactor to not leak here + xvals_per_block = 128 + xblocks = (numel_hint + xvals_per_block - 1) // xvals_per_block + if reduction_numel_hint * numel_hint < min_elements_per_device: + split_size = min_elements_per_thread + elif reduction_numel_hint * numel_hint < max_elements_per_device: + target_blocks = num_sm * threads_per_sm // (num_threads) + target_blocks = (target_blocks + xblocks - 1) // xblocks + tmp_split_size = ( + reduction_numel_hint + rvals_per_thread * target_blocks - 1 + ) // (rvals_per_thread * target_blocks) + divisors = sympy.divisors(reduction_numel_hint) + closest = min(divisors, key=lambda x: abs(x - tmp_split_size)) + if abs(tmp_split_size - closest) < 20: + split_size = max(closest, min_elements_per_thread) + else: + split_size = tmp_split_size + else: + divisors = sympy.divisors(reduction_numel_hint) + closest = min(divisors, key=lambda x: abs(x - max_elements_per_thread)) + if abs(closest - max_elements_per_thread) < 50: + # prefer even splits + split_size = closest + else: + split_size = max_elements_per_thread + + return (reduction_numel_hint + rvals_per_thread * split_size - 1) // ( + rvals_per_thread * split_size + ) + + @staticmethod + def can_fuse( + scheduler: Scheduler, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + shared_data_score: int, + ) -> bool: + """ + Heuristics to prevent fusion applied to both horizontal and vertical fusions. Heuristics here should not + be needed for correctness and tweaking them may yield additional performance. + + See also some related heuristics that can be changed via config: + - config.triton.tiling_prevents_pointwise_fusion + - config.triton.tiling_prevents_reduction_fusion + - config.aggressive_fusion (will cause this function to be called more times) + """ + if shared_data_score == 0 and ( + not config.aggressive_fusion or node1.is_reduction() or node2.is_reduction() + ): + if is_metric_table_enabled("fusion_failure_due_to_indexing_mismatch"): + common_buf_names: OrderedSet[str] = ( + node1.read_writes.buffer_names() & node2.read_writes.buffer_names() + ) + if len(common_buf_names) > 0: + get_metric_table("fusion_failure_due_to_indexing_mismatch").add_row( + # pyrefly: ignore [bad-argument-type] + lambda: { + "pre_grad_graph_id": V.graph.graph_id, + "post_grad_graph_id": V.graph.post_grad_graph_id, + "node1_name": node1.get_name(), + "node2_name": node2.get_name(), + "node1_debug_str": write_text(node1.debug_str()), + "node2_debug_str": write_text(node2.debug_str()), + "common_buffer_names": list(common_buf_names), # type: ignore[dict-item] + "failure_reason": scheduler.decide_fusion_fail_reason( + node1, node2, common_buf_names + ), + } + ) + + WhyNoFuse(node1, node2)("no shared data due to indexing mismatch") + return False + WhyNoFuse(node1, node2)("no shared data") + return False # heuristic not needed for correctness + + if ( + not node1.is_foreach() + and not node2.is_foreach() + and len(node1.get_nodes()) + len(node2.get_nodes()) > config.max_fusion_size + ): + WhyNoFuse(node1, node2)("exceeds max fusion") + return False # heuristic not needed for correctness + + if scheduler.can_fusion_increase_peak_memory(node1, node2): + WhyNoFuse(node1, node2)("Fusion will increase peak memory") + return False + + if ( + config.max_fusion_unique_io_buffers is not None + and scheduler.fusion_prevent_too_many_reads_and_writes( + node1, + node2, + config.max_fusion_unique_io_buffers, + ) + ): + WhyNoFuse(node1, node2)("fusion_prevent_too_many_reads_and_writes") + return False + + return True + + @staticmethod + def can_fuse_vertical( + scheduler: Scheduler, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + shared_data_score: int, + ) -> bool: + """Hook for heuristics to prevent vertical (producer/consumer) fusions""" + return True + + @staticmethod + def can_fuse_horizontal( + scheduler: Scheduler, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + shared_data_score: int, + ) -> bool: + """Hook for heuristics to prevent horizontal (consumer/consumer) fusions""" + if MixOrderReduction.can_fuse(node1, node2): + # For mix order reduction, we disregard shared data or + # distance. + return True + if shared_data_score < config.score_fusion_memory_threshold: + WhyNoFuse(node1, node2)("score_fusion_memory_threshold") + return False + if scheduler.are_long_distant_nodes(node1, node2): + WhyNoFuse(node1, node2)( + "Nodes are too far away. Fusing them may increase peak memory." + ) + return False + return True + + @staticmethod + def score_fusion( + scheduler: Scheduler, + node1: BaseSchedulerNode, + node2: BaseSchedulerNode, + ) -> Sortable: + """ + Assign a score (higher comes first) to the fusion of node1 and node2. + When different fusions conflict with each other, this is the way we + decide what order to run them in. + + Our current score is based on: + - The type of fusion (template/reduction/etc) + - Estimate of the saved memory operations + - Fusions closer together in original graph order + """ + + memory_score, buffer_overlap_score, is_mix_order_reduction = ( + scheduler.score_fusion_memory( + node1, node2, return_is_mix_order_reduction=True + ) + ) + proximity_score = -max( + abs(node1.min_order - node2.max_order), + abs(node2.min_order - node1.max_order), + ) + + # prologue fusion always last + if node2.is_template(): + template_score = 0 + else: + template_score = 1 + ( + (node1.is_template() == config.epilogue_fusion_first) + and memory_score > 0 + ) + + node_type_score = int( + node1.is_reduction() == node2.is_reduction() and memory_score > 0 + ) + if ( + config.triton.nested_reduction + and node1.is_reduction() + and node2.is_reduction() + and node1.get_operation_names() & node2.ancestors + ): + # Mix-order reductions are sibling reductions. Only dependent + # cross-reduction-size reductions get the lower nested score here. + _, (_, rnumel1) = node1.group + _, (_, rnumel2) = node2.group + if not V.graph.sizevars.statically_known_equals(rnumel1, rnumel2): + node_type_score = -1 + + return FusionScore( + template_score, + node_type_score, + memory_score, + buffer_overlap_score, + proximity_score, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codecache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codecache.py new file mode 100644 index 0000000000000000000000000000000000000000..53d5b52f9682b4a4b9084e502150eb9c581d8431 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codecache.py @@ -0,0 +1,5542 @@ +from __future__ import annotations + +import base64 +import copyreg +import dataclasses +import functools +import hashlib +import importlib +import importlib.resources +import io +import itertools +import json +import logging +import os +import pickle +import pkgutil +import platform +import re +import shlex +import shutil +import struct +import subprocess +import sys +import tempfile +import textwrap +import threading +import warnings +from bisect import bisect_right +from collections.abc import Set as AbstractSet +from copy import copy +from ctypes import c_void_p, CDLL, cdll +from datetime import timedelta +from functools import lru_cache, partial +from pathlib import Path +from tempfile import _TemporaryFileWrapper +from time import time, time_ns +from types import ( + BuiltinFunctionType, + BuiltinMethodType, + FunctionType, + MethodType, + ModuleType, +) +from typing import Any, cast, Generic, Literal, NoReturn, TYPE_CHECKING, TypeVar +from typing_extensions import NotRequired, override, Self, TypedDict + +import torch +import torch._library.opaque_object as opaque_object +import torch.distributed as dist +from torch import SymInt, Tensor +from torch._dynamo.device_interface import get_interface_for_device +from torch._dynamo.exc import SkipFrame +from torch._dynamo.utils import ( + CompileEventLogger, + counters, + dynamo_timed, + get_metrics_context, +) +from torch._inductor import config, config_comms, exc, metrics +from torch._inductor.codegen.common import ( + custom_backend_codegen_configs, + custom_backend_passes, + init_backend_registration, +) +from torch._inductor.codegen.cuda import compile_utils as cuda_compile_utils +from torch._inductor.codegen.rocm.compile_command import ( + rocm_compile_command, + rocm_compiler, +) +from torch._inductor.compile_worker.utils import in_toplevel_process +from torch._inductor.cpp_builder import ( + _LINKER_SCRIPT, + _set_gpu_runtime_env, + _TORCH_PATH, + batch_convert_cubins_to_obj, + convert_cubin_to_obj, + CppBuilder, + CppOptions, + CppTorchDeviceOptions, + get_compiler_version_info, + get_cpp_compiler, + get_ld_and_objcopy, + get_name_and_dir_from_output_file_path, + normalize_path_separator, + run_asm_build_object, +) +from torch._inductor.cpu_vec_isa import invalid_vec_isa, pick_vec_isa +from torch._inductor.custom_graph_pass import ( + CustomGraphModulePass, + CustomGraphPass, + CustomGraphPassCallable, + CustomPartitionerFn, + CustomPartitionerFnType, + CustomPassBase, + CustomSchedulerPass, + get_custom_graph_passes, +) +from torch._inductor.freezing_utils import has_frozen_params, is_frozen_param +from torch._inductor.runtime.compile_tasks import _reload_python_module +from torch._inductor.runtime.runtime_utils import cache_dir, default_cache_dir +from torch._inductor.utils import ( + ALIGN_BYTES, + clear_on_fresh_cache, + determine_aoti_mmap_flags, + is_linux, + is_windows, + parallel_num_threads, + XPU_KERNEL_FORMAT, +) +from torch._library.fake_class_registry import FakeScriptObject +from torch._library.opaque_object import is_opaque_symbolic_type +from torch._logging import trace_structured +from torch._subclasses.fake_tensor import ( + extract_tensor_metadata, + FakeTensor, + TensorMetadata, +) +from torch._utils_internal import log_cache_bypass +from torch.compiler import config as cconfig +from torch.compiler._cache import ( + CacheArtifact, + CacheArtifactFactory, + CacheArtifactRecorder, +) +from torch.export.pt2_archive._package_weights import TensorProperties, Weights +from torch.export.pt2_archive.constants import CUSTOM_OBJ_FILENAME_PREFIX +from torch.fx.experimental.symbolic_shapes import ( + guarding_hint_or_throw, + has_guarding_hint, + ShapeEnv, +) +from torch.utils._device import _device_constructors +from torch.utils._ordered_set import OrderedSet + +from .cache_key import ( + CODE_CACHE_KEY_STRATEGY, + COMPACT_CACHE_KEY_STRATEGY, + FX_GRAPH_CACHE_KEY_STRATEGY, + SYSTEM_CACHE_KEY_STRATEGY, +) +from .output_code import CompiledFxGraph +from .remote_cache import cache_stats, create_cache +from .runtime import autotune_cache +from .runtime.autotune_cache import AutotuneCacheBundler +from .triton_bundler import TritonBundler +from .virtualized import V + + +T = TypeVar("T") + + +class SystemDeviceInfo(TypedDict): + name: str | None + + +class SystemVersionInfo(TypedDict, total=False): + triton: str | None + cuda: str + hip: str | None + + +class SystemInfo(TypedDict): + hash: str + device: NotRequired[SystemDeviceInfo] + version: NotRequired[SystemVersionInfo] + + +class CacheInfo(TypedDict, total=False): + cache_state: Literal["bypass", "hit", "miss"] + cache_status_detailed: str + cache_status_guard_expr: str + triton_bundler_meta: str + time_saved_ns: int + time_taken_ns: int + ephemeral_timeout_increase: int + cache_bypass_reason: str + cache_event_time: int + key: str + components: list[str] + cache_bypass_exception_type: str + cache_bypass_traceback: list[str] + cache_bypass_hard_exception: bool + + +if TYPE_CHECKING: + from collections.abc import Callable, Generator, KeysView, Sequence + from concurrent.futures import Future + + from .compile_fx import _CompileFxKwargs + from .cpp_builder import BuildOptionsBase + from .graph import GraphLowering + from .ir import ChoiceCaller + from .output_code import CompiledFxGraphConstants, OutputCode + from .remote_cache import JsonDataTy, RemoteCache + from .runtime.hints import HalideInputSpec, HalideMeta + from .runtime.triton_heuristics import CachingAutotuner + from .utils import InputType + + +_IS_WINDOWS = sys.platform == "win32" +LOCK_TIMEOUT = config.file_lock_timeout + +output_code_log = torch._logging.getArtifactLogger(__name__, "output_code") +autotuning_log = torch._logging.getArtifactLogger(__name__, "autotuning") +log = logging.getLogger(__name__) + +AOTAUTOGRAD_CACHE_PREFIX = "a" + + +def _device_constructor_sort_key(target: Any) -> str: + return ".".join( + x + for x in ( + getattr(target, "__module__", None), + getattr(target, "__qualname__", None), + getattr(target, "__name__", None), + repr(target), + ) + if x + ) + + +@lru_cache(None) +def _default_device_constructor_targets() -> tuple[Any, ...]: + return tuple(sorted(_device_constructors(), key=_device_constructor_sort_key)) + + +@lru_cache(None) +def _default_device_constructor_overload_packets() -> tuple[Any, ...]: + packets: list[Any] = [] + for target in _default_device_constructor_targets(): + if (name := getattr(target, "__name__", None)) is None: + continue + if (packet := getattr(torch.ops.aten, name, None)) is not None: + packets.append(packet) + return tuple(packets) + + +def get_cpp_wrapper_cubin_path_name() -> str: + return "cubin_path" if torch.version.hip is None else "hsaco_path" + + +def get_kernel_bin_format(device: str) -> str: + if device == "cuda": + return "cubin" if torch.version.hip is None else "hsaco" + elif device == "xpu": + return XPU_KERNEL_FORMAT + else: + return "" + + +def _cuda_fatbin_command( + asm_file: str, + cubin_file: str, + raw_cubin_file: str | None, + nvcc: str | None, + fatbinary: str | None, + current_arch: str | None = None, +) -> list[str]: + if not current_arch: + current_arch = cuda_compile_utils._nvcc_arch_as_compile_option_or_raise() + gencode_options = cuda_compile_utils._cuda_multi_arch_gencode_options(current_arch) + if ( + fatbinary is not None + and raw_cubin_file is not None + and os.path.exists(raw_cubin_file) + and not cuda_compile_utils._cuda_gencode_options_have_non_current_sass( + gencode_options, current_arch + ) + ): + # Avoid re-running ptxas; the CUDA toolkit can lag the PTX version + # emitted by Triton. This path is only valid when no extra SASS images + # beyond the current GPU generation were requested. + return [ + fatbinary, + f"--create={cubin_file}", + "-64", + f"--image3=kind=elf,sm={current_arch},file={raw_cubin_file}", + f"--image3=kind=ptx,sm={current_arch},file={asm_file}", + ] + + if nvcc is None: + raise RuntimeError("nvcc is required to build fatbin") + + cmd = [ + *shlex.split(nvcc), + "-fatbin", + asm_file, + "-o", + cubin_file, + ] + for gencode_option in gencode_options: + cmd.extend(["-gencode", gencode_option]) + return cmd + + +def get_device_information(device_type: str) -> dict[str, str]: + """ + Gets all the current device information used to compile the .so. + """ + metadata: dict[str, str] = { + "AOTI_PLATFORM": sys.platform, + "AOTI_MACHINE": platform.machine(), + "AOTI_CPU_ISA": str(torch._inductor.cpu_vec_isa.pick_vec_isa()).upper(), + "AOTI_COMPUTE_CAPABILITY": str( + get_interface_for_device(device_type).get_compute_capability() + ), + } + return metadata + + +from torch.utils._functools import prefetchable_cache as torch_key_cache + + +@torch_key_cache +def triton_key() -> str | None: + from torch._inductor.runtime.triton_compat import ( + HAS_TRITON, + triton_key as _triton_key_impl, + ) + + # Use triton_key instead of triton.__version__ as the version + # is not updated with each code change + if HAS_TRITON: + return _triton_key_impl() + return None + + +class CacheBase: + @staticmethod + @functools.cache + def get_system() -> SystemInfo: + with dynamo_timed("CacheBase.get_system.triton_key"): + triton_version = triton_key() + + try: + device_info: SystemDeviceInfo = {"name": None} + version_info: SystemVersionInfo = {"triton": triton_version} + device_properties = torch.cuda.get_device_properties( + torch.cuda.current_device() + ) + if torch.version.cuda is not None: + device_info["name"] = device_properties.name + version_info["cuda"] = torch.version.cuda + else: + device_info["name"] = device_properties.gcnArchName + version_info["hip"] = torch.version.hip + hash_input: dict[str, Any] = { + "device": device_info, + "version": version_info, + } + return { + "device": device_info, + "version": version_info, + "hash": SYSTEM_CACHE_KEY_STRATEGY.key_from_json(hash_input), + } + except (AssertionError, RuntimeError): + # If cuda is not installed, none of the above config is relevant. + return {"hash": SYSTEM_CACHE_KEY_STRATEGY.key_from_json({})} + + @staticmethod + @clear_on_fresh_cache + @functools.cache + def get_local_cache_path() -> Path: + return Path(os.path.join(cache_dir(), "cache", CacheBase.get_system()["hash"])) + + def __init__(self) -> None: + self.system = CacheBase.get_system() + + def get_local_cache(self) -> dict[str, Any]: + local_cache_path = self.get_local_cache_path() + if not local_cache_path.is_file(): + return {} + with open(local_cache_path) as local_cache_fp: + local_cache = json.load(local_cache_fp) + return local_cache["cache"] + + def update_local_cache(self, local_cache: dict[str, Any]) -> None: + local_cache_path = self.get_local_cache_path() + write_atomic( + str(local_cache_path), + json.dumps({"system": self.system, "cache": local_cache}, indent=4), + make_dirs=True, + ) + + +class LocalCache(CacheBase): + def lookup(self, *keys: str) -> dict[str, Any] | None: + cache = self.get_local_cache() + + sub_cache = cache + for key in keys: + if key in cache: + sub_cache = cache[key] + else: + return None + + return sub_cache + + def set_value(self, *keys: str, value: Any) -> None: + cache = self.get_local_cache() + + sub_cache = cache + for key in keys[0:-1]: + sub_cache.setdefault(key, {}) + sub_cache = sub_cache[key] + sub_cache[keys[-1]] = value + + self.update_local_cache(cache) + + +class PersistentCache(CacheBase): + def lookup( + self, + choices: list[ChoiceCaller], + op: str, + inputs: str, + benchmark: Callable[[Any], dict[ChoiceCaller, float]] | None, + hint_override: int | None = None, + ) -> dict[ChoiceCaller, float]: + """ + Check to see if we have benchmarked the given choice callers. For each + choice caller: + + 1. Check local_cache[op][inputs][choice][precision], return benchmark if cached. + 2. If benchmark is not None: + a. `max_autotune_gemm=True`: benchmark the choice, update + local_cache[op][inputs][choice], and return the benchmark. + b. `max_autotune_gemm=False`: don't benchmark the choice, return nothing. + """ + precision = torch.get_float32_matmul_precision() + cache_key = f"{inputs}_{hint_override}" if hint_override is not None else inputs + + timings = {} + + def check_cache(cache: dict[str, Any]) -> bool: + """Check if `cache` contains data for all the choices""" + hit = True + for choice in choices: + choice_hash = choice.hash_key() + if choice_hash in cache.get(op, {}).get(cache_key, {}).get( + precision, {} + ): + # cache hit + timings[choice] = cache[op][cache_key][precision][choice_hash] + else: + # cache miss + hit = False + break + return hit + + local_cache = self.get_local_cache() if config.autotune_local_cache else {} + if (not check_cache(local_cache)) and (benchmark is not None): + # re-benchmark everything to try to get consistent numbers from the same machine + timings = benchmark(choices) + if not all(choice in timings for choice in choices): + missing = [c for c in choices if c not in timings] + raise AssertionError( + f"Benchmark results missing for choices: {missing}" + ) + local_cache.setdefault(op, {}) + local_cache[op].setdefault(cache_key, {}).setdefault(precision, {}) + for choice, timing in timings.items(): + local_cache[op][cache_key][precision][choice.hash_key()] = timing + + self.update_local_cache(local_cache) + + return timings + + +def get_lock_dir() -> str: + lock_dir = os.path.join(cache_dir(), "locks") + if not os.path.exists(lock_dir): + os.makedirs(lock_dir, exist_ok=True) + return lock_dir + + +def sha256_hash(data: bytes) -> str: + return COMPACT_CACHE_KEY_STRATEGY.key(data) + + +def code_hash(code: str | bytes, extra: str | bytes = "") -> str: + if extra: + return CODE_CACHE_KEY_STRATEGY.key(code, extra) + return CODE_CACHE_KEY_STRATEGY.key(code) + + +def get_path( + basename: str, extension: str, specified_dir: str = "" +) -> tuple[str, str, str]: + if specified_dir: + if os.path.isabs(specified_dir): + subdir = specified_dir + else: + subdir = os.path.join(cache_dir(), specified_dir) + else: + subdir = os.path.join(cache_dir(), basename[1:3]) + path = os.path.join(subdir, f"{basename}.{extension}") + return basename, subdir, path + + +def get_hash(content: str | bytes, extra: str = "", hash_type: str = "code") -> str: + if hash_type in {"amdgcn", "code", "ptx", "spv"}: + return code_hash(content, extra) + if hash_type in {"cubin", "hsaco", XPU_KERNEL_FORMAT}: + return code_hash(repr(content)) + raise AssertionError(f"Unknown hash type {hash_type}") + + +class WritableTempFile: + """ + Avoid "Permission denied error" on Windows: + with tempfile.NamedTemporaryFile("w", suffix=".gv") as temp_file: + # Not writable on Windows: + # https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile + + Example: + with WritableTempFile("w", suffix=".gv") as temp_file: + tree.to_dotfile(temp_file.name) + """ + + def __init__( + self, mode: str = "w", *, encoding: Any = None, suffix: Any = None + ) -> None: + self.mode = mode + self.encoding = encoding + self.suffix = suffix + + def __enter__(self) -> _TemporaryFileWrapper[Any]: + self.temp_file = tempfile.NamedTemporaryFile( + self.mode, encoding=self.encoding, suffix=self.suffix, delete=False + ) + return self.temp_file + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + self.temp_file.close() + try: + os.unlink(self.temp_file.name) + except OSError as e: + if _IS_WINDOWS: + # On Windows, some case temp file is opened and fail to unlink. Need to ignore it. + pass + else: + raise e + + +def write( + content: str | bytes, + extension: str, + extra: str = "", + hash_type: str = "code", + specified_dir: str = "", + key: str | None = None, +) -> tuple[str, str]: + if key is None: + # use striped content to compute hash so we don't end up with different + # hashes just because the content begins/ends with different number of + # spaces. + key = get_hash(content.strip(), extra, hash_type) + basename, _subdir, path = get_path(key, extension, specified_dir) + if not os.path.exists(path): + write_atomic(path, content, make_dirs=True) + return basename, path + + +def write_text(text: str) -> str: + """ + Write the `text` to a file and return the path computed based on the hash. + """ + return write(text, "txt")[1] + + +def write_atomic( + path_: str, + content: str | bytes, + make_dirs: bool = False, + encode_utf_8: bool = False, +) -> None: + # Write into temporary file first to avoid conflicts between threads + # Avoid using a named temporary file, as those have restricted permissions + if not isinstance(content, (str, bytes)): + raise AssertionError("Only strings and byte arrays can be saved in the cache") + path = Path(path_) + if make_dirs: + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path = path.parent / f".{os.getpid()}.{threading.get_ident()}.tmp" + write_mode = "w" if isinstance(content, str) else "wb" + with tmp_path.open(write_mode, encoding="utf-8" if encode_utf_8 else None) as f: + f.write(content) + try: + tmp_path.rename(target=path) + except FileExistsError: + if not _IS_WINDOWS: + raise + # On Windows file exist is expected: https://docs.python.org/3/library/pathlib.html#pathlib.Path.rename + # Below two lines code is equal to `tmp_path.rename(path)` on non-Windows OS. + # 1. Copy tmp_file to Target(Dst) file. + shutil.copy2(src=tmp_path, dst=path) + # 2. Delete tmp_file. + os.remove(tmp_path) + + +@dataclasses.dataclass +class TensorMetadataAndValues: + """ + TensorMetadata plus the elements as a list of raw values. + Used for hashing inlined constants. + """ + + tensor_metadata: TensorMetadata + values: list[Any] + + +def _ident(x: T) -> T: + return x + + +def _unpicklable_error(key: str) -> NoReturn: + raise RuntimeError( + f"Attempted to unpickle an object that was pickled only for cache-key " + f"hashing and cannot be reconstructed (key={key!r})" + ) + + +def extract_tensor_metadata_for_cache_key(t: Tensor) -> TensorMetadata: + """ + Extracts the tensor metadata and removes fields of the TensorMetadata + that are not needed for caching + """ + meta = extract_tensor_metadata(t) + if not hasattr(t, "_is_inductor_static"): + meta = dataclasses.replace(meta, storage_offset=0, storage_bytes=None) + + return meta + + +# Types that pickle handles natively via GLOBAL/INST opcodes even though their +# __reduce_ex__ may raise TypeError. We must not treat these as unpicklable in +# reducer_override to avoid infinite recursion. +# We use a tuple for isinstance() checks so subclasses are also matched +# (e.g. ABCMeta is a subclass of type). +_PICKLE_NATIVE_TYPES_TUPLE = ( + FunctionType, + BuiltinFunctionType, + BuiltinMethodType, + MethodType, + type, +) + + +def _get_stable_obj_key(obj: object) -> str | None: + """Produce a deterministic string key for an otherwise-unpicklable object. + + Used by FxGraphCachePickler.reducer_override as a fallback for objects + whose types don't support default pickling (e.g. pybind11 enums). + + The key is derived from the object's fully-qualified type name plus + values obtained via known accessor patterns (pybind11 enum, Python enum, + etc.). Returns ``None`` if no accessor succeeds, letting the caller + decide how to handle the failure. + """ + t = type(obj) + type_id = f"{t.__module__}.{t.__qualname__}" + parts = [] + for accessor in ( + lambda o: o.type.name, # pybind11 enum pattern + lambda o: o.name, # Python enum / named constant pattern + lambda o: o.value, # value-based pattern + ): + try: + parts.append(str(accessor(obj))) + except Exception: + continue + if parts: + return f"{type_id}:{repr(parts)}" + return None + + +class FxGraphCachePickler(pickle.Pickler): + """ + Custom pickler to customize the pickling of some objects (Tensors), only for the + purpose of computing a hash for keying into the FxGraphCache. Tensors contain + objects that don't pickle and/or vary between runs, and we want to capture the + data that allow us to compute a stable, but safe hash. + """ + + # Cache probe results so we only call __reduce_ex__ once per type. + # Maps type -> True (pickleable) or False (unpickleable). + # Class-level because a type's picklability doesn't change at runtime. + _pickleable_type_cache: dict[type, bool] = {} + + def __init__( + self, + gm: torch.fx.GraphModule, + has_user_defined_triton_kernels: bool = False, + device_id_agnostic: bool = False, + ) -> None: + """ + Create an FX graph pickler. If include_non_inlined=True, then pickling will + include the _values_ for all Tensors. (Note that any tensors are constants + attached as attributes to the GraphModule). Otherwise, pickling will include + only the metadata for these tensors. + + If device_id_agnostic=True, device indices in TensorMetadata are normalized + to 0, so that the same graph on different GPUs produces identical bytes. + """ + self._stream = io.BytesIO() + self._device_id_agnostic = device_id_agnostic + super().__init__(self._stream) + + self.dispatch_table = copyreg.dispatch_table.copy() + self.dispatch_table.update( + { + FakeTensor: functools.partial(self._reduce_fake_tensor), + torch.Tensor: functools.partial(self._reduce_tensor), + torch.nn.parameter.Parameter: functools.partial(self._reduce_tensor), + torch.SymInt: functools.partial(self._reduce_symint), + torch.SymBool: functools.partial(self._reduce_symbool), + torch.fx.experimental._backward_state.BackwardState: functools.partial( + self._reduce_unsupported + ), + FakeScriptObject: functools.partial(self._reduce_fake_script_object), + } + ) + if has_user_defined_triton_kernels: + # Need to use runtime type as GraphModule generates a singleton in __new__ function + self.dispatch_table[gm.__class__] = functools.partial( + self._reduce_graph_module + ) + + # Run with pickler.fast so it doesn't intern strings, making the hash result more predictable + # TODO: pickler.fast is technically deprecated. Will this work on new python versions? + self.fast = True + + # pyrefly: ignore [bad-override] + def reducer_override(self, obj: Any) -> Any: + """Fallback reducer for objects not registered in dispatch_table. + + This handles extension types (e.g. pybind11 enums) that don't support + default pickling. Instead of bypassing the FX graph cache entirely, + we serialize a deterministic string representation of the object which + is sufficient for cache-key hashing. + """ + t = type(obj) + # Types already registered or handled by default pickle. + # Use isinstance for _PICKLE_NATIVE_TYPES to cover subclasses + # (e.g. ABCMeta is a subclass of type, and pickle handles all + # type/class objects natively via GLOBAL opcode). + if t in self.dispatch_table or isinstance(obj, _PICKLE_NATIVE_TYPES_TUPLE): + return NotImplemented + # Fast path: type already probed. + if (pickleable := self._pickleable_type_cache.get(t)) is not None: + if not pickleable: + return self._reduce_unpicklable(obj) + return NotImplemented + # First encounter: probe whether the default reduce protocol works. + try: + result = obj.__reduce_ex__(pickle.DEFAULT_PROTOCOL) + except (TypeError, AttributeError, pickle.PicklingError): + self._pickleable_type_cache[t] = False + return self._reduce_unpicklable(obj) + except RuntimeError as e: + if "is not pickleable" in str(e): + self._pickleable_type_cache[t] = False + return self._reduce_unpicklable(obj) + raise + # Default pickling works – let pickle handle it. + self._pickleable_type_cache[t] = True + return result + + @staticmethod + def _reduce_unpicklable(obj: Any) -> Any: + key = _get_stable_obj_key(obj) + if key is None: + raise BypassFxGraphCache( + f"Cannot produce stable cache key for unpicklable type " + f"{type(obj).__qualname__}" + ) + return _unpicklable_error, (key,) + + def _reduce_fake_tensor( + self, t: Tensor + ) -> tuple[Callable[[T], T], tuple[TensorMetadata]]: + """ + Custom reducer to pickle FakeTensors. + """ + metadata = extract_tensor_metadata_for_cache_key(t) + if self._device_id_agnostic: + metadata = dataclasses.replace( + metadata, device=torch.device(metadata.device.type, 0) + ) + return (_ident, (metadata,)) + + def _reduce_tensor( + self, t: Tensor + ) -> tuple[Callable[[T], T], tuple[TensorMetadata | TensorMetadataAndValues]]: + """ + Custom reducer to pickle Tensors. If we see tensors, we know they're constants + stored as attributes on the GraphModule. + """ + from .graph import GraphLowering + + if t.is_mkldnn: + # TODO: These tensors don't currently pickle, so we can't cache a compiled + # graph containing them. Just fail now. If mkldnn tensors get pickling + # support, we can remove this. + CacheabilityValidator.check_tensor(t) + + metadata = extract_tensor_metadata_for_cache_key(t) + if self._device_id_agnostic: + metadata = dataclasses.replace( + metadata, device=torch.device(metadata.device.type, 0) + ) + + # If this is a non-inlined frozen parameter, we consider the metadata only. + if is_frozen_param(t) and not GraphLowering.can_inline_constant(t): + return (_ident, (metadata,)) + + # Very large tensors will be expensive to copy to cpu and hash. Let's at least + # report any slowness. + start = time() + values = t.tolist() + elapsed = time() - start + if elapsed > 1.0: + warnings.warn( + f"FX graph cache copying of a large constant took {elapsed:.1}s. " + "Please file an issue." + ) + + return (_ident, (TensorMetadataAndValues(metadata, values),)) + + def _reduce_symint(self, s: SymInt) -> tuple[Callable[[T], T], tuple[str]]: + """ + Custom reducer to pickle SymInts. + """ + # For hashing purposes, we only care about the name of the symbol and not the + # backed value. We evaluate guards stored with a cached graph to ensure a cached + # entity with SymInt args is safe to reuse. + return (_ident, (str(s),)) + + def _reduce_symbool(self, s: torch.SymBool) -> tuple[Callable[[T], T], tuple[str]]: + """ + Custom reducer to pickle SymBools. + """ + # Same approach as _reduce_symint: use the string representation for + # hashing. Guards ensure correctness on cache reload. + return (_ident, (str(s),)) + + def _reduce_unsupported(self, s: Any) -> NoReturn: + """ + Custom reducer to handle any objects that we don't support and therefore + raise to bypass caching. + """ + CacheabilityValidator.bypass("Reduce unsupported") + + def _reduce_graph_module( + self, gm: torch.fx.GraphModule + ) -> tuple[Any, tuple[dict[str, Any], str]]: + """ + Custom reducer for graph module to handle irrelevant data for user + defined triton kernels + Essentially what we are doing here is a huge hack where user defined + triton kernel contain a dynamo time side table and the arguments to the + call_function are indices into this side table. These arguments are not + for hashing purposes since we included the source code into the cache + key and the numbers are prone to give false negatives due to ordering. + """ + fn, (data, imports) = gm.__reduce__() + code = data["_code"] + code = re.sub(r"kernel_idx = \d+", "", code) + code = re.sub(r"constant_args_idx = \d+", "", code) + data["_code"] = code + return fn, (data, imports) + + def _reduce_fake_script_object( + self, t: FakeScriptObject + ) -> tuple[Callable[..., Any], tuple[Any, ...]]: + if t.real_obj is not None: + cls = type(t.real_obj) + # This is the only case where I'm sure it's cache safe. + # I have not worked out the details for everything else + # but I'm sure we could + if ( + opaque_object.is_custom_class(cls) + and opaque_object.should_hoist(cls) + and not opaque_object.has_members(cls) + ): + return (_ident, (t.script_class_name,)) + if opaque_object.is_custom_class(cls): + # Opaque types (e.g., DeviceMesh) may have cyclic references + # that fast-mode pickling cannot handle. Disable fast mode + # before the subtree is pickled so the memo table tracks cycles. + self.fast = False + return (_ident, (t.wrapped_obj, t.script_class_name, t.real_obj)) + + def dumps(self, obj: Any) -> bytes: + """ + Pickle an object and return a byte string. + """ + try: + self.dump(obj) + return self._stream.getvalue() + except (TypeError, AttributeError, pickle.PicklingError, ValueError) as e: + CacheabilityValidator.bypass_for_pickle_error(e) + except RuntimeError as e: + # pybind11 raises RuntimeError with message like: + # " is not pickleable." + if "pybind11" in str(e) and "is not pickleable" in str(e): + CacheabilityValidator.bypass_for_pickle_error(e) + raise + finally: + # Reset our stream for the next dump. + self._stream.seek(0) + self._stream.truncate(0) + + def get_hash(self, obj: Any) -> str: + """ + Serialize an object and return a hash of the bytes. + """ + serialized_data = self.dumps(obj) + return COMPACT_CACHE_KEY_STRATEGY.key(serialized_data) + + def get_key(self, obj: Any) -> str: + """ + Serialize an object and return an FX graph cache key. + """ + serialized_data = self.dumps(obj) + return FX_GRAPH_CACHE_KEY_STRATEGY.key(serialized_data) + + def debug_lines(self, inp: FxGraphHashDetails) -> list[str]: + """ + Get a printable string describing in more detail all the attributes + comprising an object. Useful for debugging when one graph hashes + to a different value than another. + """ + + def get_str(obj: Any) -> str: + if isinstance(obj, torch.Tensor): + return str(extract_tensor_metadata_for_cache_key(obj)) + elif isinstance(obj, bytes): + val = obj.decode("utf-8", errors="replace") + return val if len(val) <= 1024 else val[:1024] + "..." + elif type(obj) in self.dispatch_table: + # Run the reducer on the object + return str(self.dispatch_table[type(obj)](obj)[1]) + else: + return str(obj) + + lines = [] + for attr, obj in vars(inp).items(): + if isinstance(obj, list): + for ii in range(len(obj)): + h = self.get_hash(obj[ii]) + lines.append(f"[{h}] {attr}[{ii}]: {get_str(obj[ii])}") + elif isinstance(obj, dict): + for k, v in obj.items(): + h = self.get_hash(v) + lines.append(f"[{h}] {attr}[{k}]: {get_str(v)}") + else: + h = self.get_hash(obj) + lines.append(f"[{h}] {attr}: {get_str(obj)}") + return lines + + +def build_code_hash( + roots: list[str] | None, prefix: str, hasher: hashlib._Hash +) -> None: + for lib in sorted(pkgutil.iter_modules(roots, prefix), key=lambda x: x.name): + spec = lib.module_finder.find_spec(lib.name, None) + if spec is None: + raise AssertionError(f"Failed to find spec for module {lib.name}") + module = spec.origin + if module is None: + raise AssertionError(f"Module spec for {lib.name} has no origin") + with open(module, "rb") as f: + hasher.update(spec.name.encode("utf-8")) + hasher.update(f.read()) + if lib.ispkg: + # need to also hash submodules + build_code_hash(spec.submodule_search_locations, f"{spec.name}.", hasher) + + +@torch_key_cache +def torch_key() -> bytes: + """ + Compute a key that contains relevant information about torch source files + """ + with dynamo_timed("inductor_codecache_torch_key", log_pt2_compile_event=False): + if not config.is_fbcode(): + + def get_code_hash(root: str) -> bytes: + # This function isn't meant to be used outside of torch_key, just a + # helper for clarity. Instead, use torch_key() directly when you need + # a hash representing the state of the source code. + extra_files = ( + "codegen/aoti_runtime/interface.cpp", + "codegen/aoti_runtime/streams.h", + "script.ld", + ) + inductor_root = os.path.dirname(__file__) + extra_files = [os.path.join(inductor_root, x) for x in extra_files] + hasher = hashlib.sha256() + hasher.update(torch.__version__.encode("utf-8")) + build_code_hash([root], "", hasher) + for path in extra_files: + if os.path.exists(path): + with open(path, "rb") as f: + hasher.update(f.read()) + return hasher.digest() + + return get_code_hash(_TORCH_PATH) + + from libfb.py import parutil + + return parutil.get_file_contents("torch/src_hash.txt").rstrip().encode("ascii") + + +def get_inductor_root() -> str: + return os.path.dirname(__file__) + + +@dataclasses.dataclass +class OrderedSetHolder: + """ + See FxGraphHashDetails. Holds a sorted list to support stable hashing + of set kwargs. + """ + + items: list[Any] + + +class BypassFxGraphCache(Exception): + """ + Exception to indicate that the FxGraphCache should be bypassed. + """ + + +@dataclasses.dataclass(frozen=True) +class CacheabilityValidator: + """ + Centralized validation for deciding whether an FX graph can use the cache. + + The cache key pickler still defends itself when serializing arbitrary objects, + but non-cacheable inputs should be rejected here before hashing starts. + """ + + gm: torch.fx.GraphModule + example_inputs: Sequence[InputType] = () + fx_kwargs: _CompileFxKwargs | None = None + require_shape_env: bool = True + shape_env: ShapeEnv | None = None + + def validate(self) -> None: + self._check_custom_passes() + self._check_nested_region_inductor_config_patches() + self._check_frozen_params() + self._check_runtime_constant_folding() + self._check_compiler_bisector() + self._check_shape_env() + self.validate_graph(include_constants=True) + self._check_cache_key_object(self.example_inputs) + if self.fx_kwargs is not None: + self._check_cache_key_object(self.fx_kwargs) + + def validate_graph(self, include_constants: bool) -> None: + for module in self.gm.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in module.graph.nodes: + if ( + isinstance(node.target, torch._ops.HigherOrderOperator) + and not node.target.cacheable() + ): + self.bypass( + f"Can't cache HigherOrderOperator: {node.target.name()}" + ) + # TODO: this check is broken in two ways: + # 1. FX uses "get_attr" (with underscore), not "getattr" + # 2. It only checks for ScriptObject, not FakeScriptObject + # Fixing it would also bypass AOTAutogradCache (which calls + # _check_can_cache), so we'd need to decouple the two first. + if node.op == "getattr" and isinstance( + getattr(self.gm, node.target), torch._C.ScriptObject + ): + self.bypass("Can't cache torchbind objects") + if include_constants and node.op == "get_attr": + try: + attr = self._get_attr(module, node.target) + except AttributeError: + continue + self._check_cache_key_object(attr) + + @staticmethod + def check_tensor(t: Tensor) -> None: + if t.is_mkldnn: + CacheabilityValidator.bypass("mkldnn tensors unpickleable") + + @staticmethod + def bypass(reason: str) -> NoReturn: + raise BypassFxGraphCache(reason) + + @staticmethod + def bypass_for_pickle_error(e: Exception) -> NoReturn: + log.warning( + "Failed to pickle cache key", + exc_info=(type(e), e, e.__traceback__), + ) + raise BypassFxGraphCache("Failed to pickle cache key") from e + + @staticmethod + def _get_attr(module: torch.fx.GraphModule, target: str) -> Any: + from torch.fx.graph_module import _get_attr + + return _get_attr(module, target) + + def _check_custom_passes(self) -> None: + # Custom passes must implement the CustomGraphPass or we don't + # know how to include them in the cache key calculation. + # When timing is EARLY, pre-grad passes already ran before the cache + # lookup so there's nothing to validate here. + if resolve_pre_grad_pass_timing() != "early": + for p in get_custom_graph_passes(config.pre_grad_custom_pass): + if not isinstance(p, CustomGraphPass) or not p.uuid(): + self.bypass("Unsupported pre grad custom pass") + for p in itertools.chain( + get_custom_graph_passes(config.post_grad_custom_pre_pass), + get_custom_graph_passes(config.post_grad_custom_post_pass), + ): + if not isinstance(p, CustomGraphPass) or not p.uuid(): + self.bypass("Unsupported post grad custom pass") + # Same with the joint custom passes + for p in itertools.chain( + get_custom_graph_passes(config.joint_custom_pre_pass), + get_custom_graph_passes(config.joint_custom_post_pass), + ): + if not isinstance(p, CustomGraphPass) or not p.uuid(): + self.bypass("Unsupported joint custom pass") + # We should find any users of _pre_fusion_custom_pass and _fuse_ddp_communication_passes + # and ensure they are not passing us raw callables + if config._pre_fusion_custom_pass is not None: + if not isinstance(config._pre_fusion_custom_pass, CustomSchedulerPass): + self.bypass("Unsupported _pre_fusion_custom_pass") + if config._post_fusion_custom_pass is not None: + if not isinstance(config._post_fusion_custom_pass, CustomSchedulerPass): + self.bypass("Unsupported _post_fusion_custom_pass") + for p in config._fuse_ddp_communication_passes: + if callable(p) and not isinstance(p, CustomGraphPass): + self.bypass("Unsupported _fuse_ddp_communication_pass") + + def _check_nested_region_inductor_config_patches(self) -> None: + # Nested region config patches are hashed by pickling their raw value + # (see _collect_nested_region_inductor_config_patches_for_hash). Unlike + # top-level custom passes there is no uuid() fallback, so any callable or + # custom-pass value is conservatively treated as uncacheable, including a + # CustomGraphPass that provides a stable uuid(). + for _, config_patches in _collect_nested_region_inductor_config_patches( + self.gm + ): + for key, value in config_patches.items(): + # A value may be a list of callables (e.g. + # _fuse_ddp_communication_passes), so look inside sequences too. + values = value if isinstance(value, (list, tuple)) else (value,) + if any(callable(v) for v in values): + self.bypass( + f"Uncacheable nested region config '{key}': callable value" + ) + if key in _NESTED_REGION_UNCACHEABLE_CONFIG_KEYS and value: + self.bypass( + f"Uncacheable nested region config '{key}': custom pass" + ) + + def _check_frozen_params(self) -> None: + # Freezing can embed constants that wouldn't be static across runs. + if has_frozen_params(self.gm) and not torch._utils_internal.justknobs_check( + "pytorch/inductor:allow_freezing_with_caching" + ): + self.bypass("Skipping graph with frozen constants") + + def _check_runtime_constant_folding(self) -> None: + if config.aot_inductor.use_runtime_constant_folding: + self.bypass( + "Runtime constant folding can introduce constants that aren't " + "static across runs" + ) + + def _check_compiler_bisector(self) -> None: + from torch._inductor.compiler_bisector import CompilerBisector + + if CompilerBisector.bisection_enabled: + log.debug("don't cache graph when bisect enabled") + self.bypass("compiler bisector enabled") + + def _check_shape_env(self) -> None: + # The treatment of guards in the caching implementation requires that + # we have a shape env. + if self.require_shape_env and self.shape_env is None: + log.debug("fx graph cache no shape env") + self.bypass("No shape env") + + def _check_cache_key_object( + self, + obj: Any, + seen: set[int] | None = None, # noqa: set_linter + ) -> None: + if seen is None: + seen = set() # noqa: set_linter + + obj_id = id(obj) + if obj_id in seen: + return + seen.add(obj_id) + + if isinstance(obj, torch.Tensor): + self.check_tensor(obj) + return + elif isinstance(obj, torch.fx.experimental._backward_state.BackwardState): + self.bypass("Reduce unsupported") + elif isinstance(obj, dict): + for key, value in obj.items(): + self._check_cache_key_object(key, seen) + self._check_cache_key_object(value, seen) + elif isinstance(obj, (list, tuple, AbstractSet)): + for item in obj: + self._check_cache_key_object(item, seen) + + +_warned_pre_grad_pass_missing_uuid: OrderedSet[str] = OrderedSet() + + +def _custom_pass_has_uuid(custom_pass: Any) -> bool: + return isinstance(custom_pass, CustomGraphPass) and custom_pass.uuid() is not None + + +def _custom_pass_name(custom_pass: Any) -> str: + return getattr(custom_pass, "__qualname__", None) or type(custom_pass).__qualname__ + + +def resolve_pre_grad_pass_timing() -> Literal["early", "late"]: + """Resolve the effective pre-grad pass timing from the config. + + "default" is resolved based on whether the custom pass provides a UUID: + passes with a UUID (or no custom pass) run "late" (after cache lookup), + passes without a UUID run "early" (before cache lookup). + + Raises RuntimeError if a custom pass without a UUID is explicitly set to + run "late", since the cache key cannot account for it. + """ + timing: Literal["early", "late", "default"] = config.pre_grad_pass_timing + custom_passes = get_custom_graph_passes(config.pre_grad_custom_pass) + passes_missing_uuid = [ + custom_pass + for custom_pass in custom_passes + if not _custom_pass_has_uuid(custom_pass) + ] + missing_uuid_pass_names = ( + ", ".join(_custom_pass_name(custom_pass) for custom_pass in passes_missing_uuid) + if passes_missing_uuid + else "" + ) + + if timing == "default": + supports_late = not passes_missing_uuid + timing = "late" if supports_late else "early" + if timing == "early" and custom_passes: + if missing_uuid_pass_names not in _warned_pre_grad_pass_missing_uuid: + _warned_pre_grad_pass_missing_uuid.add(missing_uuid_pass_names) + log.warning( + "pre_grad_custom_pass %s does not implement uuid(); " + "falling back to early timing (pre-grad pass cache will be bypassed). " + "Implement uuid() on your CustomGraphPass to enable caching.", + missing_uuid_pass_names, + ) + CompileEventLogger.try_add_pt2_compile( + "backend_compile", + pre_grad_pass_missing_uuid=True, + pre_grad_pass_name=missing_uuid_pass_names, + ) + + if timing == "late" and passes_missing_uuid: + raise RuntimeError( + f"pre_grad_custom_pass {missing_uuid_pass_names} must implement uuid() to run late " + "(after cache lookup). Either implement uuid() or set " + "pre_grad_pass_timing to 'early'." + ) + + return timing + + +@dataclasses.dataclass +class HashableOpaqueValue: + ordinal: int + + +_NESTED_REGION_UNCACHEABLE_CONFIG_KEYS = OrderedSet( + [ + "custom_partitioner_fn", + "joint_custom_post_pass", + "joint_custom_pre_pass", + "post_grad_custom_post_pass", + "post_grad_custom_pre_pass", + "pre_grad_custom_pass", + "_post_fusion_custom_pass", + "_pre_fusion_custom_pass", + ] +) + + +def _collect_nested_region_inductor_config_patches( + gm: torch.fx.GraphModule, +) -> tuple[tuple[str, dict[str, Any]], ...]: + patches: list[tuple[str, dict[str, Any]]] = [] + + def add_patches(name: str, nested_config: Any) -> None: + config_patches = getattr(nested_config, "inductor_config_patches", None) + if config_patches: + patches.append((name, config_patches)) + + for name, module in gm.named_modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + add_patches(name, getattr(module, "meta", {}).get("nested_region_config")) + for node in module.graph.find_nodes( + op="call_function", target=torch.ops.higher_order.invoke_subgraph + ): + add_patches( + f"{name}.{node.name}", + node.meta.get("custom", {}).get("nested_region_config"), + ) + return tuple(patches) + + +def _collect_nested_region_inductor_config_patches_for_hash( + gm: torch.fx.GraphModule, +) -> tuple[tuple[str, tuple[tuple[str, Any], ...]], ...]: + return tuple( + ( + name, + tuple((key, config_patches[key]) for key in sorted(config_patches)), + ) + for name, config_patches in _collect_nested_region_inductor_config_patches(gm) + ) + + +class FxGraphHashDetails: + """ + Object to capture all the details for a compiled FX graph relevant to computing + a safe and stable cache key. + """ + + # Excluded kwargs param that are not stable between runs or that + # don't affect compiled output (like compile_region_name which is + # just a debug label). + EXCLUDED_KWARGS = ["graph_id", "compile_region_name"] + TENSOR_METADATA_KEYS = ("val", "example_value") + LIKE_FACTORY_TARGETS = ( + torch.empty_like, + torch.full_like, + torch.ones_like, + torch.rand_like, + torch.randint_like, + torch.randn_like, + torch.zeros_like, + ) + LIKE_FACTORY_PACKETS = ( + torch.ops.aten.empty_like, + torch.ops.aten.full_like, + torch.ops.aten.ones_like, + torch.ops.aten.rand_like, + torch.ops.aten.randint_like, + torch.ops.aten.randn_like, + torch.ops.aten.zeros_like, + ) + + @classmethod + def _contains_tensor(cls, value: Any) -> bool: + if isinstance(value, torch.Tensor): + return True + if isinstance(value, (list, tuple, OrderedSet, frozenset)): + return any(cls._contains_tensor(x) for x in value) + if isinstance(value, dict): + return any( + cls._contains_tensor(x) + for x in itertools.chain(value.keys(), value.values()) + ) + return False + + @classmethod + def _contains_cpu_tensor(cls, value: Any) -> bool: + if isinstance(value, torch.Tensor): + return value.device.type == "cpu" + if isinstance(value, (list, tuple, OrderedSet, frozenset)): + return any(cls._contains_cpu_tensor(x) for x in value) + if isinstance(value, dict): + return any( + cls._contains_cpu_tensor(x) + for x in itertools.chain(value.keys(), value.values()) + ) + return False + + @staticmethod + def _device_type(value: Any) -> str | None: + if isinstance(value, torch.device): + return value.type + if isinstance(value, str): + try: + return torch.device(value).type + except RuntimeError: + return None + return None + + @classmethod + def _is_factory_target( + cls, target: Any, targets: tuple[Any, ...], packets: tuple[Any, ...] + ) -> bool: + if target in targets or target in packets: + return True + overload_packet = getattr(target, "overloadpacket", None) + return overload_packet in packets + + @classmethod + def _tensor_metadata(cls, node: torch.fx.Node) -> tuple[Any, ...]: + return tuple( + node.meta[key] for key in cls.TENSOR_METADATA_KEYS if key in node.meta + ) + + @classmethod + def _factory_device_type(cls, node: torch.fx.Node) -> str | None: + if node.op != "call_function": + return None + + is_default_device_factory = cls._is_factory_target( + node.target, + _default_device_constructor_targets(), + _default_device_constructor_overload_packets(), + ) + is_like_factory = cls._is_factory_target( + node.target, + cls.LIKE_FACTORY_TARGETS, + cls.LIKE_FACTORY_PACKETS, + ) + if not (is_default_device_factory or is_like_factory): + return None + + device_type = cls._device_type(node.kwargs.get("device")) + if device_type is not None: + return device_type + + schema = getattr(node.target, "_schema", None) + if schema is not None: + for arg, value in zip(schema.arguments, node.args): + if arg.name == "device": + device_type = cls._device_type(value) + if device_type is not None: + return device_type + + if is_like_factory: + return None + return torch.device(torch.get_default_device()).type + + @classmethod + def _may_generate_cpu_cpp_code( + cls, gm: torch.fx.GraphModule | None, example_inputs: Sequence[InputType] + ) -> bool: + if cls._contains_cpu_tensor(example_inputs): + return True + if gm is None: + return False + for module in gm.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in module.graph.nodes: + tensor_metadata = cls._tensor_metadata(node) + if cls._contains_cpu_tensor(tensor_metadata): + return True + if not cls._contains_tensor(tensor_metadata) and ( + cls._factory_device_type(node) == "cpu" + ): + return True + return False + + def __init__( + self, + gm: torch.fx.GraphModule | None, + example_inputs: Sequence[InputType], + fx_kwargs: _CompileFxKwargs, + inputs_to_check: Sequence[int], + ) -> None: + self.gm = gm + # Replace opaque references with hashable ordinals. What's important + # is that if the same reference appears twice then it's the same hash + # value for each. + processed_inputs: list[InputType | HashableOpaqueValue] = [] + seen_opaques: dict[int, HashableOpaqueValue] = {} + for inp in example_inputs: + if is_opaque_symbolic_type(type(inp)): + if id(inp) not in seen_opaques: + seen_opaques[id(inp)] = HashableOpaqueValue(len(seen_opaques)) + processed_inputs.append(seen_opaques[id(inp)]) + else: + processed_inputs.append(inp) + self.example_inputs = processed_inputs + self.cache_key_tag = cconfig.cache_key_tag + self.nested_inductor_config_patches = ( + _collect_nested_region_inductor_config_patches_for_hash(gm) + if gm is not None + else () + ) + + # Order kwargs so hashing is stable to changes in kwarg order. Although + # it's technically a _CompileFxKwargs we don't actually need it typed as + # such since we're just using it to generate a hash. + self.fx_kwargs: dict[str, object] = {} + for k, v in sorted(fx_kwargs.items()): + if k not in self.EXCLUDED_KWARGS: + if type(v) in (set, OrderedSet): # noqa: set_linter + # Special case to handle set params. Python sets can't be + # ordered, so sort the elements and store them in a proxy. + self.fx_kwargs[k] = OrderedSetHolder(sorted(v)) # type: ignore[call-overload] + else: + self.fx_kwargs[k] = v + + from torch._higher_order_ops.triton_kernel_wrap import ( + kernel_side_table, + triton_kernel_wrapper_functional, + triton_kernel_wrapper_mutation, + ) + from torch._inductor.codegen.wrapper import ( + user_defined_triton_kernel_transitive_closure_source_code, + ) + + # Node meta will not be part of gm's reduce function, so lets remember + # the kernel source code separately + self.user_defined_triton_source: list[Any] = [] + if gm is not None: + for module in gm.modules(): + if not isinstance(module, torch.fx.GraphModule): + continue + for node in itertools.chain( + module.graph.find_nodes( + op="call_function", target=triton_kernel_wrapper_functional + ), + module.graph.find_nodes( + op="call_function", target=triton_kernel_wrapper_mutation + ), + ): + from triton.runtime.autotuner import Autotuner + + kernel = kernel_side_table.get_kernel(node.kwargs["kernel_idx"]) + configs = None + if isinstance(kernel, Autotuner): + if kernel.configs: + configs = str( + sorted( + sorted(str(kv) for kv in c.all_kwargs().items()) + for c in kernel.configs + ) + ) + kernel = kernel.fn + + kernel_source = ( + user_defined_triton_kernel_transitive_closure_source_code( + kernel + ) + ) + constant_args = kernel_side_table.get_constant_args( + node.kwargs["constant_args_idx"] + ) + self.user_defined_triton_source.append( + (kernel_source, constant_args, configs) + ) + + no_tensor_inputs = not any(isinstance(x, torch.Tensor) for x in example_inputs) + # This device index is usually already encoded by the device of the inputs + # but fx graphs don't necessarily have tensor inputs. If there aren't any, + # we need to guard on the device index in case we allocate cuda tensors + if no_tensor_inputs and torch.accelerator.is_available(): + self.default_cuda_device_index = torch.accelerator.current_device_index() + + # 'Deterministic algorithms' can affect codegen via lowering to cuda kernels. + self.deterministic_algorithms_settings = ( + torch.are_deterministic_algorithms_enabled(), + torch.is_deterministic_algorithms_warn_only_enabled(), + torch.utils.deterministic.fill_uninitialized_memory, # type: ignore[attr-defined] + ) + + # CPU C++ kernels specialize on torch.get_num_threads() when cpp.threads + # is left at its runtime default and dynamic threading is disabled. + # Include that resolved value so FX graph cache entries compiled under + # one thread count are not reused under another. + if ( + config.cpp.threads < 1 + and not config.cpp.dynamic_threads + and self._may_generate_cpu_cpp_code(gm, example_inputs) + ): + self.cpp_runtime_thread_count = parallel_num_threads() + + # Provenance tracking level affects whether provenance data is stored + # in the CompiledFxGraph, so it must be part of the cache key. + # Note: the "trace" prefix is excluded from _cache_config_ignore_prefix, + # so we add this explicitly. + self.provenance_tracking_level = config.effective_provenance_tracking_level() + self.provenance_tracking_to_timeline = ( + config.trace.provenance_tracking_to_timeline + ) + + # Factory ops with dtype=None are lowered using the ambient default dtype, + # so cached code compiled under one default dtype is not valid under another. + self.default_dtype = torch.get_default_dtype() + + # Global settings affecting matmul codegen. + self.cuda_matmul_settings = ( + torch.backends.cuda.matmul.fp32_precision, + torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction, + torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction, + ) + + # compile-on-one-rank changes wrapper and kernel codegen (runtime device + # resolution, DeviceProperties(index=None)) even for graphs that contain no + # coor::current_device node, so an entry compiled with it off must not be served + # to a compile with it on -- that would hand back the device-baked artifact CooR + # exists to avoid. + from torch.fx.experimental.proxy_tensor import _coor_enabled + + self.compile_on_one_rank = _coor_enabled() + + # Include cudagraph annotation in cache key only when it changes + # behavior. When both fwd and bwd are overridden to the same value, + # normalize to a simple boolean (equivalent to flipping the config). + # When fwd and bwd differ, include the full annotation. + if gm is not None: + annotation = gm.meta.get("cudagraph_annotation") + if annotation is not None: + default = config.triton.cudagraphs + if annotation.fwd == annotation.bwd and annotation.fwd is not None: + if annotation.fwd != default: + self.cudagraph_override = annotation.fwd + elif (annotation.fwd is not None and annotation.fwd != default) or ( + annotation.bwd is not None and annotation.bwd != default + ): + self.cudagraph_annotation = annotation + + # Also hash on various system info (including the triton compiler version). + self.torch_version = torch_key() + self.system_info = CacheBase.get_system() + self.inductor_config = config.save_config_portable( + ignore_private_configs=False, readonly_values=True + ) + # pyrefly: ignore [missing-attribute] + self.inductor_config_comms = config_comms.save_config_portable( + ignore_private_configs=False, readonly_values=True + ) + + # Custom passes should provide an ID to hash when they run late (after cache lookup). + if resolve_pre_grad_pass_timing() != "early": + self.pre_grad_custom_pass = self._get_custom_pass_detail( + config.pre_grad_custom_pass + ) + self.post_grad_custom_pre_pass = self._get_custom_pass_detail( + config.post_grad_custom_pre_pass + ) + # TODO: change to more holistic config rather than bundled_autograd_cache + self.precompile_enabled = torch._functorch.config.bundled_autograd_cache + self.post_grad_custom_post_pass = self._get_custom_pass_detail( + config.post_grad_custom_post_pass + ) + self.joint_custom_pre_pass = self._get_custom_pass_detail( + config.joint_custom_pre_pass + ) + self.joint_custom_post_pass = self._get_custom_pass_detail( + config.joint_custom_post_pass + ) + self._pre_fusion_custom_pass = self._get_custom_pass_detail_unsafe( + config._pre_fusion_custom_pass + ) + self._post_fusion_custom_pass = self._get_custom_pass_detail_unsafe( + config._post_fusion_custom_pass + ) + self._fuse_ddp_communication_passes = self._get_custom_pass_detail_unsafe( + config._fuse_ddp_communication_passes + ) + + # Register inductor backends and custom passes and get their UUIDs. + init_backend_registration() + self.custom_backend_passes = tuple( + map(self._get_custom_pass_detail, custom_backend_passes.values()) + ) + + # Save custom inductor codegen configs + self.custom_backend_codegen_configs = { + device: custom_config.save_config_portable( + ignore_private_configs=False, readonly_values=True + ) + for device, custom_config in custom_backend_codegen_configs.items() + if custom_config is not None + } + + # Register the custom partitioner function + self._custom_partitioner_fn = self._get_custom_partitioner_fn_detail( + config.custom_partitioner_fn + ) + + # Include hint overrides in the cache key because _reduce_symint + # only hashes symbol names, not hint values. + self.var_to_hint_override: dict[str, int] = {} + shape_env = FxGraphCache._get_shape_env() + if shape_env is not None and shape_env.var_to_hint_override: + self.var_to_hint_override = { + str(sym): val + for sym, val in sorted( + shape_env.var_to_hint_override.items(), key=lambda x: str(x[0]) + ) + } + + # This is mainly added to handle these two inductor configs, which are (unfortunately) + # sometimes cache safe: + # - _pre_fusion_custom_pass + # - _post_fusion_custom_pass + # - _fuse_ddp_communication_passes + # Their types can be found in `torch/_inductor/config.py`, but: + # - if they are string names, we can cache them safely (one is by default) + # - if any of them are set to custom callables, we will need to cache miss + # Future work is for someone to find any places where these functions are used + # and force them to be of type CustomGraphPass, so we can guarantee serialization. + def _get_custom_pass_detail_unsafe(self, custom_pass: Any) -> Any | None: + if not custom_pass: + return None + if isinstance(custom_pass, list): + return [self._get_custom_pass_detail_unsafe(x) for x in custom_pass] + if isinstance(custom_pass, tuple): + return tuple(self._get_custom_pass_detail_unsafe(x) for x in custom_pass) + if isinstance(custom_pass, str): + return custom_pass + if isinstance(custom_pass, CustomPassBase): + return custom_pass.uuid() + if callable(custom_pass): + # Returning None is safe here because we raise an explicit bypass error + # later if we detect these passes are set to callables + return None + raise AssertionError(f"unknown config type: {str(type(custom_pass))}") + + def _get_custom_pass_detail( + self, + custom_pass: ( + CustomGraphPassCallable + | list[CustomGraphPassCallable] + | tuple[CustomGraphPassCallable, ...] + | CustomGraphModulePass + | None + ), + ) -> Any | None: + if not custom_pass: + # Empty custom-pass lists mean no passes, matching None. + return None + if isinstance(custom_pass, (list, tuple)): + return tuple(self._get_custom_pass_detail(x) for x in custom_pass) + if not isinstance(custom_pass, (CustomGraphPass, CustomGraphModulePass)): + raise AssertionError(f"unknown custom pass type: {str(type(custom_pass))}") + return custom_pass.uuid() + + def _get_custom_partitioner_fn_detail( + self, custom_partitioner_fn: CustomPartitionerFnType + ) -> Any | None: + if not custom_partitioner_fn: + return None + if not isinstance(custom_partitioner_fn, CustomPartitionerFn): + raise AssertionError( + f"Expected CustomPartitionerFn, got {type(custom_partitioner_fn)}" + ) + return custom_partitioner_fn.uuid() + + +def compiled_fx_graph_hash( + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType], + fx_kwargs: _CompileFxKwargs, + inputs_to_check: Sequence[int], +) -> tuple[str, list[str]]: + """ + Generate a unique hash of the FX graph for caching. + """ + details = FxGraphHashDetails(gm, example_inputs, fx_kwargs, inputs_to_check) + has_user_defined_triton_kernels = len(details.user_defined_triton_source) != 0 + pickler = FxGraphCachePickler(gm, has_user_defined_triton_kernels) + + # The prefix distinguishes among the other kinds of objects we + # cache in this module. + key = pickler.get_key(details) + debug_lines = pickler.debug_lines(details) + debug_str = "\n".join(debug_lines) + log.debug(f"FX graph cache hash details for key {key}:\n{debug_str}") # noqa: G004 + return key, debug_lines + + +def add_ephemeral_timeout_increase_for_distributed(time_saved_ns: int) -> int: + """ + Ephemerally increases the NCCL timeout when compiling for a distributed job + Returns amount of seconds increased + """ + if not torch.distributed.is_available() or not torch.distributed.is_initialized(): + return 0 + + increased_timeout_sec = int(time_saved_ns // 1e9) # convert to seconds + + if config.is_fbcode(): + fudge_factor = torch._utils_internal.justknobs_getval_int( + "pytorch/remote_cache:ephemeral_timeout_fudge_factor_percentage" + ) + log.info( + "Ephemeral NCCL timeout increase fudge factor %d and original increase value %d", + fudge_factor, + increased_timeout_sec, + ) + increased_timeout_sec += int(increased_timeout_sec * fudge_factor / 100) + + log.info("Increasing NCCL timeout by %d", increased_timeout_sec) + dist.distributed_c10d._add_ephemeral_timeout_for_all_pgs( + timedelta(seconds=increased_timeout_sec) + ) + return increased_timeout_sec + + +class GuardedCache(Generic[T]): + """ + Mixin for caches that have guards associated with their entries. + """ + + @classmethod + def _get_tmp_dir_for_key(cls: type[GuardedCache[T]], _key: str) -> str: + raise NotImplementedError("Implement _get_tmp_dir_for_key on parent class") + + @classmethod + def _record_result( + cls: type[GuardedCache[T]], + key: str, + local_hit: bool, + local_miss: bool, + remote_hit: bool, + remote_miss: bool, + ) -> None: + raise NotImplementedError("Implement _record_result on parent class") + + @classmethod + def iterate_over_candidates( + cls: type[GuardedCache[T]], + local: bool, + remote_cache: RemoteCache[JsonDataTy] | None, + key: str, + ) -> Generator[tuple[T, bytes, bool], None, None]: + if local: + subdir = cls._get_tmp_dir_for_key(key) + if os.path.exists(subdir): + for path in sorted(os.listdir(subdir)): + if path.startswith("."): + continue # Skip temp files from concurrent write_atomic() calls + try: + with open(os.path.join(subdir, path), "rb") as f: + content = f.read() + yield pickle.loads(content), content, True + except Exception: + log.warning( + "fx graph cache unable to load compiled graph", + exc_info=True, + ) + + if remote_cache: + try: + if (cache_data := remote_cache.get(key)) is not None: + if not isinstance(cache_data, dict): + raise AssertionError( + f"Expected dict from remote cache, got {type(cache_data)}" + ) + data = cache_data["data"] + if not isinstance(data, (str, bytes)): + raise AssertionError( + f"Expected str or bytes for cache data, got {type(data)}" + ) + content = base64.b64decode(data) + yield pickle.loads(content), content, False + except Exception: + log.warning( + "%s unable to load compiled graph", cls.__name__, exc_info=True + ) + + @classmethod + def find_guarded_entry( + cls: type[GuardedCache[T]], + key: str, + local: bool, + remote_cache: RemoteCache[JsonDataTy] | None, + evaluate_guards: Callable[[str, list[int] | list[torch.SymInt]], bool], + hints: list[int], + ) -> tuple[T | None, bytes | None, CacheInfo]: + """ + Find the first cache entry in iterate_over_candidates that passes `evaluate_guards`. + + Args: + key: The cache key to look up + local: Whether to check the local cache + remote_cache: The remote cache to check, if any + evaluate_guards: Function that evaluates whether a guard passes the check, + given a list of hint values and the guard expression. + hints: List of symint hints paired with evaluate_guards + + Returns: + A tuple of (graph, pickled_content) if found, or (None, None) if not found + """ + graph = None + pickled_content = None + result_status = "full_miss" + sample_guards_expr = None + in_local = False + + # Iterate over any entries in the subdir for this key and evaluate + # guards to determine whether there's a hit. + + for candidate, content, in_local in cls.iterate_over_candidates( + local, remote_cache, key + ): + if not hasattr(candidate, "guards_expr"): + raise AssertionError( + f"Cache candidate {type(candidate)} missing 'guards_expr' attribute" + ) + if not candidate.guards_expr: # type: ignore[attr-defined] + # No guards to evaluate, so this is a hit. + graph = candidate + pickled_content = content + result_status = "hit" + break + + # Evaluate the guard expression in the current context. + # If there's not a cache hit, we don't want the evaluation to + # affect the current env, e.g., cause the creation of new guards, + # so we evaluate with the hints instead of the symbols. + hit = bool(evaluate_guards(candidate.guards_expr, hints)) # type: ignore[attr-defined] + if hit: + graph = candidate + pickled_content = content + result_status = "hit" + sample_guards_expr = candidate.guards_expr + break + else: + # At least one guard missed, log this + result_status = "guard_miss" + sample_guards_expr = candidate.guards_expr + + info: CacheInfo = {"cache_status_detailed": result_status} + if sample_guards_expr is not None: + info["cache_status_guard_expr"] = sample_guards_expr + + # Record hits/misses for compilation event logging. The tricky part is that a + # remote hit would imply a local miss (if local caching is enabled). + local_hit = graph is not None and in_local + remote_hit = graph is not None and not in_local + local_miss = (graph is None or remote_hit) and local + remote_miss = graph is None and remote_cache is not None + cls._record_result( + key, + local_hit=local_hit, + local_miss=local_miss, + remote_hit=remote_hit, + remote_miss=remote_miss, + ) + + return graph, pickled_content, info + + @classmethod + def _filter_backed_symints( + cls: type[GuardedCache[T]], inputs: Sequence[InputType] + ) -> list[torch.SymInt]: + """ + Get the backed SymInt objects from the input list. Note that we can never + have guards that depend on unbacked symint. + """ + return [ + s for s in inputs if isinstance(s, torch.SymInt) and has_guarding_hint(s) + ] + + @classmethod + def _get_shape_env(cls: type[GuardedCache[T]]) -> ShapeEnv | None: + """ + Helper to get the shape env from the tracing context. + """ + ctx = torch._guards.TracingContext.try_get() + if not ctx or not ctx.fake_mode: + return None + return ctx.fake_mode.shape_env + + +@CacheArtifactFactory.register +class InductorCacheArtifact(CacheArtifact): + @override + def populate_cache(self) -> None: + FxGraphCache._write_to_local_cache(self.key, self.content) + + @override + @staticmethod + def type() -> str: + return "inductor" + + +class FxGraphCache(GuardedCache[CompiledFxGraph]): + """ + Supports caching and reusing compiled Fx graphs. + + The overall strategy is as follows: + - This cache stores entries on disk. When saving an entry, we can't + serialize callables (that could be C++, Triton, etc.), so we serialize + their own disk cache location. We then recreate the compiled artifact + after fetching from disk. + - For indexing the cache, we gather the fields relevant to identifying an + FxGraph (the graph module, graph inputs, system settings etc.) into an + FxGraphCacheDetails object, pickle it, and compute a hash for the key. + See FxGraphCachePickler. + - Among the metadata we store, we also include a guards expression that's + appropriate for validating any symbols for Tensor arguments that have + symbolic bounds. On cache lookup then, we evaluate those guards in the + current context to validate that a cached entry can be served. + - A given graph could have multiple compiled versions, corresponding to + different sets of guards. Therefore, we store cache entries in the form: + // + - On lookup, we compute the key from the graph details, iterate over all + leaf files in the corresponding subdirectory, deserialize the entry, and + evaluate its guards expression. If the evaluation succeeds, we have a + cache hit. If it fails, we compile the graph and store a new entry. + - Finally, on a cache hit, we need to make sure any guards that would + have been created during compilation are added to the current context. + """ + + # TODO(masnesral): Investigate whether it's beneficial to store compiled graphs + # in an in-memory cache after loading from disk. + @staticmethod + def _get_tmp_dir() -> str: + """ + Get the toplevel temporary directory for storing compiled graphs. + """ + return os.path.join(cache_dir(), "fxgraph") + + @classmethod + def _get_tmp_dir_for_key(cls: type[FxGraphCache], key: str) -> str: + """ + Return the disk location for a given cache key. + """ + return os.path.join(FxGraphCache._get_tmp_dir(), key[1:3], key) + + @classmethod + def _record_result( + cls: type[FxGraphCache], + key: str, + local_hit: bool, + local_miss: bool, + remote_hit: bool, + remote_miss: bool, + ) -> None: + """ + Called by GuardedCache to record hit/miss statistics. + """ + if local_hit: + cache_stats.hit("LocalFxGraphCache") + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "inductor_fx_local_cache_hit_count", + ) + if remote_hit: + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "inductor_fx_remote_cache_hit_count", + ) + CompileEventLogger.try_( + CompileEventLogger.add_to_set_toplevel, + "inductor_fx_remote_cache_hit_keys", + key, + ) + if local_miss: + cache_stats.miss("LocalFxGraphCache") + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "inductor_fx_local_cache_miss_count", + ) + if remote_miss: + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "inductor_fx_remote_cache_miss_count", + ) + CompileEventLogger.try_( + CompileEventLogger.add_to_set_toplevel, + "inductor_fx_remote_cache_miss_keys", + key, + ) + + @staticmethod + def cache_hit_post_compile( + graph: CompiledFxGraph, + cache_info: CacheInfo, + constants: CompiledFxGraphConstants, + ) -> tuple[CompiledFxGraph | None, CacheInfo]: + """ + Cache specific post compile steps that need to run if we find a graph in the cache + This includes putting bundled triton artifacts in the right place, + reloading the PyCodeCache artifact, etc. + + These don't always happen (i.e. on a cache miss, so they are in a separate function from + CompiledFxGraph.post_compile) + """ + if bundle := graph._triton_bundle: + triton_bundler_meta = TritonBundler.read_and_emit(bundle) + if (meta := triton_bundler_meta) is not None: + cache_info["triton_bundler_meta"] = str(meta) + CompileEventLogger.try_add_pt2_compile( + "inductor_compile", cached_kernel_names=meta.cached_kernel_names + ) + CompileEventLogger.try_add_pt2_compile( + "AOTAutogradCache.inductor_load", + cached_kernel_names=meta.cached_kernel_names, + ) + if len(meta.cached_kernel_names) > 0: + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, "num_triton_bundles" + ) + + try: + artifact_path = graph.after_deserialization(constants) + + from .graph import GraphLowering + + # This is used by tests to check the output for specific details. + if GraphLowering.save_output_code is not None: + GraphLowering.save_output_code(graph.source_code) + + except OSError: + # Not expected, but in case the PyCodeCache entry is removed from + # underneath us, treat it as a cache miss and recompile. + return None, cache_info + + inductor_meta = autotune_cache.inductor_meta_from_config() + code = graph.source_code + AutotuneCacheBundler.begin_compile(inductor_meta, code=code) + graph._set_compile_context_for_autotune_cache() + + # Increment the cached metrics/counters by the amounts recorded when the FX + # graph was compiled for this cache entry. Pretending these counters + # were incremented normally is useful for testing with the cache enabled. + metrics.CachedMetricsHelper.apply_deltas(graph.metrics_deltas) + counters["inductor"] += graph.counter_deltas + + output_code_log.debug("Output code: \n%s", code) + output_code_log.debug("Output code written to: %s", artifact_path) + # On cache hit, use artifact path as filename + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "fx_graph_runnable", + "encoding": "string", + }, + payload_fn=lambda: graph.runnable_graph_str, + ) + trace_structured( + "inductor_post_grad_graph", + payload_fn=lambda: graph.inductor_post_grad_graph_str, + ) + trace_structured( + "inductor_output_code", + lambda: { + "filename": artifact_path, + "file_path": os.path.abspath(artifact_path), + }, + payload_fn=lambda: code, + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_provenance_tracking_node_mappings", + "encoding": "json", + }, + payload_fn=lambda: graph.inductor_provenance_mapping_str, + ) + trace_structured( + "artifact", + metadata_fn=lambda: { + "name": "inductor_provenance_tracking_kernel_stack_traces", + "encoding": "json", + }, + payload_fn=lambda: graph.inductor_provenance_stack_traces_str, + ) + if ( + get_metrics_context().in_progress() + and graph.inductor_provenance_stack_traces_str + ): + get_metrics_context().add_to_set( + "inductor_provenance", graph.inductor_provenance_stack_traces_str + ) + return graph, cache_info + + @staticmethod + def _lookup_graph( + key: str, + example_inputs: Sequence[InputType], + local: bool, + remote_cache: RemoteCache[JsonDataTy] | None, + constants: CompiledFxGraphConstants, + evaluate_guards: Callable[[str, list[int] | list[torch.SymInt]], bool] + | None = None, + ) -> tuple[CompiledFxGraph | None, CacheInfo]: + """ + Lookup a compiled graph in the cache by key. On a hit, return the + deserialized CompiledFxGraph object. On a miss, return None. + `constants` tracks a list of constants, or a way to obtain the list of constants + associated with a given cache entry + `evaluate_guards` allows AOTAutogradCache and other callers to customize + what constitutes a guard success. Normally, a guard hit happens if + `shape_env.evaluate_guards_expression` returns True. + """ + shape_env = FxGraphCache._get_shape_env() + if shape_env is None: + raise AssertionError("ShapeEnv is not set for guard evaluation") + + symints = FxGraphCache._filter_backed_symints(example_inputs) + hints = [guarding_hint_or_throw(s) for s in symints] + + # If this config is turned on, everything is a guard hit and we check nothing + if config.unsafe_skip_cache_dynamic_shape_guards: + # This also makes it so we don't add anything to the dynamic + # shape environment + evaluate_guards = lambda x, y: True # noqa: E731 + + if evaluate_guards is None: + evaluate_guards = shape_env.evaluate_guards_expression + + cache_info: CacheInfo = {} + + # Use the find_graph_for_key method to find a graph for the given key + graph, pickled_content, guard_info = FxGraphCache.find_guarded_entry( + key, local, remote_cache, evaluate_guards, hints + ) + cache_info.update(guard_info) + if graph is None: + return None, cache_info + + # Validate extern_libs (e.g. libdevice) match the current env. + if graph.extern_libs_key is not None: + try: + backend = torch.utils._triton.triton_backend() + current = torch.utils._triton._extern_libs_key(backend) + except Exception: + current = None + if current != graph.extern_libs_key: + cache_info["cache_status_detailed"] = "guard_miss" + return None, cache_info + + CacheArtifactRecorder(InductorCacheArtifact.type(), key).record_if_present( + pickled_content + ) + + # Now re-evaluate with the symints to add any guards to the current env. + if graph.guards_expr: + check = bool(evaluate_guards(graph.guards_expr, symints)) + if check is not True: + raise AssertionError(f"expected check to be True, got {check}") + log.debug( + "fx graph cache key %s post-load guards: %s", key, shape_env.guards + ) + + return FxGraphCache.cache_hit_post_compile(graph, cache_info, constants) + + @staticmethod + def _write_to_local_cache(key: str, content: bytes) -> None: + subdir = FxGraphCache._get_tmp_dir_for_key(key) + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + + # Use a hash of the serialized CompiledFxGraph to get a unique file + # name. The specific name doesn't matter since a lookup involves + # iterating over all entries in the parent subdir. + path = os.path.join(subdir, sha256_hash(content)) + write_atomic(path, content, make_dirs=True) + + @staticmethod + def _save_graph( + key: str, + compiled_graph: OutputCode, + example_inputs: Sequence[InputType], + local: bool, + remote_cache: RemoteCache[JsonDataTy] | None, + ) -> None: + """ + Store a serialized CompiledFxGraph on disk. + """ + from .compile_fx import CompiledFxGraph + + if not isinstance(compiled_graph, CompiledFxGraph): + raise AssertionError(f"serialization for {type(compiled_graph)} NYI") + + # Before serializing, compute the guard expression that will be used to + # ensure that a CompiledFxGraph is valid when loaded from the cache. It's + # sufficient to consider only the SymInt args to the fx graph since the + # Tensor shapes are already captured in the hash for the cache key. Any + # Tensor arg with a symbolic shape will have a SymInt arg for the graph. + shape_env = FxGraphCache._get_shape_env() + if shape_env is None: + raise AssertionError("ShapeEnv is not set for cache serialization") + symints = FxGraphCache._filter_backed_symints(example_inputs) + guards = shape_env.get_pruned_guards(symints) + compiled_graph.guards_expr = shape_env.produce_guards_expression( + placeholders=symints, guards=guards + ) + try: + backend = torch.utils._triton.triton_backend() + compiled_graph.extern_libs_key = torch.utils._triton._extern_libs_key( + backend + ) + except Exception: + pass + disk_compiled_graph = copy(compiled_graph) + disk_compiled_graph.prepare_for_serialization() + + try: + content = pickle.dumps(disk_compiled_graph) + except Exception: + log.warning( + "fx graph cache unable to serialize compiled graph", exc_info=True + ) + counters["inductor"]["fxgraph_cache_pickle_error"] += 1 + return + + try: + CacheArtifactRecorder(InductorCacheArtifact.type(), key).record(content) + if local: + FxGraphCache._write_to_local_cache(key, content) + cache_stats.put("LocalFxGraphCache") + + if remote_cache: + time_taken_ms = int((disk_compiled_graph._time_taken_ns or 0) // 1e6) + cache_data: JsonDataTy = { + "data": base64.b64encode(content).decode("ascii"), + "time_taken_ms": time_taken_ms, + } + remote_cache.put(key, cache_data) + except Exception: + log.warning("fx graph unable to write to cache", exc_info=True) + counters["inductor"]["fxgraph_cache_write_error"] += 1 + + @staticmethod + def _check_for_hop(gm: torch.fx.GraphModule) -> None: + CacheabilityValidator(gm, require_shape_env=False).validate_graph( + include_constants=False + ) + + @staticmethod + def _check_can_cache( + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType] = (), + fx_kwargs: _CompileFxKwargs | None = None, + require_shape_env: bool = True, + ) -> None: + """ + Check some conditions that would preclude caching and raise BypassFxGraphCache + to bypass in case caching is not possible. + """ + shape_env = FxGraphCache._get_shape_env() if require_shape_env else None + CacheabilityValidator( + gm, + example_inputs=example_inputs, + fx_kwargs=fx_kwargs, + require_shape_env=require_shape_env, + shape_env=shape_env, + ).validate() + + @staticmethod + def prepare_key( + gm: torch.fx.GraphModule, + example_inputs: Sequence[InputType], + fx_kwargs: _CompileFxKwargs, + inputs_to_check: Sequence[int], + remote: bool, + ) -> tuple[tuple[str, list[str]] | None, CacheInfo]: + """ + Checks that the inductor input is cacheable, then computes + and returns the cache key for the input. + Returns (key_info, cache_info) where: + - key_info is (hash_key, debug_lines), and + - cache_info will contain debug info in the event of BypassFxGraphCache. + + NB: It is possible to have this function return a union instead. But + I personally believe it is more annoying/difficult to read in that format. + """ + try: + FxGraphCache._check_can_cache(gm, example_inputs, fx_kwargs) + key, debug_lines = compiled_fx_graph_hash( + gm, example_inputs, fx_kwargs, inputs_to_check + ) + except BypassFxGraphCache as e: + counters["inductor"]["fxgraph_cache_bypass"] += 1 + log.info("Bypassing FX Graph Cache because '%s'", e) + if remote: + log_cache_bypass("bypass_fx_graph", str(e)) + cache_info: CacheInfo = { + "cache_state": "bypass", + "cache_bypass_reason": str(e), + "cache_event_time": time_ns(), + } + return None, cache_info + # If key exists, then cache_info will come from load_with_key + return (key, debug_lines), {} + + @staticmethod + def get_remote_cache() -> RemoteCache[JsonDataTy] | None: + """ + Attempts to load the remote cache, returns None on error. + """ + cache_id = "fx-graph-v1" + return create_cache( + cache_id, + config.is_fbcode(), + "FbRemoteFxGraphCache", + "RemoteFxGraphCache", + ) + + @staticmethod + def load_with_key( + key: str, + debug_lines: list[str], + example_inputs: Sequence[InputType], + local: bool, + remote_cache: RemoteCache[JsonDataTy] | None, + is_backward: bool, + constants: CompiledFxGraphConstants, + evaluate_guards: Callable[[str, list[int] | list[torch.SymInt]], bool] + | None = None, + ) -> tuple[CompiledFxGraph | None, CacheInfo]: + """ + Lookup the graph with the given key, and return results and metadata. + Doesn't do any logging on its own, because AOTAutograd handles a cache miss + differently from FXGraphCache. + """ + compiled_graph, cache_info = FxGraphCache._lookup_graph( + key, example_inputs, local, remote_cache, constants, evaluate_guards + ) + cache_info: CacheInfo = { + **cache_info, + "key": key, + "components": debug_lines, + "cache_event_time": time_ns(), + } + if compiled_graph is not None: + log.info("fx graph cache hit for key %s", key) + counters["inductor"]["fxgraph_cache_hit"] += 1 + cache_info["cache_state"] = "hit" + + if (time_saved_ns := compiled_graph._time_taken_ns) is not None: + cache_info["time_saved_ns"] = time_saved_ns + CompileEventLogger.try_( + CompileEventLogger.increment_toplevel, + "distributed_ephemeral_timeout_us", + time_saved_ns // 1000, + ) + if ( + ephemeral_increase + := add_ephemeral_timeout_increase_for_distributed(time_saved_ns) + ) != 0: + cache_info["ephemeral_timeout_increase"] = ephemeral_increase + else: + log.info("fx graph cache miss for key %s", key) + counters["inductor"]["fxgraph_cache_miss"] += 1 + cache_info["cache_state"] = "miss" + + return compiled_graph, cache_info + + @staticmethod + def clear() -> None: + """ + Clear out the on-disk cache. + """ + try: + shutil.rmtree(FxGraphCache._get_tmp_dir()) + except FileNotFoundError: + pass + + +@functools.cache +def split_aot_inductor_output_path(path: str) -> tuple[str, str]: + def get_module_ext_type() -> str: + if _IS_WINDOWS: + return ".pyd" + else: + return ".so" + + """Returns the path where the AOT Inductor compiled kernels are stored.""" + if path.endswith(get_module_ext_type()): + return os.path.split(path) + elif path.endswith(".pt2"): + return os.path.split(path) + else: + return path, "" + + +@clear_on_fresh_cache +class CudaKernelParamCache: + cache: dict[str, dict[str, Any]] = {} + cache_clear = staticmethod(cache.clear) + + @classmethod + def set( + cls, + key: str, + params: dict[str, str | None], + cubin: str, + bin_type: str, + asm: str | None = None, + asm_type: str | None = None, + ) -> None: + basename = None + if config.aot_inductor.package_cpp_only: + if not config.triton.unique_kernel_names: + raise AssertionError( + "package_cpp_only requires triton kernel names to be unique" + ) + if not params["mangled_name"]: + raise AssertionError("Missing kernel name") + basename = params["mangled_name"] + + _, bin_path = write( + cubin, + bin_type, + hash_type=bin_type, + specified_dir=split_aot_inductor_output_path( + config.aot_inductor.output_path + )[0], + key=basename, + ) + # Multi-arch mode rewrites cubin_path to an artifact built later. + runtime_bin_path = bin_path + # Retrieve the basename again in case it is a generated hashcode + basename, _ = get_name_and_dir_from_output_file_path(bin_path) + + if config.aot_inductor.emit_multi_arch_kernel: + # Distinct from the single-arch .hsaco the JIT pass reloads, so + # the multi-arch bundle doesn't clobber it. + bin_type_to_ext = { + "cubin": ".fatbin", + XPU_KERNEL_FORMAT: ".spv", + "hsaco": "_multiarch.hsaco", + } + if bin_type not in bin_type_to_ext: + raise AssertionError( + "multi_arch_kernel_binary only supported in CUDA/XPU/ROCm" + ) + base_path, _ = os.path.splitext(bin_path) + bin_path = base_path + bin_type_to_ext[bin_type] + + asm_path: str = "" + + # Kernel assembly/IR requirements for AOT Inductor: + # - CUDA/XPU: Always require PTX/SPV + # - ROCm multi-arch: Require LLVM IR (.ll) for bundle compilation + if ( + config.aot_inductor.emit_multi_arch_kernel + or config.aot_inductor.package_cpp_only + ): + # Allow ROCm single-arch to skip (asm=None OK), require for everything else + if torch.version.hip is None or (asm and asm_type): + if not asm: + raise AssertionError("Missing kernel assembly code") + if not asm_type: + raise AssertionError("Missing kernel assembly type") + + # Cache directory mapping: asm_type → hash_type + # Problem: LLVM IR extension ".ll" isn't a recognized cache category + # Solution: Map to "code" (generic category for non-standard formats) + # Recognized categories: "ptx", "amdgcn", "spv", "code" + hash_kind = asm_type if asm_type in {"amdgcn", "ptx", "spv"} else "code" + + _, asm_path = write( + asm, + asm_type, + hash_type=hash_kind, + specified_dir=split_aot_inductor_output_path( + config.aot_inductor.output_path + )[0], + key=basename, + ) + + params[get_cpp_wrapper_cubin_path_name()] = bin_path + params["runtime_bin_path"] = runtime_bin_path + params["asm"] = asm_path + cls.cache[key] = params + + @classmethod + def get(cls, key: str) -> dict[str, Any] | None: + return cls.cache.get(key, None) + + @classmethod + def get_keys(cls) -> KeysView[str]: + return cls.cache.keys() + + +@clear_on_fresh_cache +class CpuTritonKernelCache: + """AOTI counterpart of CudaKernelParamCache for CPU Triton kernels.""" + + cache: dict[str, dict[str, Any]] = {} + cache_clear = staticmethod(cache.clear) + + @classmethod + def set( + cls, + key: str, + kernel_bytes: bytes, + launcher_bytes: bytes, + kernel_symbol: str, + signature: dict[str, Any], + ) -> None: + out_dir = split_aot_inductor_output_path(config.aot_inductor.output_path)[0] + _, kernel_so_path = write( + kernel_bytes, "so", hash_type="code", specified_dir=out_dir + ) + _, launcher_so_path = write( + launcher_bytes, "so", hash_type="code", specified_dir=out_dir + ) + cls.cache[key] = { + "kernel_so_path": kernel_so_path, + "launcher_so_path": launcher_so_path, + "kernel_symbol": kernel_symbol, + "signature": signature, + } + + @classmethod + def get(cls, key: str) -> dict[str, Any] | None: + return cls.cache.get(key, None) + + @classmethod + def get_keys(cls) -> KeysView[str]: + return cls.cache.keys() + + +class AotCodeCompiler: + """ + Compile AOT Inductor generated code. + """ + + @classmethod + def compile( + cls, + graph: GraphLowering, + wrapper_code: str, + kernel_code: str, + serialized_extern_kernel_nodes: str | None, + *, + device_type: str, + additional_files: list[str], + ) -> list[str | Weights] | str: + """ + Returns the .so path, or returns a list of files that were generated if + config.aot_inductor.package=True. + """ + generated_files: list[str | Weights] = additional_files # type: ignore[assignment] + + _set_gpu_runtime_env() # cpp_extension consults the env + + picked_vec_isa = pick_vec_isa() + vec_isa_cmd_gen = CppBuilder( + name="o", + sources="i", + BuildOption=CppTorchDeviceOptions( + vec_isa=picked_vec_isa, + device_type=device_type, + aot_mode=graph.aot_mode, + ), + ) + # write function will calc source_code hash, the same source code with different + # ISA level should be generate different hash. + # So we need get a command_line which contains isa related parameter as a part of hash key. + # And then pass the command_line to below write function as extra parameter to + # guarantee the source code hash contains ISA difference. + cpp_command = repr(vec_isa_cmd_gen.get_command_line()) + + # Meta internal AOTInductor CPU + use_relative_path = ( + config.is_fbcode() and device_type == "cpu" and graph.aot_mode + ) + + ( + specified_output_path, + specified_artifact_name, + ) = split_aot_inductor_output_path(config.aot_inductor.output_path) + + # TODO (benjaminglass1): the CMake packaging path doesn't support linking files + # built with different flags. Until that's implemented, append the kernel code + # to the wrapper and build everything at max optimization. + if config.aot_inductor.package_cpp_only: + wrapper_code = "\n".join((wrapper_code, kernel_code)) + kernel_code = "" + + wrapper_key, wrapper_path = write( + wrapper_code, + "wrapper.cpp", + extra=cpp_command, + specified_dir=specified_output_path, + key=config.aot_inductor.model_name_for_generated_files, + ) + kernel_code = ( + f"// Triton kernels are embedded as comments in {wrapper_path}\n" + + kernel_code + ) + _, kernel_path = write( + kernel_code, + "kernel.cpp", + extra=cpp_command, + specified_dir=specified_output_path, + key=config.aot_inductor.model_name_for_generated_files, + ) + + header_code = "" + header_path = "" + if not config.aot_inductor.dynamic_linkage: + # to link statically, we also need a header file + with open( + os.path.join( + os.path.dirname(os.path.dirname(__file__)), + "csrc", + "inductor", + "aoti_runtime", + "model.h", + ) + ) as f: + # model_name_for_generated_files is guaranteed to be non-empty when compile_standalone + model_class_name = config.aot_inductor.model_name_for_generated_files + class_name = f"AOTInductorModel{model_class_name}" + header_code = f.read() + + # we replace like this to avoid replacing + # AOTInductorModelBase and AOTInductorModelKernelsBase + header_code = ( + header_code.replace("", f"<{class_name}>") + .replace("AOTInductorModel(", f"{class_name}(") + .replace("AOTInductorModel :", f"{class_name} :") + ) + _, header_path = write( + header_code, + "h", + specified_dir=specified_output_path, + key=model_class_name, + ) + + # Log the AOTInductor wrapper and kernel code, if needed. + with WritableTempFile("w+") as t: + """ + Avoid "Permission denied error" on Windows: + with tempfile.NamedTemporaryFile("w", suffix=".gv") as temp_file: + # Not writable on Windows: + # https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile + + Example: + with WritableTempFile("w", suffix=".gv") as temp_file: + tree.to_dotfile(temp_file.name) + """ + t.writelines((wrapper_code, "\n", kernel_code, "\n")) + t.flush() + V.debug.output_code(t.name, extension="cpp") + + if config.aot_inductor.package: + generated_files.append(wrapper_path) + if not config.aot_inductor.package_cpp_only: + generated_files.append(kernel_path) + if not config.aot_inductor.dynamic_linkage: + generated_files.append(header_path) + + output_code_log.info("AOT wrapper code written to: %s", wrapper_path) + output_code_log.info("AOT kernel code written to: %s", kernel_path) + trace_structured( + "graph_dump", + lambda: { + "name": "inductor_aot_wrapper_code", + "type": "cpp", + "filename": wrapper_path, + }, + payload_fn=lambda: wrapper_code, + ) + trace_structured( + "graph_dump", + lambda: { + "name": "inductor_aot_kernel_code", + "type": "cpp", + "filename": kernel_path, + }, + payload_fn=lambda: kernel_code, + ) + if not config.aot_inductor.dynamic_linkage: + output_code_log.info("Header code written to: %s", header_path) + trace_structured( + "graph_dump", + lambda: { + "name": "inductor_aot_header_code", + "type": "cpp", + "filename": header_path, + }, + payload_fn=lambda: header_code, + ) + + # We use a file lock below to protect FS operations. The lock file + # is scoped to the 'key', so make sure the consts_s is protected + # by the same lock: + wrapper_path_operator = Path(wrapper_path) + kernel_path_operator = Path(kernel_path) + specified_sub_dir = wrapper_path_operator.parent / wrapper_key + if not specified_sub_dir.exists(): + specified_sub_dir.mkdir(exist_ok=True) + cmake_path = str(Path(specified_sub_dir) / "CMakeLists.txt") + + def _compile_consts(consts: bytes | bytearray, platform: str) -> str: + # Load from aot_inductor, and update the value on demand. + use_asm_build: bool = config.aot_inductor.use_consts_asm_build + + if platform == "linux": + if graph.mutated_buffers & OrderedSet(graph.constants.keys()): + # .data section is between .text and .bss. When the size of .data is large, + # during the linking, the relocation of .text against .bss may overflow. + # Rename it to .ldata so that it won't be in between the .text and .bss section + if len(consts) > 2_000_000_000: + raise ValueError( + "Models with buffer mutation included doesn't support constants greater than 2GB!" + ) + section_attr = '.ldata, "aw"' + else: + section_attr = '.lrodata, "a"' + symbol_prefix = "" + elif platform == "darwin": + section_attr = "__DATA,__data" + symbol_prefix = "_" + elif platform == "win32": + symbol_prefix = "" + # ASM build is not supported on Windows, force use CPP build. + use_asm_build = False + else: + raise RuntimeError(f"Unsupported platform: {platform}") + + # Intel compiler failed to compile this manually constructed assembly file. + # Switch XPU to use consts cpp build. + if device_type == "xpu": + use_asm_build = False + + is_large_consts = len(consts) > 1024 + is_zero_size_consts = len(consts) == 0 + + def format_consts_to_gnu_asm( + consts: bytes | bytearray, + align_bytes: int, + symbol_prefix: str, + is_large_consts: bool, + ) -> tuple[str, str]: + consts_asm = f"\t.section\t{section_attr}\n" + consts_asm += f"\t.balign {align_bytes}\n" + consts_asm += f"\t.globl\t{symbol_prefix}_binary_constants_bin_start\n" + consts_asm += f"{symbol_prefix}_binary_constants_bin_start:\n" + if not is_large_consts: + for c in consts: + consts_asm += f"\t.byte {c}\n" + # Add one element even if constants are empty + # Otherwise assembler will not put them in data section + if not consts: + consts_asm += "\t.space 1\n" + else: + consts_asm += "\t.quad 0x1234567899abcdef\n" + consts_asm += f"\t.space {len(consts) - 8}\n" + consts_asm += f".globl\t{symbol_prefix}_binary_constants_bin_end\n" + consts_asm += f"{symbol_prefix}_binary_constants_bin_end:\n" + return consts_asm, "weights.S" + + # Use c++ to convert consts to object file can support more compilers, such as msvc and icx. + def format_consts_to_cpp( + consts: bytes | bytearray, align_bytes: int, symbol_prefix: str + ) -> tuple[str, str]: + consts_size = len(consts) + asan_attr = """#if defined(__clang__) || defined (__GNUC__)\t\n\ +#define ATTRIBUTE_NO_SANITIZE_ADDRESS __attribute__((no_sanitize("address")))\t\n\ +#else\t\n\ +#define ATTRIBUTE_NO_SANITIZE_ADDRESS\t\n\ +#endif\t\n\ +\t\n\ +ATTRIBUTE_NO_SANITIZE_ADDRESS\t\n""" + const_cpp = asan_attr + const_cpp += f"alignas({align_bytes}) extern " + const_cpp += f"unsigned char {symbol_prefix}_binary_constants_bin_start[{consts_size}] = {{\t\n" + count_bytes = 0 + for c in consts: + const_cpp += f"{c}, " + count_bytes = count_bytes + 1 + if count_bytes % 16 == 0: + const_cpp += "\t\n" + const_cpp += "};\t\n" + const_cpp += f"alignas({align_bytes}) extern unsigned char * {symbol_prefix}_binary_constants_bin_end;\t\n" + return const_cpp, "weights.cpp" + + def get_zero_consts_asm_code( + align_bytes: int, + symbol_prefix: str, + ) -> tuple[str, str]: + """ + This function handles zero-sized constants because the C++ standard prohibits zero-length arrays: + https://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size-array-in-c-c + + On Windows (MSVC): + The compiler reports error C2466 for zero-sized arrays: + https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2466 + Solution: Use assembly compilation to handle this case. + + Why not use Win32 assembly for all paths? + ml64 only supports alignment up to 16 bytes, which isn't optimal for performance. + + Cross-platform implementation: + Linux: Added '-pedantic' to disable zero-sized arrays in C++ compiler + Windows: MSVC naturally rejects zero-sized arrays by default + """ + if _IS_WINDOWS: + # Windows ml64 is max support align to 16, but it is no effect to zero size data. + asm_code = """ +option casemap:none +.data +?_binary_constants_bin_start@@3PAEA: +align 16 +?_binary_constants_bin_end@@3PAEA: +align 16 +public ?_binary_constants_bin_start@@3PAEA +public ?_binary_constants_bin_end@@3PAEA +end +""" + asm_ext = "asm" + else: + asm_code = f"\t.section\t{section_attr}\n" + asm_code += f"\t.balign {align_bytes}\n" + asm_code += ( + f"\t.globl\t{symbol_prefix}_binary_constants_bin_start\n" + ) + asm_code += f"{symbol_prefix}_binary_constants_bin_start:\n" + asm_code += f".globl\t{symbol_prefix}_binary_constants_bin_end\n" + asm_code += f"{symbol_prefix}_binary_constants_bin_end:\n" + asm_ext = "S" + return asm_code, asm_ext + + if use_asm_build: + consts_code, code_ext = format_consts_to_gnu_asm( + consts, ALIGN_BYTES, symbol_prefix, is_large_consts + ) + else: + if is_zero_size_consts: + consts_code, code_ext = get_zero_consts_asm_code( + ALIGN_BYTES, symbol_prefix + ) + else: + consts_code, code_ext = format_consts_to_cpp( + consts, ALIGN_BYTES, symbol_prefix + ) + + _, consts_s = write( + consts_code, + code_ext, + specified_dir=str(specified_sub_dir), + key=config.aot_inductor.model_name_for_generated_files, + ) + consts_s = Path(consts_s) + object_build_options = CppTorchDeviceOptions( + device_type=device_type, + aot_mode=graph.aot_mode, + compile_only=True, + use_relative_path=use_relative_path, + ) + object_builder = CppBuilder( + name=str(consts_s.stem), + sources=str(consts_s), + output_dir=str(consts_s.parent), + BuildOption=object_build_options, + ) + consts_o = object_builder.get_target_file_path() + if use_asm_build is False and is_zero_size_consts: + run_asm_build_object(str(consts_s), consts_o, str(consts_s.parent)) + else: + object_builder.build() + + if is_large_consts and use_asm_build: + with open(consts_o, "r+b") as f: + f.seek(0) + hdr = f.read(1024) + # Search for magic number and write the actual data over it + start_idx = ( + hdr.find(b"\xef\xcd\xab\x99\x78\x56\x34\x12") + if sys.byteorder == "little" + else hdr.find(b"\x12\x34\x56\x78\x99\xab\xcd\xef") + ) + if start_idx == -1: + raise AssertionError( + "Magic number not found in constants header" + ) + f.seek(start_idx) + pos = 0 + while pos < len(consts): + rc = f.write(consts[pos:]) + pos += rc + + # Remove the .S file to save space + os.remove(consts_s) + + return consts_o + + from torch.utils._filelock import FileLock + + lock_dir = get_lock_dir() + lock = FileLock( + os.path.join(lock_dir, wrapper_key + ".lock"), timeout=LOCK_TIMEOUT + ) + with lock: + if serialized_extern_kernel_nodes: + extern_kernel_nodes_json = str( + wrapper_path_operator.with_suffix(".json") + ) + with open(extern_kernel_nodes_json, "w") as f: + f.write(serialized_extern_kernel_nodes) + + if config.aot_inductor.package: + generated_files.append(extern_kernel_nodes_json) + + metadata = config.aot_inductor.metadata + metadata["AOTI_DEVICE_KEY"] = device_type + + # Add environment information to ensure .so compatibility + metadata.update(get_device_information(device_type)) + + # Save user provided metadata + meta_json = str( + wrapper_path_operator.with_name( + f"{wrapper_path_operator.stem}_metadata.json" + ) + ) + for k, v in config.aot_inductor.metadata.items(): + if not isinstance(k, str) or not isinstance(v, str): + raise AssertionError("Metadata must only contain strings") + + with open(meta_json, "w") as f: + f.write(json.dumps(config.aot_inductor.metadata)) + + kernel_meta_json = str( + kernel_path_operator.with_name( + f"{kernel_path_operator.stem}_metadata.json" + ) + ) + shutil.copy(meta_json, kernel_meta_json) + + if config.aot_inductor.package: + generated_files.append(meta_json) + if not config.aot_inductor.package_cpp_only: + generated_files.append(kernel_meta_json) + + output_so = ( + config.aot_inductor.output_path + if specified_artifact_name + else str(wrapper_path_operator.with_suffix(".so")) + ) + all_cuda = all( + graph.get_original_value_of_constant(name).is_cuda + for name in graph.constants + if name not in graph.folded_constants + ) + + import ctypes + + def _constant_nbytes(t: torch.Tensor) -> int: + if t.numel() == 0: + return 0 + if t.is_mkldnn: + return torch.ops.mkldnn._nbytes(t) + return t.untyped_storage().nbytes() + + if ( + config.aot_inductor.package_constants_in_so + or config.aot_inductor.package_constants_on_disk_format == "binary_blob" + ): + with dynamo_timed( + "aoti_serialize_constants", log_pt2_compile_event=True + ): + constant_names = [ + name + for name in graph.constants + if name not in graph.folded_constants + ] + if constant_names: + from concurrent.futures import ThreadPoolExecutor + + # Compute offsets up front so each worker can write into a + # disjoint slice of a single pre-allocated buffer independently + offsets: list[int] = [] + sizes: list[int] = [] + total_size = 0 + for name in constant_names: + t = graph.get_original_value_of_constant(name) + n = _constant_nbytes(t) + offsets.append(total_size) + sizes.append(n) + total_size += ( + n + if all_cuda + else (n + ALIGN_BYTES - 1) // ALIGN_BYTES * ALIGN_BYTES + ) + + serialized_weights = bytearray(total_size) + # Hold one persistent view so the bytearray can't be resized, + # and cache the base address for pointer arithmetic. + buf_view = (ctypes.c_ubyte * total_size).from_buffer( + serialized_weights + ) + base_addr = ctypes.addressof(buf_view) + + def _worker(i: int) -> None: + n = sizes[i] + if n == 0: + return + t = graph.get_original_value_of_constant(constant_names[i]) + if t.is_mkldnn: + data_ptr = torch.ops.mkldnn.data_ptr(t) + ctypes.memmove(base_addr + offsets[i], data_ptr, n) + else: + # Hold the CPU storage until memmove finishes — + # otherwise it may be freed and data_ptr dangles. + t_cpu = t.untyped_storage().cpu() + ctypes.memmove( + base_addr + offsets[i], t_cpu.data_ptr(), n + ) + + with ThreadPoolExecutor() as pool: + # Consume iterator to surface any worker exceptions. + for _ in pool.map(_worker, range(len(constant_names))): + pass + + del buf_view + else: + serialized_weights = b"" + else: + serialized_weights = b"" + + if config.aot_inductor.package_constants_on_disk_format == "pickle_weights": + # We need to return a storage key here because the original value tensor might be a clone + weights_dict = Weights( + { + graph.allocated_constant_name[name]: ( + graph.get_original_value_of_constant(name), + TensorProperties(graph.constants[name]), + ) + for name in graph.constants + if name not in graph.folded_constants + } + ) + generated_files.append(weights_dict) + + consts_size = len(serialized_weights) + + use_external_weights, use_mmap_weights = determine_aoti_mmap_flags( + consts_size + ) + if use_external_weights and use_mmap_weights: + # Should never reach here, just a check for sanity + raise RuntimeError( + "use_external_weights and use_mmap_weights cannot both be True." + ) + + external_weights_path = None + if use_external_weights: + external_weights_filename = f"{wrapper_path_operator.stem}_weights.blob" + external_weights_path = str( + wrapper_path_operator.with_name(external_weights_filename) + ) + + compile_command: dict[str, Any] = { + "aot_mode": graph.aot_mode, + "device_type": device_type, + "use_mmap_weights": use_mmap_weights, + "use_mmap_weights_external": use_external_weights, + "use_relative_path": use_relative_path, + "vec_isa": picked_vec_isa, + } + # If we're packaging via CMake, we build the whole code at max optimization. + wrapper_build_options = CppTorchDeviceOptions( + compile_only=True, + min_optimize=not config.aot_inductor.package_cpp_only, + **compile_command, + ) + kernel_build_options = CppTorchDeviceOptions( + compile_only=True, + **compile_command, + ) + + # potentially, precompile the AOT header for this device + if config.aot_inductor.precompile_headers and not _IS_WINDOWS: + with dynamo_timed("aoti_precompile_header", log_pt2_compile_event=True): + header_file = _get_cpp_wrapper_header( + device_type, aot_mode=graph.aot_mode + ) + wrapper_build_options.precompiled_header = _precompile_header( + header_file, + cpp_command, + min_optimize=not config.aot_inductor.package_cpp_only, + **compile_command, + ) + if cpp_prefix := _get_cpp_prefix_header(device_type): + kernel_build_options.precompiled_header = _precompile_header( + cpp_prefix, + cpp_command, + **compile_command, + ) + + wrapper_builder = CppBuilder( + name=str(wrapper_path_operator.stem), + sources=wrapper_path, + output_dir=str(wrapper_path_operator.parent), + BuildOption=wrapper_build_options, + ) + wrapper_compile_cmd = wrapper_builder.get_command_line() + wrapper_o = wrapper_builder.get_target_file_path() + + kernel_builder = CppBuilder( + name=str(kernel_path_operator.stem), + sources=kernel_path, + output_dir=str(wrapper_path_operator.parent), + BuildOption=kernel_build_options, + ) + kernel_compile_cmd = kernel_builder.get_command_line() + kernel_o = kernel_builder.get_target_file_path() + + log.debug("aot wrapper compilation command: %s", wrapper_compile_cmd) + log.debug("aot kernel compilation command: %s", kernel_compile_cmd) + if config.aot_inductor.package_cpp_only: + # Not doing the actual compilation here + compile_flags = str( + wrapper_path_operator.with_name( + f"{wrapper_path_operator.stem}_compile_flags.json" + ) + ) + wrapper_build_options.save_flags_to_json(compile_flags) + generated_files.append(compile_flags) + wrapper_builder.save_compile_cmd_to_cmake(cmake_path, device_type) + wrapper_builder.save_src_to_cmake(cmake_path, wrapper_path) + generated_files.append(cmake_path) + else: + try: + wrapper_builder.build() + except (exc.CppCompileError, SkipFrame) as e: + if " is too big to optimize" in str(e): + raise RuntimeError( + "Please use torch._inductor.config.aot_inductor.compile_wrapper_opt_level = 'O0' flag." + ) from e + raise e + kernel_builder.build() + + if not use_mmap_weights: + aot_constants = serialized_weights + magic_number = 0 + if use_external_weights: + aot_constants = struct.pack("q", consts_size) + if external_weights_path is None: + raise AssertionError( + "external_weights_path must be set when use_external_weights is True" + ) + # For external weights, write weights to separate file and embed minimal placeholder + with open(external_weights_path, "wb") as f_weights: + f_weights.write(serialized_weights) + generated_files.append(external_weights_path) + else: + # we'll append weights binary to the end of .so file and mmap it when loading + magic_number = cast( + int, torch.randint(0, torch.iinfo(torch.int64).max, (1,)).item() + ) + aot_constants = struct.pack("qq", consts_size + 8, magic_number) + + consts_o = _compile_consts(aot_constants, sys.platform) + custom_obj_idx = 0 + # Note that custom_objs_config.json file is different from the model_constants_config.json file produced + # in package_sigmoid(). The keys in custom_objs_config.json directly correspond to the arg name in extern + # nodes json. The key in model_constants_config.json produced by package_sigmoid is the attribute name in the + # user model code. + + qual_name_to_id = {} # Map from constant name to its name in constants folder + for custom_obj_idx, (name, constant) in enumerate( + graph.torchbind_constants.items() + ): + if isinstance( + constant, torch._library.fake_class_registry.FakeScriptObject + ): + constant = constant.real_obj + if not isinstance(constant, torch._C.ScriptObject): + raise AssertionError(f"Expected ScriptObject, got {type(constant)}") + custom_obj_name = f"{CUSTOM_OBJ_FILENAME_PREFIX}{custom_obj_idx}" + + log.debug("saving script object %s as %s", name, custom_obj_name) + + qual_name_to_id[name] = custom_obj_name + custom_obj_bytes = torch._C._pickle_save(constant) + custom_obj_path = os.path.join( + wrapper_path_operator.parent, custom_obj_name + ) + + write_atomic(custom_obj_path, custom_obj_bytes, True) + generated_files.append(custom_obj_path) + + if qual_name_to_id: + constants_config_json = os.path.join( + wrapper_path_operator.parent, "custom_objs_config.json" + ) + with open(constants_config_json, "w") as f: + f.write(json.dumps(qual_name_to_id)) + generated_files.append(constants_config_json) + + cache_cls = { + "rocm": ROCmCodeCache, + "cuda": CUDACodeCache, + "xpu": XPUCodeCache, + }.get("rocm" if torch.version.hip else device_type, CUDACodeCache) + + gpu_codecache = cache_cls() + gpu_kernels_o = gpu_codecache.aot_kernels_o.copy() + # clear the list of aot kernels after each linking + gpu_codecache.aot_kernels_o.clear() + + if gpu_kernels_o: + if config.aot_inductor.emit_multi_arch_kernel: + raise AssertionError( + "TODO: add emit_multi_arch_kernel support for cutlass kernels" + ) + + cubins_o = [] + asm_files = [] + fatbin_cmds: list[tuple[str, str, str | None, str | None]] = [] + if not _IS_WINDOWS: + cubins_to_embed: list[tuple[str, str]] = [] + ld, objcopy = get_ld_and_objcopy(use_relative_path) + kernels = getattr(V.graph.wrapper_code, "_kernel_name_to_body", {}) + for kernel_name, value in CudaKernelParamCache.cache.items(): + if kernel_name not in kernels: + # It is possible that CudaKernelParamCache contains more Triton kernels + # than what the current graph uses + continue + + if asm_file := value["asm"]: + asm_files.append(asm_file) + + cubin_file = value[get_cpp_wrapper_cubin_path_name()] + if ( + config.aot_inductor.emit_multi_arch_kernel + and device_type == "cuda" + ): + if torch.version.hip is None: + fatbin_cmds.append( + ( + asm_file, + cubin_file, + value.get("runtime_bin_path"), + value.get("cuda_arch"), + ) + ) + + else: + # ROCm multi-arch: compile LLVM IR to multi-arch bundle + from torch._inductor.rocm_multiarch_utils import ( + compile_multiarch_bundle_from_llvm_ir, + ) + + # pyrefly: ignore [unbound-name] + if not os.path.exists(asm_file): + raise RuntimeError( + f"Multi-arch ROCm compilation requires LLVM IR file, " + # pyrefly: ignore [unbound-name] + f"but {asm_file} not found. " + f"Ensure asm_type='ll' is captured in triton_heuristics.py" + ) + + # Compile for multiple archs and bundle them + success = compile_multiarch_bundle_from_llvm_ir( + # pyrefly: ignore [unbound-name] + llvm_ir_path=asm_file, + output_bundle_path=cubin_file, + target_archs=None, + ) + + if not success: + raise RuntimeError( + f"Failed to compile multi-arch bundle for kernel {kernel_name}. " + f"Check that ROCm toolchain is available and LLVM IR is valid." + ) + + log.info("Created multi-arch bundle: %s", cubin_file) + + if config.aot_inductor.embed_kernel_binary: + cubins_to_embed.append((cubin_file, kernel_name)) + + # Build CUDA fatbins in parallel before cubin embedding below. + if fatbin_cmds: + from concurrent.futures import ThreadPoolExecutor + + nvcc = cuda_compile_utils._cuda_compiler() + fatbinary = shutil.which("fatbinary") + if nvcc is not None and (nvcc_dir := os.path.dirname(nvcc)): + candidate = os.path.join(nvcc_dir, "fatbinary") + if os.path.exists(candidate): + fatbinary = candidate + + def _compile_fatbin( + asm_cubin_and_raw: tuple[str, str, str | None, str | None], + ) -> None: + asm_f, cubin_f, raw_cubin_f, cuda_arch = asm_cubin_and_raw + cmd = _cuda_fatbin_command( + asm_f, cubin_f, raw_cubin_f, nvcc, fatbinary, cuda_arch + ) + try: + subprocess.run( + cmd, capture_output=True, text=True, check=True + ) + except subprocess.CalledProcessError as e: + print( + f"{shlex.join(cmd)} failed with:\nstdout:\n{e.stdout}\nstderr:\n{e.stderr}", + file=sys.stderr, + ) + raise + + with ( + dynamo_timed("aoti_compile_fatbin", log_pt2_compile_event=True), + ThreadPoolExecutor() as pool, + ): + list(pool.map(_compile_fatbin, fatbin_cmds)) + + if cubins_to_embed: + # Batch all cubins into a single .o using .incbin assembly. + # This replaces N * 3 subprocess calls (ld + 2x objcopy per + # cubin) with a single compiler invocation. + try: + combined_obj = batch_convert_cubins_to_obj( + cubins_to_embed, + os.path.dirname(output_so), + cpp_compiler=get_cpp_compiler(), + ) + cubins_o.append(combined_obj) + except subprocess.CalledProcessError: + log.warning( + "Batched cubin embedding failed, " + "falling back to per-cubin objcopy" + ) + for cubin_file, kernel_name in cubins_to_embed: + cubins_o.append( + convert_cubin_to_obj( + cubin_file, kernel_name, ld, objcopy + ) + ) + + output_name, output_dir = get_name_and_dir_from_output_file_path(output_so) + so_build_options = CppTorchDeviceOptions( + vec_isa=picked_vec_isa, + device_type=device_type, + aot_mode=graph.aot_mode, + use_relative_path=use_relative_path, + ) + + if gpu_kernels_o and device_type == "xpu": + so_build_options = CppTorchDeviceOptions( + compiler="icpx", + vec_isa=picked_vec_isa, + device_type=device_type, + aot_mode=graph.aot_mode, + use_relative_path=use_relative_path, + extra_flags=[ + "-fsycl", + "-fsycl-targets=intel_gpu_pvc", + "-Xspirv-translator", + ( + "-spirv-ext=" + "+SPV_INTEL_split_barrier," + "+SPV_INTEL_2d_block_io," + "+SPV_INTEL_subgroup_matrix_multiply_accumulate" + ), + ], + ) + + obj_srcs = [wrapper_o, kernel_o, consts_o, *gpu_kernels_o, *cubins_o] + so_builder = CppBuilder( + name=output_name, + sources=obj_srcs, + output_dir=output_dir, + BuildOption=so_build_options, + ) + link_cmd = so_builder.get_command_line() + output_so = so_builder.get_target_file_path() + + log.debug("aot linkage command: %s", link_cmd) + + # Append cmds to the end of codegen-ed wrapper file + with open(wrapper_path, "a") as f: + f.write("\n") + f.write(f"// Compile cmd\n// {wrapper_compile_cmd}\n") + f.write(f"// Link cmd\n// {link_cmd}\n") + + with open(kernel_path, "a") as f: + f.write("\n") + f.write(f"// Compile cmd\n// {kernel_compile_cmd}\n") + f.write(f"// Link cmd\n// {link_cmd}\n") + + if config.aot_inductor.package_cpp_only: + linker_flags = str( + wrapper_path_operator.with_name( + f"{wrapper_path_operator.stem}_linker_flags.json" + ) + ) + so_build_options.save_flags_to_json(linker_flags) + generated_files.append(linker_flags) + generated_files.append(_LINKER_SCRIPT) + + # If we only want to package the cpp, then we need to save the + # weights separately into a bin, and we also need to prevent compiling the so + if use_mmap_weights: + weight_file = str( + wrapper_path_operator.with_name( + f"{wrapper_path_operator.stem}_serialized_weights.bin" + ) + ) + with open(weight_file, "wb") as f_weights: + f_weights.write(serialized_weights) + f_weights.write(struct.pack("q", magic_number)) + + generated_files.append(weight_file) + else: + # TODO: unify to always use mmap_weights + generated_files.append(consts_o) + so_builder.save_src_to_cmake(cmake_path, consts_o) + + # Different CMake strategies for CUDA vs ROCm: + # - CUDA: Save asm for CMake to recompile (user has nvcc) + # - ROCm: Link pre-compiled bundle (user may lack dev tools) + if ( + config.aot_inductor.emit_multi_arch_kernel + and torch.version.hip is None + ): + so_builder.save_kernel_asm_to_cmake(cmake_path, asm_files) + generated_files.extend(asm_files) + else: + # ROCm multi-arch + all single-arch: Link pre-compiled objects + # Bundle already embedded in .o files - just link into .so + obj_srcs = [*gpu_kernels_o, *cubins_o] + generated_files.extend(obj_srcs) + for obj in obj_srcs: + so_builder.save_src_to_cmake(cmake_path, obj) + + so_builder.save_link_cmd_to_cmake(cmake_path) + else: + so_builder.build() + for o_file in obj_srcs: + if o_file in gpu_kernels_o: + continue + # Remove these as they are not needed anymore + os.remove(o_file) + + if use_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." + ) + + def get_page_size() -> int: + # Don't use resource.getpagesize() on Windows, as it is a Unix specific package + # as seen in https://docs.python.org/2/library/resource.html + if _IS_WINDOWS: + from ctypes import ( + byref, + Structure, + windll, # pyrefly: ignore [missing-module-attribute] + ) + from ctypes.wintypes import DWORD, LPVOID, WORD + + class SYSTEM_INFO(Structure): + _fields_ = [ + ("wProcessorArchitecture", WORD), + ("wReserved", WORD), + ("dwPageSize", DWORD), + ("lpMinimumApplicationAddress", LPVOID), + ("lpMaximumApplicationAddress", LPVOID), + ("dwActiveProcessorMask", DWORD), + ("dwNumberOfProcessors", DWORD), + ("dwProcessorType", DWORD), + ("dwAllocationGranularity", DWORD), + ("wProcessorLevel", WORD), + ("wProcessorRevision", WORD), + ] + + si = SYSTEM_INFO() + windll.kernel32.GetSystemInfo(byref(si)) + sys_page_size = si.dwPageSize + else: + import resource + + sys_page_size = resource.getpagesize() + + return sys_page_size + + page_size_ = get_page_size() + page_size = max(16384, page_size_) + + with open(output_so, "a+b") as f_so: + so_size = f_so.tell() + # Page align the weights + f_so.write(b" " * (page_size - so_size % page_size)) + f_so.write(serialized_weights) + f_so.write(struct.pack("q", magic_number)) + + if config.aot_inductor.package: + generated_files.append(output_so) + + if config.effective_provenance_tracking_level() != 0: + kernel_info = torch._inductor.debug.create_kernel_information_json() + kernel_info_json = os.path.join( + wrapper_path_operator.parent, "kernel_information.json" + ) + with open(kernel_info_json, "w") as f: + f.write(json.dumps(kernel_info, indent=4)) + generated_files.append(kernel_info_json) + + if config.aot_inductor.package: + # We want to return the directory that contains all the AOTI + # generated files, not just the so + # return os.path.split(output_so)[0] + return generated_files + + return output_so + + +_libgomp: CDLL | None = None + + +def custom_op_wrapper(op: str, *args: Any) -> list[c_void_p] | c_void_p | None: + # This function will be called from generated cpp wrapper code in the JIT mode. + # Because tensors will be passed in as AtenTensorHandle, we need to explicitly convert them. + def convert_arg(arg: Any) -> Any: + if str(type(arg)) == "": + # No easy way to do isinstance check on PyCapsule + return torch._C._aoti.alloc_tensor_by_stealing_from_void_ptr(arg) + elif isinstance(arg, (list, tuple)): + return type(arg)(convert_arg(a) for a in arg) + else: + return arg + + converted_args = [convert_arg(arg) for arg in args] + + if not op.startswith("torch.ops."): + raise AssertionError(op + " can not be called through custom_op_wrapper") + func = None + for i, s in enumerate(op.split(".")): + if i == 0: + func = importlib.import_module(s) + func = getattr(func, s) + + if not callable(func): + raise AssertionError(op + " can not be loaded through custom_op_wrapper") + + # convert any kwarg-only arguments to kwargs + kwargs = dict() + # pyrefly: ignore [missing-attribute] + for func_arg, conv_arg in zip(func._schema.arguments, converted_args): + if func_arg.kwarg_only: + kwargs[func_arg.name] = conv_arg + if kwargs: + del converted_args[-len(kwargs) :] + + result = func(*converted_args, **kwargs) + if result is None: + return None + + if isinstance(result, (list, tuple)): + # unsafe_alloc_void_ptrs_from_tensors expects result contains tensor only + result = [torch.tensor([]) if r is None else r for r in result] + for r in result: + if not isinstance(r, torch.Tensor): + raise AssertionError(op + " returns a list of non-tensors") + return torch._C._aoti.unsafe_alloc_void_ptrs_from_tensors(result) # type: ignore[arg-type] + + if not isinstance(result, torch.Tensor): + raise AssertionError(op + " returns a non-tensor") + return torch._C._aoti.unsafe_alloc_void_ptr_from_tensor(result) + + +# Precompiled headers are persistent past program runtime, but associated with one +# specific compiler version and set of flags. We explicitly use default_cache_dir here +# because these headers need to be global, rather than ignored by fresh_cache. +_HEADER_DIR = os.path.join(default_cache_dir(), "precompiled_headers") +_HEADER_LOCK_DIR = os.path.join(_HEADER_DIR, "locks") +_VEC_ISA_CPP_SOURCE_MARKERS = ("at::vec::", "prod_masked_reduce(") + + +@functools.cache +def _precompile_header( + header: str, + hashable_cmd_line: str, + **compile_command: Any, +) -> str: + if _IS_WINDOWS: + raise AssertionError( + "CppBuilder does not currently support precompiling on Windows!" + ) + + # extra_flags carries link-time inputs (e.g. precompiled kernel .so paths + # for CUTLASS/ROCm CK under JIT cpp_wrapper). Preprocessing and PCH + # compilation don't link, so g++ rejects .so paths as unused linker + # input. Strip them here. + compile_command.pop("extra_flags", None) + + # Get the preprocessed output from the header file to be precompiled. This allows + # us to properly invalidate the file cache when any header dependency changes. This + # is thread-safe, as each thread will get its own temporary directory. + # + # N.B. we can't use NamedTemporaryFile here because Windows errors out on attempts + # to read from a file with an open write handle. + with tempfile.TemporaryDirectory() as preprocessing_dir: + preprocessing_header = Path(preprocessing_dir) / "header.hpp" + preprocessing_header.write_text(f"#include <{header}>\n") + preprocessor = CppBuilder( + name=str(preprocessing_header)[:-4], # strip off the .hpp extension + sources=str(preprocessing_header), + BuildOption=CppTorchDeviceOptions(**compile_command, preprocessing=True), + ) + preprocessor.build() + + def _get_file_checksum(filename: str) -> str: + """Reading the whole preprocessed header in for hashing is very expensive, + but calling a fast hashing utility in a subprocess is cheap.""" + # If Windows support needs to be added here, use certutil -hashfile. + cmd_output = subprocess.run( + ("openssl", "sha512", filename), capture_output=True, text=True + ) + return cmd_output.stdout.split()[-1] + + preprocessor_hash = _get_file_checksum(preprocessor.get_target_file_path()) + + header_build_option = CppTorchDeviceOptions(**compile_command, precompiling=True) + header_hash, header_full_path = write( + content=f"#include <{header}>\n", + extension="h", + extra=( + hashable_cmd_line + + preprocessor_hash + + get_compiler_version_info(header_build_option.get_compiler()) + ), + specified_dir=_HEADER_DIR, + ) + cpp_builder = CppBuilder( + name=header_full_path, + sources=header_full_path, + BuildOption=header_build_option, + ) + # _worker_compile_cpp will automatically ignore any compilation whose result already + # exists, so this is always safe. + os.makedirs(_HEADER_LOCK_DIR, exist_ok=True) + _worker_compile_cpp( + os.path.join(_HEADER_LOCK_DIR, f"{header_hash}.lock"), + (cpp_builder,), + ) + + return header_full_path + + +def _get_cpp_prefix_header(device: str) -> str | None: + if device.startswith("cpu"): + return "torch/csrc/inductor/cpp_prefix.h" + return None + + +def _get_cpp_wrapper_header(device: str, aot_mode: bool = False) -> str: + """Given a device type (and optionally whether we're in AOT Inductor mode), returns + the path to the cpp_wrapper header file to be precompiled.""" + base_device = device.split(":", maxsplit=1)[0] + is_array_ref = config.aot_inductor.allow_stack_allocation and base_device == "cpu" + return ( + "torch/csrc/inductor/" + f"{'aoti_include' if aot_mode else 'cpp_wrapper'}/" + f"{'array_ref' if is_array_ref else base_device}.h" + ) + + +def _resolve_needs_vec_isa( + base_device_type: str, source: str | None, explicit: bool | None +) -> bool: + if explicit is not None: + return explicit + if source is None: + return False + if base_device_type == "cpu": + return True + return any(marker in source for marker in _VEC_ISA_CPP_SOURCE_MARKERS) + + +@clear_on_fresh_cache +class CppCodeCache: + """Compiles and caches C++ libraries. Users of this class supply the source code to + be compiled, while compilation flags are set by CppBuilder.""" + + cache: dict[str, Callable[[], CDLL | ModuleType]] = {} + cache_clear = staticmethod(cache.clear) + cpp_compile_command_flags: dict[str, Any] = {} + + @staticmethod + def _load_library_inner(path: str, key: str) -> CDLL | ModuleType: + return cdll.LoadLibrary(path) + + @classmethod + def _load_library(cls, path: str, key: str) -> CDLL | ModuleType: + try: + result = cls._load_library_inner(path, key) + result.key = key # type: ignore[union-attr] + return result + except (ImportError, OSError) as e: + if "gomp" in str(e) and os.path.exists("/usr/lib64/libgomp.so.1"): + # hacky workaround for fbcode/buck + global _libgomp + _libgomp = cdll.LoadLibrary("/usr/lib64/libgomp.so.1") + result = cls._load_library_inner(path, key) + result.key = key # type: ignore[union-attr] + return result + if "failed to map segment from shared object" in str(e): + raise OSError( + f"{e}. The most common reason this may occur is if the {tempfile.gettempdir()} folder " + "is mounted with noexec (e.g., by default Docker mounts tmp file systems " + f"as noexec). Please remount {tempfile.gettempdir()} with exec enabled, or set another " + "temporary directory with TORCHINDUCTOR_CACHE_DIR environment variable." + ) from e + raise + + @classmethod + def _get_uncompiled_header(cls, device: str) -> str | None: + """ + Given a device type, returns the path to a CPP header file to be precompiled. + """ + return None + + @classmethod + def load_async( + cls, + main_code: str, + device_type: str = "cpu", + submit_fn: Any = None, + extra_flags: Sequence[str] = (), + optimized_code: str | None = None, + needs_vec_isa: bool | None = None, + kernel_needs_vec_isa: bool | None = None, + ) -> Any: + """Compile and load a C++ library. Returns a callable that returns the loaded + library.""" + base_device_type = device_type.split(":", maxsplit=1)[0] + main_needs_vec_isa = _resolve_needs_vec_isa( + base_device_type, main_code, needs_vec_isa + ) + kernel_needs_vec_isa = _resolve_needs_vec_isa( + base_device_type, optimized_code, kernel_needs_vec_isa + ) + picked_vec_isa = ( + pick_vec_isa() + if main_needs_vec_isa or kernel_needs_vec_isa + else invalid_vec_isa + ) + shared_compile_command = { + **cls.cpp_compile_command_flags, + "device_type": device_type, + "extra_flags": extra_flags, + "use_relative_path": config.is_fbcode(), + } + main_compile_command = { + **shared_compile_command, + "vec_isa": picked_vec_isa if main_needs_vec_isa else invalid_vec_isa, + } + optimized_compile_command = { + **shared_compile_command, + "vec_isa": picked_vec_isa if kernel_needs_vec_isa else invalid_vec_isa, + } + + _set_gpu_runtime_env() # cpp_extension consults the env + + # Note the distinction between the two booleans. We do minimal optimization if + # the optimized_code argument is present at all, since that's how the user of + # this function opts in, but we do compilation and linking in one step if the + # optimized_code argument is empty (as a micro-optimization). + # On GPU the C++ wrapper is just glue — the real kernels are compiled + # separately by Triton/CUDA. Always use -O1 to cut compile time. + min_optimize = optimized_code is not None or device_type != "cpu" + main_build_option = CppTorchDeviceOptions( + compile_only=bool(optimized_code), + min_optimize=min_optimize, + # pyrefly: ignore [bad-argument-type] + **main_compile_command, + ) + optimized_build_option = CppTorchDeviceOptions( + # pyrefly: ignore [bad-argument-type] + compile_only=True, + # pyrefly: ignore [bad-argument-type] + **optimized_compile_command, + ) + + def get_hashable_command_line(build_option: BuildOptionsBase) -> str: + """Writing the code to file will calculate a hash, which we need to vary if + the command line flags change. This implements a mostly-generic way of + validating that.""" + return CppBuilder( + name="o", sources="i", BuildOption=build_option + ).get_command_line() + + main_cmd_line = get_hashable_command_line(main_build_option) + optimized_cmd_line = get_hashable_command_line(optimized_build_option) + + key, main_path = write( + main_code, "main.cpp", extra=f"{optimized_code} {main_cmd_line}" + ) + + # Don't bother writing if the argument is empty. + if optimized_code: + _, optimized_path = write( + optimized_code, "optimized.cpp", extra=optimized_cmd_line + ) + else: + # Unused, but makes type checkers happy. + optimized_path = os.devnull + + if key not in cls.cache: + from torch.utils._filelock import FileLock + + lock_path = os.path.join(get_lock_dir(), key + ".lock") + future: Future[Any] | None = None + lib = None + + # if requested, pre-compile any headers + if config.cpp_cache_precompile_headers and not _IS_WINDOWS: + if header := cls._get_uncompiled_header(device_type): + main_build_option.precompiled_header = _precompile_header( + header, + main_cmd_line, + min_optimize=min_optimize, + **main_compile_command, + ) + + # Currently, the optimized_code field is only used for cpp kernel code, + # so go ahead and precompile the relevant header here. Revisit this + # decision if that ever changes. + if optimized_code and (header := _get_cpp_prefix_header(device_type)): + optimized_build_option.precompiled_header = _precompile_header( + # pyrefly: ignore [unbound-name] + header, + optimized_cmd_line, + **optimized_compile_command, + ) + + main_name, output_dir = get_name_and_dir_from_output_file_path(main_path) + main_builder = CppBuilder( + name=main_name, + sources=main_path, + BuildOption=main_build_option, + output_dir=output_dir, + ) + + if optimized_code: + optimized_name, _ = get_name_and_dir_from_output_file_path( + optimized_path + ) + optimized_builder = CppBuilder( + name=optimized_name, + sources=optimized_path, + BuildOption=optimized_build_option, + output_dir=output_dir, + ) + + linker = CppBuilder( + name=main_name, + sources=[ + main_builder.get_target_file_path(), + optimized_builder.get_target_file_path(), + ], + # pyrefly: ignore [bad-argument-type] + BuildOption=CppTorchDeviceOptions(**shared_compile_command), + output_dir=output_dir, + ) + + worker_fn = functools.partial( + _worker_compile_cpp, + lock_path, + (main_builder, optimized_builder, linker), + ) + binary_path = normalize_path_separator(linker.get_target_file_path()) + else: + worker_fn = functools.partial( + _worker_compile_cpp, lock_path, (main_builder,) + ) + binary_path = normalize_path_separator( + main_builder.get_target_file_path() + ) + + def load_fn() -> Any: + nonlocal lib + if lib is None: + if future is not None: + future.result() + result = worker_fn() + if result is not None: + raise AssertionError( + f"worker_fn expected to return None, got {type(result)}" + ) + lib = cls._load_library(binary_path, key) + if lib is None: + raise AssertionError( + f"Failed to load library from {binary_path}" + ) + return lib + + if submit_fn is not None: + with FileLock(lock_path, timeout=LOCK_TIMEOUT): + if not os.path.exists(binary_path): + future = submit_fn(worker_fn) + + cls.cache[key] = load_fn + + return cls.cache[key] + + @classmethod + def load(cls, *args: Any, **kwargs: Any) -> Any: + return cls.load_async(*args, **kwargs)() + + +def _worker_compile_cpp( + lock_path: str, + cpp_builders: Sequence[CppBuilder], +) -> None: + from torch.utils._filelock import FileLock + + with FileLock(lock_path, timeout=LOCK_TIMEOUT): + for builder in cpp_builders: + if not os.path.exists(builder.get_target_file_path()): + builder.build() + + +# Customized Python binding for cpp kernels +@clear_on_fresh_cache +class CppPythonBindingsCodeCache(CppCodeCache): + cache: dict[str, Callable[[], CDLL | ModuleType]] = {} + _loaded_module_names: OrderedSet[str] = OrderedSet() + + @staticmethod + def cache_clear() -> None: + CppPythonBindingsCodeCache.cache.clear() + for name in CppPythonBindingsCodeCache._loaded_module_names: + sys.modules.pop(name, None) + CppPythonBindingsCodeCache._loaded_module_names.clear() + + cpp_compile_command_flags = { + # kernels have no dependency on libtorch + "include_pytorch": False, + "shared": True, + } + entry_function = "kernel" + call_entry_function = "kernel({}); Py_RETURN_NONE;" + extra_parse_arg = "" + suffix_template = textwrap.dedent( + """ + // Python bindings to call {entry_func}(): + #define PY_SSIZE_T_CLEAN + #include + #include + #include + #include + + // This is defined in guards.cpp so we don't need to import PyTorch headers that are slooow. + // We manually link it below to workaround issues with fbcode build. + static void* (*_torchinductor_pyobject_tensor_data_ptr)(PyObject* obj); + + template static inline T parse_arg(PyObject* args, size_t n) {{ + static_assert(std::is_pointer_v, "arg type must be pointer or long"); + return static_cast(_torchinductor_pyobject_tensor_data_ptr(PyTuple_GET_ITEM(args, n))); + }} + template <> inline int64_t parse_arg(PyObject* args, size_t n) {{ + auto result = PyLong_AsSsize_t(PyTuple_GET_ITEM(args, n)); + if(result == -1 && PyErr_Occurred()) [[unlikely]] + throw std::runtime_error("expected int arg"); + return result; + }} + template <> inline uintptr_t parse_arg(PyObject* args, size_t n) {{ + auto result = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, n)); + if(result == reinterpret_cast(-1) && PyErr_Occurred()) [[unlikely]] + throw std::runtime_error("expected int arg"); + return reinterpret_cast(result); + }} + template <> inline float parse_arg(PyObject* args, size_t n) {{ + auto result = PyFloat_AsDouble(PyTuple_GET_ITEM(args, n)); + if(result == -1.0 && PyErr_Occurred()) [[unlikely]] + throw std::runtime_error("expected float arg"); + return static_cast(result); + }} + + {extra_parse_arg} + + static PyObject* {entry_func}_py(PyObject* self, PyObject* args) {{ + try {{ + if(!PyTuple_CheckExact(args)) [[unlikely]] + throw std::runtime_error("tuple args required"); + if(PyTuple_GET_SIZE(args) != {arg_len}) [[unlikely]] + throw std::runtime_error("requires {arg_len} args"); + {call_entry_func} + }} catch(std::exception const& e) {{ + PyErr_SetString(PyExc_RuntimeError, e.what()); + return nullptr; + }} catch(...) {{ + PyErr_SetString(PyExc_RuntimeError, "unhandled error"); + return nullptr; + }} + }} + + static PyMethodDef py_methods[] = {{ + {{"{entry_func}", {entry_func}_py, METH_VARARGS, ""}}, + {{NULL, NULL, 0, NULL}}}}; + + static struct PyModuleDef py_module = + {{PyModuleDef_HEAD_INIT, "{entry_func}", NULL, -1, py_methods}}; + + PyMODINIT_FUNC PyInit_{entry_func}(void) {{ + const char* str_addr = std::getenv("_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR"); + if(!str_addr) {{ + PyErr_SetString(PyExc_RuntimeError, "_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR must be set"); + return nullptr; + }} + + char* endptr = nullptr; + errno = 0; + uintptr_t addr = std::strtoull(str_addr, &endptr, 10); + if(errno != 0 || endptr == str_addr || addr == 0) {{ + PyErr_SetString(PyExc_RuntimeError, "Failed to parse _TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR"); + return nullptr; + }} + _torchinductor_pyobject_tensor_data_ptr = + reinterpret_cast(addr); + PyObject* module = PyModule_Create(&py_module); + if (module == NULL) {{ + return NULL; + }} + #ifdef Py_GIL_DISABLED + PyUnstable_Module_SetGIL(module, Py_MOD_GIL_NOT_USED); + #endif + return module; + }} + """ + ) + + @classmethod + # pyrefly: ignore [bad-override] + def _load_library_inner(cls, path: str, key: str) -> ModuleType: + os.environ["_TORCHINDUCTOR_PYOBJECT_TENSOR_DATA_PTR"] = str( + torch._C._dynamo.guards._torchinductor_pyobject_tensor_data_ptr # type: ignore[attr-defined] + ) + module_name = f"{key}.{cls.entry_function}" + try: + return sys.modules[module_name] + except KeyError: + pass + spec = importlib.util.spec_from_file_location(module_name, path) + if spec is None: + raise AssertionError( + f"Failed to create module spec for {module_name} from {path}" + ) + module = importlib.util.module_from_spec(spec) + sys.modules[module_name] = module + CppPythonBindingsCodeCache._loaded_module_names.add(module_name) + if spec.loader is None: + raise AssertionError(f"Module spec for {module_name} has no loader") + spec.loader.exec_module(module) + return module + + @classmethod + def _get_uncompiled_header(cls, device: str) -> str | None: + return _get_cpp_prefix_header(device) + + @classmethod + def load_pybinding_async( + cls, + argtypes: Sequence[str], + main_code: str, + device_type: str = "cpu", + needs_vec_isa: bool | None = None, + kernel_needs_vec_isa: bool | None = None, + num_outputs: int = -1, + submit_fn: Any = None, + extra_flags: Sequence[str] = (), + kernel_code: str | None = None, + ) -> Any: + """ + Wrap a C++ function in fast Python bindings. + + Args: + argtypes: The types of args to ENTRY_FUNCTION(), e.g. ["float*", "long"] + main_code: C++ source code containing ENTRY_FUNCTION(). Will be built at + -O3 if kernel_code is None (to maximize performance in any kernels that + are present), or -O1 otherwise (to minimize compile time). + needs_vec_isa: Whether the generated wrapper requires CPU vectorized + host helpers. If omitted, this is inferred from the generated + source as a conservative fallback. + kernel_needs_vec_isa: Whether the separately compiled kernel source + requires CPU vectorized host helpers. Only relevant when + kernel_code is provided. + kernel_code: If present, C++ source code that will be built at -O3 and + linked to main_code. + + Returns: + A python version of ENTRY_FUNCTION() + """ + parseargs = ", ".join( + f"parse_arg<{argtype.replace('const ', '')}>(args, {n})" + for n, argtype in enumerate(argtypes) + ) + suffix = cls.suffix_template.format( + arg_len=len(argtypes), + call_entry_func=cls.call_entry_function.format(parseargs), + entry_func=cls.entry_function, + extra_parse_arg=cls.extra_parse_arg.format(array_len=num_outputs), + ) + get_result = cls.load_async( + main_code + suffix, + device_type, + submit_fn=submit_fn, + extra_flags=extra_flags, + optimized_code=kernel_code, + needs_vec_isa=needs_vec_isa, + kernel_needs_vec_isa=kernel_needs_vec_isa, + ) + result = None + + def future() -> Any: + nonlocal result + if result is None: + result = get_result() + if not isinstance(result, ModuleType): + raise AssertionError(f"Expected ModuleType, got {type(result)}") + return getattr(result, cls.entry_function) + + return future + + @classmethod + def load_pybinding(cls, *args: Any, **kwargs: Any) -> Any: + return cls.load_pybinding_async(*args, **kwargs)() + + +@clear_on_fresh_cache +class CppWrapperCodeCache(CppPythonBindingsCodeCache): + cache: dict[str, Callable[[], CDLL | ModuleType]] = {} + + @staticmethod + def cache_clear() -> None: + CppWrapperCodeCache.cache.clear() + + @classmethod + def load_pybinding(cls, *args: Any, **kwargs: Any) -> Any: + # The cpp_wrapper host glue is compiled synchronously here (in the JIT + # torch.compile path this runs while importing the generated wrapper + # module, and in AOTI it runs during the autotune pass). Time it under a + # dedicated key so the host C++ cold-compile cost is attributed to + # cpp_wrapper instead of being hidden inside the generic + # PyCodeCache.load_by_key_path timer. + with dynamo_timed("cpp_wrapper_compile", log_pt2_compile_event=True): + return super().load_pybinding(*args, **kwargs) + + cpp_compile_command_flags = { + "include_pytorch": True, + "shared": True, + } + entry_function = "inductor_entry_cpp" + call_entry_function = "return inductor_entry_cpp({});" + extra_parse_arg = textwrap.dedent( + """ + #include + + static inline std::vector unpack_tensor_handle_list(PyObject* pyvec) {{ + std::vector result; + size_t result_len = PyList_GET_SIZE(pyvec); + result.reserve(result_len); + for (size_t i = 0; i < result_len; i++) {{ + PyObject* item = PyList_GET_ITEM(pyvec, i); + if (item == Py_None) {{ + result.push_back(nullptr); + continue; + }} + // AtenTensorHandle is essentially a pointer + void* elem = PyCapsule_GetPointer(item, NULL); + if (elem == nullptr && PyErr_Occurred()) {{ + PyErr_Clear(); + throw std::runtime_error( + "expected input handle to be a PyCapsule or None" + ); + }} + result.push_back(reinterpret_cast(elem)); + }} + return result; + }} + + static inline PyObject* pack_tensor_handle_list(const std::array& arr) {{ + PyObject* result = PyList_New({array_len}); + for (size_t i = 0; i < {array_len}; i++) {{ + PyObject *elem = + arr[i] == nullptr + ? Py_NewRef(Py_None) + // Store AtenTensorHandle as PyCapsulate + : PyCapsule_New(reinterpret_cast(arr[i]), NULL, NULL); + PyList_SET_ITEM(result, i, elem); + }} + return result; + }} + + template <> inline std::vector parse_arg>(PyObject* args, size_t n) {{ + return unpack_tensor_handle_list(PyTuple_GET_ITEM(args, n)); + }} + + PyObject* inductor_entry_cpp(std::vector&& input_handles) {{ + // For outputs, we only allocate an array to hold returned tensor handles, + // not the actual output tensor storage. + std::array output_handles{{}}; + try {{ + inductor_entry_impl(input_handles.data(), output_handles.data()); + if (PyErr_Occurred()) {{ + return nullptr; + }} + return pack_tensor_handle_list(output_handles); + }} catch(std::exception const& e) {{ + PyErr_SetString(PyExc_RuntimeError, e.what()); + return nullptr; + }} catch(...) {{ + PyErr_SetString(PyExc_RuntimeError, "unhandled error"); + return nullptr; + }} + }} + """ + ) + + @classmethod + def _get_uncompiled_header(cls, device: str) -> str | None: + return _get_cpp_wrapper_header(device) + + +@clear_on_fresh_cache +class HalideCodeCache(CppPythonBindingsCodeCache): + cache: dict[str, Callable[[], ModuleType | CDLL]] = {} + cache_clear = staticmethod(cache.clear) + _standalone_runtime_path: str | None = None + prefix = textwrap.dedent( + """ + #include "{halideruntime_h}" + #include "{headerfile}" + #include + #include + + namespace c10 {{ + inline long div_floor_integer(long a, long b) {{ + if ((a<0) != (b<0)) {{ + const auto quot = a / b; + const auto rem = a % b; + return rem ? quot - 1 : quot; + }} + return a / b; + }} + }} + """ + ) + glue_template_cpp = prefix + textwrap.dedent( + """ + void kernel({argdefs}) {{ + {buffers} + int err = halide_kernel({buffer_names}); + if(err != 0) throw std::runtime_error("halide_kernel failed"); + }} + """ + ) + glue_template_cuda = prefix + textwrap.dedent( + """ + #include + static const halide_device_interface_t* cuda_interface = halide_cuda_device_interface(); + + void kernel({argdefs}, uintptr_t stream) {{ + {buffers} + int err = halide_kernel(reinterpret_cast(stream), {buffer_names}); + if(err != 0) throw std::runtime_error("halide_kernel failed"); + }} + """ + ) + standalone_runtime_cuda_init = textwrap.dedent( + """ + #include "{}" + #include + + static int acquire_context(void* user_context, + void** cuda_context_out, + bool create) {{ + return cuCtxGetCurrent(reinterpret_cast(cuda_context_out)); + }} + + static int release_context(void* user_context) {{ + return 0; + }} + + static int get_stream(void* user_context, + void* cuda_context, + void** stream_out) {{ + *stream_out = user_context; + return 0; + }} + + static int register_halide_hooks() {{ + halide_set_cuda_acquire_context(&acquire_context); + halide_set_cuda_release_context(&release_context); + halide_set_cuda_get_stream(&get_stream); + return 0; + }} + + int inductor_register_halide_hooks_result = register_halide_hooks(); + """ + ) + + @classmethod + def _codegen_buffer(cls, name: str, arg: HalideInputSpec, cuda: bool) -> list[str]: + if arg.shape is None: + raise AssertionError(f"arg.shape is None for {name}") + if arg.stride is None or len(arg.shape) != len(arg.stride): + raise AssertionError( + f"arg.stride is None or shape/stride length mismatch for {name}: " + f"shape={arg.shape}, stride={arg.stride}" + ) + if arg.offset is None: + raise AssertionError(f"arg.offset is None for {name}") + data_ptr = f"{arg.alias_of or arg.name} + {arg.offset}" + if cuda: + device = f"reinterpret_cast({data_ptr})" + device_interface = "cuda_interface" + host = "nullptr" + flags = "halide_buffer_flag_device_dirty" + else: + device = "0" + device_interface = "nullptr" + host = f"reinterpret_cast({data_ptr})" + flags = "halide_buffer_flag_host_dirty" + + dims = [] + for size, stride in zip(arg.shape, arg.stride): + dims.append(f"halide_dimension_t(0, {size}, {stride})") + + return [ + f"halide_buffer_t {name};", + f"halide_dimension_t {name}_dims[] = {{{', '.join(dims)}}};" + if len(dims) > 0 + else f"halide_dimension_t * {name}_dims = nullptr;", + f"{name}.device = {device};", + f"{name}.device_interface = {device_interface};", + f"{name}.host = {host};", + f"{name}.flags = {flags};", + f"{name}.type = {arg.halide_type()};", + f"{name}.dimensions = {len(dims)};", + f"{name}.dim = {name}_dims;", + f"{name}.padding = nullptr;", + ] + + @classmethod + def _codegen_glue(cls, meta: HalideMeta, headerfile: object) -> str: + is_cuda = meta.is_cuda() + if is_cuda is not ("user_context" in meta.target): + raise AssertionError( + f"is_cuda={is_cuda} inconsistent with meta.target={meta.target}" + ) + if "no_runtime" not in meta.target: + raise AssertionError(f"'no_runtime' not found in meta.target={meta.target}") + buffers = [] + buffer_names = [] + for i, arg in enumerate(meta.argtypes): + if arg.is_buffer(): + # pyrefly: ignore [bad-argument-type] + buffer_names.append(f"&hl_buf_{i}") + buffers.extend(cls._codegen_buffer(f"hl_buf_{i}", arg, is_cuda)) + else: + if "*" in arg.ctype: + raise AssertionError( + f"Unexpected pointer type in non-buffer arg: {arg.ctype}" + ) + # pyrefly: ignore [bad-argument-type] + buffer_names.append(arg.name) + buffers = "\n".join([f" {line}" for line in buffers]).lstrip() + + glue_template = cls.glue_template_cuda if is_cuda else cls.glue_template_cpp + glue_code = glue_template.format( + halideruntime_h=cls.find_header( + "HalideRuntimeCuda.h" if is_cuda else "HalideRuntime.h" + ), + headerfile=headerfile, + argdefs=", ".join( + f"{a.bindings_type()} {a.name}" + for a in meta.argtypes + if a.alias_of is None + ), + buffers=buffers, + buffer_names=", ".join(buffer_names), + ) + return glue_code + + @classmethod + @functools.cache + def config_hash(cls) -> str: + command_gen = CppBuilder( + name="O", + sources="I", + BuildOption=CppOptions(), + ) + command_line = command_gen.get_command_line() + return sha256_hash( + "\n".join( + [ + cls.glue_template_cpp, + cls.glue_template_cuda, + cls.standalone_runtime_cuda_init, + command_line, + ] + ).encode("utf-8") + ) + + @staticmethod + def _search_for_file(suffix: str, errmsg: str) -> str: + spec = importlib.machinery.PathFinder.find_spec("halide") + if spec is None or not spec.submodule_search_locations: + raise RuntimeError("halide python bindings not installed") + try: + search = spec.submodule_search_locations[0] + for file in os.listdir(search): + if file.endswith(".so"): + try: + out = subprocess.check_output( + ["ldd", os.path.join(search, file)] + ) + except subprocess.SubprocessError: + continue + m = re.search(r"(/.*)/libHalide.so", out.decode("utf-8")) + if m: + path = os.path.join(os.path.abspath(m.group(1)), suffix) + if os.path.exists(path): + return os.path.abspath(path) + except Exception as e: + raise RuntimeError(errmsg) from e + raise RuntimeError(errmsg) + + @staticmethod + @functools.cache + def find_libautoschedule(name: str) -> str: + sofile = f"libautoschedule_{name.lower()}.so" + if "HALIDE_LIB" in os.environ: + path = os.path.join(os.environ["HALIDE_LIB"], sofile) + if os.path.exists(path): + return path + errmsg = ( + f"Can't find {sofile}, set env HALIDE_LIB to the directory containing it" + ) + return HalideCodeCache._search_for_file(sofile, errmsg) + + @staticmethod + @functools.cache + def find_header(name: str) -> str: + if "HALIDE_INCLUDE" in os.environ: + path = os.path.join(os.environ["HALIDE_INCLUDE"], name) + if os.path.exists(path): + return path + if "HALIDE_LIB" in os.environ: + path = os.path.abspath( + os.path.join(os.environ["HALIDE_LIB"], f"../include/{name}") + ) + if os.path.exists(path): + return path + errmsg = ( + f"Can't find {name}, set env HALIDE_INCLUDE to the directory containing it" + ) + return HalideCodeCache._search_for_file(f"../include/{name}", errmsg) + + @classmethod + def generate_halide_async( + cls, meta: HalideMeta, source_code: str, submit_fn: Any = None + ) -> Callable[[], Any]: + dirpath = Path( + get_path( + code_hash( + source_code, + extra=repr((cls.config_hash(), meta)), + ), + "halide", + )[2] + ) + os.makedirs(dirpath, exist_ok=True) + wait_for_compile = None + genfile = str(dirpath / "generate_kernel.py") + libfile = str(dirpath / "halide_kernel.a") + headerfile = str(dirpath / "halide_kernel.h") + donefile = str(dirpath / "done") + lockfile = str(dirpath / "lock") + need_compile = not os.path.exists(donefile) + jobs: list[Any] = [] + if need_compile: + write_atomic(genfile, source_code) + cmd = [ + sys.executable, + genfile, + "-g", + "kernel", + "-o", + f"{dirpath}", + "-f", + "halide_kernel", + "-e", + "static_library,h,schedule", + ] + if meta.scheduler: + cmd.extend(["-p", cls.find_libautoschedule(meta.scheduler)]) + cmd.extend(meta.args()) + jobs.append(functools.partial(subprocess.check_call, cmd)) + + binding_types = [ + arg.bindings_type() for arg in meta.argtypes if arg.alias_of is None + ] + if meta.is_cuda(): + binding_types.append("uintptr_t") # stream + bindings_future = cls.load_pybinding_async( + binding_types, + cls._codegen_glue(meta, headerfile), + extra_flags=(libfile, cls.build_standalone_runtime()), + submit_fn=jobs.append if need_compile else None, + device_type="cuda" if meta.is_cuda() else "cpu", + ) + + if need_compile: + jobs.append(functools.partial(touch, donefile)) + task = functools.partial(_worker_task_halide, lockfile, jobs) + if submit_fn: + wait_for_compile = submit_fn(task).result + else: + task() + + def load() -> Callable[[], Any]: + if wait_for_compile: + wait_for_compile() + return bindings_future() + + return load + + @classmethod + def generate_halide(cls, *args: Any, **kwargs: Any) -> Callable[[], Any]: + return cls.generate_halide_async(*args, **kwargs)() + + @classmethod + def build_standalone_runtime(cls) -> str: + if cls._standalone_runtime_path and os.path.exists( + cls._standalone_runtime_path + ): + return cls._standalone_runtime_path + device_type = "cuda" if torch.cuda.is_available() else "cpu" + libname = "libStandaloneHalideRuntime.so" + target = "host-cuda" if device_type == "cuda" else "host" + if cls._standalone_runtime_path: + if os.path.exists(cls._standalone_runtime_path): + raise AssertionError( + f"Standalone runtime path already exists: {cls._standalone_runtime_path}" + ) + # We hit this case in unittests when we run with fresh_cache() + # Generating a fresh runtime over and over causes errors because we initialize + # cuda hundreds of times in the same process and run out of file descriptors. + # Workaround by jail breaking the current fresh_cache(). + base = default_cache_dir() + else: + base = cache_dir() + dirpath = Path(base) / f"halide-runtime-{target}-{cls.config_hash()}" + os.makedirs(dirpath, exist_ok=True) + done_file = str(dirpath / "done") + lock_file = str(dirpath / "lock") + hook_file = str(dirpath / "hooks.cpp") + a_file = str(dirpath / "standalone_halide_runtime.a") + so_file = str(dirpath / libname) + if not os.path.exists(done_file): + import halide as hl # type: ignore[import-untyped,import-not-found] + + from torch.utils._filelock import FileLock + + with FileLock(lock_file, LOCK_TIMEOUT): + if not os.path.exists(done_file): + with open(hook_file, "w") as f: + if device_type == "cuda": + f.write( + cls.standalone_runtime_cuda_init.format( + cls.find_header("HalideRuntimeCuda.h") + ) + ) + hl.compile_standalone_runtime(a_file, hl.Target(target)) + + name, output_dir = get_name_and_dir_from_output_file_path(so_file) + halide_cmd_gen = CppBuilder( + name=name, + sources=[hook_file, a_file], + output_dir=output_dir, + BuildOption=CppTorchDeviceOptions( + device_type=device_type, + ), + ) + + subprocess.check_call( + shlex.split(halide_cmd_gen.get_command_line()) + ) + touch(done_file) + if not os.path.exists(so_file): + raise AssertionError(f"Halide runtime .so not found at {so_file}") + cls._standalone_runtime_path = so_file + return so_file + + @classmethod + def _get_uncompiled_header(cls, device: str) -> str | None: + """Header precompiling is currently disabled for halide.""" + return None + + +def _worker_task_halide(lockfile: str, jobs: list[partial[Any]]) -> None: + from torch.utils._filelock import FileLock + + try: + with FileLock(lockfile, LOCK_TIMEOUT): + for job in jobs: + job() + except subprocess.SubprocessError as e: + if os.environ.get("HALIDE_REPRO") == "1": + cmd: list[Any] + python, script, *cmd = getattr(e, "cmd", ("", "", "")) + if os.path.basename(python).startswith("python"): + code = Path(script).read_text() + main = " hl.main()" + if code.count(main) != 1: + raise AssertionError( + f"Expected exactly 1 occurrence of {main!r} in code, " + f"found {code.count(main)}" + ) from e + + class Out: + def __repr__(self) -> str: + return "out" + + ci = cmd.index("-o") + if not isinstance(ci, int): + raise AssertionError( + f"Expected int index from cmd.index, got {type(ci)}" + ) from e + # pyrefly: ignore [unsupported-operation] + cmd[ci + 1] = Out() + repl = textwrap.indent( + textwrap.dedent( + f"""\ + import sys, tempfile + with tempfile.TemporaryDirectory() as out: + sys.argv = {["repro.py", *cmd]!r} + hl.main() + """ + ), + " ", + ) + code = code.replace(main, repl) + with open("repro.py", "w") as fd: + fd.write(code.lstrip()) + raise RuntimeError(f"wrote repro.py: {e}") from e + raise + + +def touch(filename: str) -> None: + with open(filename, "a"): + pass + + +@clear_on_fresh_cache +class PyCodeCache: + """Caches generated Python modules and their source mappings.""" + + # Track the loaded modules so we can remove the on-disk artifacts when + # clearing the cache. Note also that we may load the same path more + # than once, but attach different attributes, i.e., due to different + # constant values. + modules: list[ModuleType] = [] + + # Modules loaded without extra attributes are stored here, those do not + # need to be re-loaded. + modules_no_attr: dict[str, ModuleType] = {} + + linemaps: dict[str, list[tuple[Any, ...]]] = {} + + @classmethod + def write(cls, source_code: str, extra: str = "") -> tuple[str, str]: + return write(source_code, "py", extra=extra) + + @classmethod + def load( + cls, + source_code: str, + extra: str = "", + *, + set_sys_modules: bool | None = None, + ) -> ModuleType: + key, path = write(source_code, "py", extra=extra) + return cls.load_by_key_path(key, path, set_sys_modules=set_sys_modules) + + @classmethod + def load_by_key_path( + cls, + key: str, + path: str, + linemap: list[tuple[int, str]] | None = None, + attrs: dict[str, Any] | None = None, + *, + set_sys_modules: bool | None = None, + ) -> ModuleType: + if linemap is None: + linemap = [] + + in_toplevel = in_toplevel_process() + set_sys_modules = in_toplevel if set_sys_modules is None else set_sys_modules + + # we only cache when attrs is None + if attrs is None and path in cls.modules_no_attr: + mod = cls.modules_no_attr[path] + if set_sys_modules: + sys.modules.setdefault(mod.__name__, mod) + return mod + + mod = _reload_python_module(key, path, set_sys_modules=set_sys_modules) + + # unzip into separate lines/nodes lists + if set_sys_modules: + cls.linemaps[path] = list(zip(*linemap)) + + if attrs is not None: + for k, v in attrs.items(): + setattr(mod, k, v) + + if in_toplevel: + # we only cache when attrs is None + if attrs is None: + cls.modules_no_attr[path] = mod + + cls.modules.append(mod) + return mod + + @classmethod + def cache_clear(cls, purge: bool = False) -> None: + """ + Clear the in-memory module cache. If purge=True, also delete all the + corresponding on-disk source files. + """ + if purge: + for mod in cls.modules: + try: + if not mod.__file__: + raise AssertionError(f"Module {mod} has no __file__ attribute") + os.remove(mod.__file__) + except FileNotFoundError: + pass + cls.modules.clear() + cls.modules_no_attr.clear() + + @classmethod + @functools.cache + def stack_frames_for_code( + cls, path: str, lineno: int + ) -> list[dict[str, Any]] | None: + if path not in cls.linemaps: + return None + if len(cls.linemaps[path]) == 0: + return None + # [(starting_line, ), ...] + lines, nodes = cls.linemaps[path] + p = bisect_right(lines, lineno) + if p == 0: + return None + entry = nodes[p - 1] + if not entry: + return None + + def parse_stack_trace(stack_trace: str) -> list[dict[str, Any]]: + # ideally fx stores stack traces as data rather than a string + # but this is not along a performance critical path + regex = r'File "(.+)", line (\d+), in (.+)\n' + matches = re.findall(regex, stack_trace) + return [ + {"filename": f, "line": int(l), "name": n} + for f, l, n in reversed(matches) + ] + + return parse_stack_trace(entry) + + +def _load_triton_kernel_from_source( + kernel_name: str, source_code: str +) -> CachingAutotuner: + return getattr(PyCodeCache.load(source_code), kernel_name) + + +@torch_key_cache +def cutlass_key() -> bytes: + """ + Compute a key representing the state of the CUTLASS library. + + Note: OSS and fbcode will have different keys. + """ + if config.is_fbcode(): + with ( + importlib.resources.path( + "cutlass_library", "src_hash.txt" + ) as resource_path, + open(resource_path) as resource_file, + ): + return resource_file.read().encode() + + combined_hash = hashlib.sha256() + build_code_hash([config.cutlass.cutlass_dir], "", combined_hash) + return combined_hash.digest() + + +class DLLWrapper: + """A wrapper for a dynamic library.""" + + def __init__( + self, + lib_path: str, + ) -> None: + self.lib_path = lib_path + self.is_open = False + self.open() + + def open(self) -> None: + if not self.is_open: + self.DLL = cdll.LoadLibrary(self.lib_path) + self.is_open = True + + def close(self) -> None: + if self.is_open: + self._dlclose() + self.is_open = False + + def _dlclose(self) -> None: + f_dlclose = None + # During Python interpreter shutdown, importing modules or calling + # dlclose is unsafe. Silently skip cleanup in that case. + try: + import sys + + if sys.is_finalizing(): + return + except Exception: + # import machinery may already be torn down + return + if is_linux(): + syms = CDLL(None) + if not hasattr(syms, "dlclose"): + # Apline Linux + syms = CDLL("libc.so") + + if hasattr(syms, "dlclose"): + f_dlclose = syms.dlclose + elif is_windows(): + import ctypes + + kernel32 = ctypes.CDLL("kernel32", use_last_error=True) + + f_dlclose = kernel32.FreeLibrary + else: + raise NotImplementedError("Unsupported env, failed to do dlclose!") + + if f_dlclose is not None: + if is_linux(): + f_dlclose.argtypes = [c_void_p] + f_dlclose(self.DLL._handle) + elif is_windows(): + import ctypes + from ctypes import wintypes + + f_dlclose.argtypes = [wintypes.HMODULE] + f_dlclose(self.DLL._handle) + else: + log.warning( + "dll unloading function was not found, library may not be unloaded properly!" + ) + + def __getattr__(self, name: str) -> Callable[..., None]: + if not self.is_open: + raise RuntimeError(f"Cannot use closed DLL library: {self.lib_path}") + + method = getattr(self.DLL, name) + + def _wrapped_func(*args: Any) -> None: + err = method(*args) + if err: + raise RuntimeError(f"Error in function: {method.__name__}") + + return _wrapped_func + + def __enter__(self) -> Self: + return self + + def __exit__(self, *args: Any) -> None: + self.close() + + def __del__(self) -> None: + self.close() + + +@lru_cache +def binary_error_path(output_path: str) -> str: + """ + standard format for the error path + """ + return output_path + ".error" + + +class CUTLASSCodeCache: + """ + A cache for managing the compilation and loading source code specifically for CUTLASS. + This class handles writing source code to files, compiling them into shared objects, and caching + the results to avoid redundant compilations. It also manages error handling and logging for the + compilation process. + """ + + @dataclasses.dataclass + class CacheEntry: + input_path: str + output_path: str + error_json: str | None = None + + cache: dict[str, CacheEntry] = {} + aot_kernels_o: list[str] = [] + + _SOURCE_CODE_SUFFIX: str = "" + _BACKEND: str = "" + _COMPILE_ERROR: type[exc.CppCompileError] = exc.CUDACompileError + + @classmethod + def cache_clear(cls) -> None: + cls.cache.clear() + cls.aot_kernels_o.clear() + cls.write.cache_clear() + + @staticmethod + @lru_cache(maxsize=4) + def get_kernel_binary_remote_cache( + caching_enabled: bool, caching_available: bool + ) -> Any | None: + """ + Get or create the class instance of the CUTLASSKernelBinaryRemoteCache. + + Args: + caching_enabled: Whether binary remote caching is enabled + caching_available: Whether we're in fbcode environment + + Returns: + CUTLASSKernelBinaryRemoteCache: The class instance of the kernel binary remote cache + """ + if not caching_enabled: + log.debug("CUTLASSKernelBinaryRemoteCache not requested, skipping") + return None + if not caching_available: + return None + + try: + from torch._inductor.fb.kernel_binary_remote_cache import ( + CUTLASSKernelBinaryRemoteCache, + ) + + return CUTLASSKernelBinaryRemoteCache() + except ImportError: + log.debug( + "CUTLASSKernelBinaryRemoteCache not available, remote caching disabled" + ) + return None + + @classmethod + def _use_re_build(cls) -> bool: + raise NotImplementedError + + @classmethod + def _compile_command( + cls, + src_files: list[str], + dst_file: str, + dst_file_ext: str, + extra_args: list[str] | None = None, + ) -> str: + raise NotImplementedError + + @classmethod + def _source_code_extra(cls) -> str: + raise NotImplementedError + + @classmethod + @lru_cache(None) + def write(cls, source_code: str, dst_file_ext: str) -> tuple[str, str]: + """ + Writes source code into a file with dst_file_ext as the file extension. + Returns the hash key of source code, and the path to the file. + """ + + if config.cutlass.cutlass_hash_with_compile_cmd: + compile_command = repr( + cls._compile_command(["dummy_input"], "dummy_output", dst_file_ext) + ) + extra = compile_command + else: + extra = cls._source_code_extra() + + key, input_path = write(source_code, cls._SOURCE_CODE_SUFFIX, extra=extra) + return key, input_path + + @classmethod + def compile( + cls, source_code: str, dst_file_ext: str, extra_args: list[str] | None = None + ) -> tuple[str, str, str]: + """ + Compiles CUDA source_code into a file with dst_file_ext extension. + If dst_file_ext is "so", first compiles to ".o" and then links to ".so". + Returns a tuple of dst_file_path, hash_key, source_code_path + """ + if dst_file_ext == "so": + # Two-step compilation: first compile to .o, then link to .so + obj_path, _, _ = cls.compile(source_code, "o", extra_args) + key, input_path = cls.write(source_code, dst_file_ext) + src_files, operation_name = [obj_path], "Linking" + else: + # Regular compilation for non-.so files + key, input_path = cls.write(source_code, dst_file_ext) + src_files, operation_name = [input_path], "Compilation" + + key_with_ext = key + dst_file_ext + if key_with_ext not in cls.cache: + 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_path = input_path[: -len(cls._SOURCE_CODE_SUFFIX)] + dst_file_ext + error_path = binary_error_path(output_path) + binary_remote_cache = cls.get_kernel_binary_remote_cache( + caching_enabled=config.cutlass.use_binary_remote_cache + and not config.force_disable_caches, + caching_available=config.is_fbcode(), + ) + if binary_remote_cache is not None: + # The remote cache implementation will only download if the file does + # not already exist locally + binary_remote_cache.get(output_path, error_path) + + if os.path.exists(error_path): + with open(error_path, encoding="utf-8") as fh: + error_json = fh.read() + cmd_parts, error_output = json.loads(error_json) + if ( + binary_remote_cache is not None + and config.cutlass.upload_to_binary_remote_cache + ): + # This ensures that a local error is uploaded to the remote cache, + # as we make no assumptions about the remote cache having the same + # information as the local cache + binary_remote_cache.put( + error_path, config.cutlass.binary_remote_cache_force_write + ) + cls.cache[key_with_ext] = cls.CacheEntry( + input_path, output_path, error_json + ) + raise cls._COMPILE_ERROR(cmd_parts, error_output) + if not os.path.exists(output_path): + cmd = cls._compile_command( + src_files, output_path, dst_file_ext, extra_args + ) + with open(input_path, "a") as f: + f.write("\n") + f.write(f"// {cls._BACKEND} {operation_name} cmd\n// {cmd}\n") + start_time = time() + log.debug("%s %s: %s", cls._BACKEND, operation_name, cmd) + cmd_parts = shlex.split(cmd) + try: + if cls._use_re_build(): + from triton.fb.re_build_helper import run_build_command + + run_build_command( + cmd_parts, + os.path.dirname(input_path), + os.path.basename(output_path), + ) + else: + subprocess.check_output( + cmd_parts, stderr=subprocess.STDOUT, env=os.environ + ) + except subprocess.CalledProcessError as error: + cls._record_compile_error( + error.output.decode("utf-8"), + key_with_ext, + cmd_parts, + input_path, + output_path, + binary_remote_cache, + ) + raise cls._COMPILE_ERROR(cmd_parts, error.output) from error + except Exception as error: + if "COMPILE FAILED WITH" in str(error): + cls._record_compile_error( + str(error), + key_with_ext, + cmd_parts, + input_path, + output_path, + binary_remote_cache, + ) + raise cls._COMPILE_ERROR(cmd_parts, str(error)) from error + raise error + end_time = time() + log_duration_msg = f"{cls._BACKEND} {operation_name} took {end_time - start_time} seconds. Command: {cmd}" + log.info(log_duration_msg) + + else: + log.debug( + "%s %s skipped: %s since output already exists", + cls._BACKEND, + operation_name, + output_path, + ) + # Upload to remote cache if enabled + if ( + binary_remote_cache is not None + and config.cutlass.upload_to_binary_remote_cache + ): + # will log on errors, but not fail out + binary_remote_cache.put( + output_path, config.cutlass.binary_remote_cache_force_write + ) + cls.cache[key_with_ext] = cls.CacheEntry(input_path, output_path, None) + + cache_entry: CUTLASSCodeCache.CacheEntry = cls.cache[key_with_ext] + if cache_entry.error_json is not None: + # Restore cached Exception and raise it as if we had compiled + cmd_parts, error_output = json.loads(cache_entry.error_json) + raise cls._COMPILE_ERROR(cmd_parts, error_output.encode("utf-8")) + return (cls.cache[key_with_ext].output_path, key, input_path) + + @classmethod + def load(cls, source_code: str, dst_file_ext: str) -> tuple[DLLWrapper, str, str]: + """ + Compiles source code and loads the generated .so file. + Returns a tuple of DLLWrapper, hash_key, source_code_path + """ + + if dst_file_ext != "so": + raise RuntimeError( + f"Only support loading a .so file for now. " + f"Requested file extension: {dst_file_ext}. Source code: {source_code}" + ) + dst_file_path, hash_key, source_code_path = cls.compile( + source_code, dst_file_ext + ) + return (DLLWrapper(dst_file_path), hash_key, source_code_path) + + @classmethod + def _record_compile_error( + cls, + error_str: str, + key_with_ext: str, + cmd_parts: list[str], + input_path: str, + output_path: str, + # Any here, as the import and type will only work in fbcode + # TODO: Make the typing hint strong here + binary_remote_cache: Any = None, + ) -> None: + error_json = json.dumps([cmd_parts, error_str]) + cls.cache[key_with_ext] = cls.CacheEntry(input_path, output_path, error_json) + error_path = binary_error_path(output_path) + with open(error_path, "w", encoding="utf-8") as fh: + fh.write(error_json) + + # Upload to remote cache directly from memory if enabled + if ( + binary_remote_cache is not None + and config.cutlass.upload_to_binary_remote_cache + ): + binary_remote_cache.put( + error_path, config.cutlass.binary_remote_cache_force_write + ) + + +@clear_on_fresh_cache +class CUDACodeCache(CUTLASSCodeCache): + _SOURCE_CODE_SUFFIX = "cu" + _BACKEND = "CUDA" + + @classmethod + def _use_re_build(cls) -> bool: + return cuda_compile_utils.use_re_build() + + @classmethod + def _compile_command( + cls, + src_files: list[str], + dst_file: str, + dst_file_ext: str, + extra_args: list[str] | None = None, + ) -> str: + return cuda_compile_utils.cuda_compile_command( + src_files, dst_file, dst_file_ext, extra_args=extra_args + ) + + @classmethod + def _source_code_extra(cls) -> str: + extra = repr( + [ + # nvcc and cuda hash + cuda_compile_utils._cuda_compiler(), + # cutlass flags and gcc hash + cuda_compile_utils._nvcc_compiler_options(), + # flags + cuda_compile_utils._nvcc_host_compiler_options(), + # cutlass key + cutlass_key(), + # hack to deal with AOTI .o compilation + ] + ) + return extra + + +from torch._inductor.codegen.xpu import compile_utils as xpu_compile_utils + + +@clear_on_fresh_cache +class XPUCodeCache(CUTLASSCodeCache): + _SOURCE_CODE_SUFFIX = "cpp" + _BACKEND = "XPU" + _COMPILE_ERROR: type[exc.CppCompileError] = exc.XPUCompileError + dll_cache: dict[str, DLLWrapper] = {} + + @classmethod + def cache_clear(cls) -> None: + super().cache_clear() + cls.dll_cache.clear() + + @classmethod + def _use_re_build(cls) -> bool: + return False + + @classmethod + def _compile_command( + cls, + src_files: list[str], + dst_file: str, + dst_file_ext: str, + extra_args: list[str] | None = None, + ) -> str: + return xpu_compile_utils.xpu_compile_command( + src_files, dst_file, dst_file_ext, extra_args=extra_args + ) + + @classmethod + def _source_code_extra(cls) -> str: + extra = repr( + [ + xpu_compile_utils._sycl_compiler(), + xpu_compile_utils._sycl_compiler_options(), + cutlass_key(), + ] + ) + return extra + + @classmethod + def load(cls, source_code: str, dst_file_ext: str) -> tuple[DLLWrapper, str, str]: + """ + Compiles source code and loads the generated .so file. + Returns a tuple of DLLWrapper, hash_key, source_code_path + """ + + if dst_file_ext != "so": + raise RuntimeError( + f"Only support loading a .so file for now. " + f"Requested file extension: {dst_file_ext}. Source code: {source_code}" + ) + dst_file_path, hash_key, source_code_path = cls.compile( + source_code, dst_file_ext + ) + if dst_file_path not in cls.dll_cache: + cls.dll_cache[dst_file_path] = DLLWrapper(dst_file_path) + + return (cls.dll_cache[dst_file_path], hash_key, source_code_path) + + +@clear_on_fresh_cache +class ROCmCodeCache: + """ + A cache for managing the compilation and loading source code specifically for ROCm. + This class handles writing source code to files, compiling them into shared objects, and caching + the results to avoid redundant compilations. + """ + + @dataclasses.dataclass + class CacheEntry: + input_path: str + output_path: str + + cache: dict[str, CacheEntry] = {} + aot_kernels_o: list[str] = [] + _SOURCE_CODE_SUFFIX = "cpp" + _logged_compiler_version = False + + @staticmethod + def cache_clear() -> None: + ROCmCodeCache.cache.clear() + ROCmCodeCache.aot_kernels_o.clear() + + @classmethod + def write(cls, source_code: str, dst_file_ext: str) -> tuple[str, str]: + """ + Writes source code into a file with dst_file_ext as the file extension. + Returns the hash key of source code, and the path to the file. + """ + + cuda_command = repr( + rocm_compile_command(["dummy_input"], "dummy_output", dst_file_ext) + ) + key, input_path = write( + source_code, cls._SOURCE_CODE_SUFFIX, extra=cuda_command + ) + return key, input_path + + @classmethod + def compile( + cls, source_code: str, dst_file_ext: str, extra_args: list[str] | None = None + ) -> tuple[str, str, str]: + """ + Compiles source_code into a file with dst_file_ext extension, + using the compile command specific for the ROCm platform. + Returns a tuple of dst_file_path, hash_key, source_code_path + """ + if not cls._logged_compiler_version: + cls._logged_compiler_version = True + log.debug(get_compiler_version_info(str(rocm_compiler()))) + + key, input_path = cls.write(source_code, dst_file_ext) + if key not in cls.cache: + 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_path = input_path[: -len(cls._SOURCE_CODE_SUFFIX)] + dst_file_ext + if not os.path.exists(output_path): + cmd = rocm_compile_command( + [input_path], output_path, dst_file_ext, extra_args + ) + start_time = time() + cmd_parts = cmd.split(" ") + try: + output = subprocess.check_output( + cmd_parts, + stderr=subprocess.STDOUT, + text=True, + env=os.environ, + ) + log.debug("Compilation output: %s", output) + except subprocess.CalledProcessError as error: + raise exc.CUDACompileError(cmd_parts, error.output) from error + end_time = time() + log_duration_msg = f"Compilation took {end_time - start_time} seconds. Compile command: {cmd}" + log.info(log_duration_msg) + else: + log.debug( + "Skip compiling %s: output %s already exists", + input_path, + output_path, + ) + cls.cache[key] = ROCmCodeCache.CacheEntry(input_path, output_path) + + return (cls.cache[key].output_path, key, input_path) + + @classmethod + def load(cls, source_code: str, dst_file_ext: str) -> tuple[DLLWrapper, str, str]: + """ + Compiles source code and loads the generated .so file. + Returns a tuple of DLLWrapper, hash_key, source_code_path + """ + + if dst_file_ext != "so": + raise RuntimeError( + f"Only support loading a .so file for now. " + f"Requested file extension: {dst_file_ext}. Source code: {source_code}" + ) + dst_file_path, hash_key, source_code_path = cls.compile( + source_code, dst_file_ext + ) + return (DLLWrapper(dst_file_path), hash_key, source_code_path) + + +class CodeCacheFuture: + def result(self, timeout: float | None = None) -> Callable[..., Any]: + raise NotImplementedError + + +class LambdaFuture(CodeCacheFuture): + def __init__( + self, result_fn: Callable[..., Any], future: Future[Any] | None = None + ) -> None: + self.result_fn = result_fn + self.future = future + + def result(self, timeout: float | None = None) -> Callable[..., Any]: + if timeout is not None and self.future is not None: + # Wait on the underlying cross-process future with the caller's + # timeout; raises concurrent.futures.TimeoutError if it does not + # resolve in time. result_fn will then consume the completed + # future without blocking further. + self.future.result(timeout=timeout) + return self.result_fn() + + +class StaticAutotunerFuture(CodeCacheFuture): + """ + A statically launchable CachingAutotuner, loaded from TritonBundler + """ + + def __init__(self, static_autotuner: CachingAutotuner) -> None: + # Pickled version of CachingAutotuner + self.static_autotuner = static_autotuner + # This needs to be set in AsyncCompile.triton, in case + # we need to reload the CachingAutotuner from its source code + # We don't store the source code on the CachingAutotuner itself + # since it can be very large. + self.reload_kernel_from_src: Callable[[], Any] | None = None + + def result(self, timeout: float | None = None) -> CachingAutotuner: + # timeout is accepted for interface parity with other CodeCacheFuture + # subclasses; this work is synchronous in-process and has no pending + # future to wait on. + if self.reload_kernel_from_src is None: + raise AssertionError( + "reload_kernel_from_src must be set before calling result()" + ) + with dynamo_timed("StaticAutotunerFuture.warm_precompile"): + self.static_autotuner.recheck_autotune_cache( + reload_kernel_from_src=self.reload_kernel_from_src + ) + self.static_autotuner.precompile( # type: ignore[union-attr] + warm_cache_only=False, + reload_kernel=self.reload_kernel_from_src, + static_triton_bundle_key=None, # no need to save again + ) + return self.static_autotuner diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..960c9874fa7ca379d27cbc1d9f15caa910fd93b6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/aoti_hipify_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/aoti_hipify_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8579bde8fc1a8fece8625fe883fbe5a4572641d7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/aoti_hipify_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/block_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/block_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1616915a3099905bad83739d343e1f24bdfa6df3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/block_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d68ccf8ad3841dc9fdee8de8464f15ee2867b2ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/common.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7580c2d8c245d106654e3a17c7f77f9103be2ce1040eefc2c408f0a3bae2a5a1 +size 150073 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95a558c9e34d111da68f03d6b016d84b2f7eb5b8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9bb32737923397f47a5eef74f245dfb33c5daba559c0220c275fd80a3fab5bad +size 295482 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_bmm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_bmm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..177187e2f3622eed89efa43fec9b7f51bf03f92d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_bmm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_flex_attention_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_flex_attention_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8f041a01dd9dbe46fd79652ae7e89cba9f0746c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_flex_attention_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_gemm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_gemm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a94caba6e0379967158d7c4d56e502c82d536fe2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_gemm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_grouped_gemm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_grouped_gemm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71671b9099a6bb4bc86645cdcf4558f794f0fac3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_grouped_gemm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_micro_gemm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_micro_gemm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fa96173b7a32e284e8a5a74929219cea39467ee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_micro_gemm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3175073347193d7adb6a0f4c0d7ce7721230e2d8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c852609eec35790ba1956337bbbb72bb5d362a0c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_template_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c06498476769359a3581a77d6cae0c464c104a8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10777a80fe959fd6a799e1361d2eea45e5d04d4a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5b4dfccff5574d081508c18d5f610a1598a85954fbaa9c78a5a515d630a64c5 +size 216475 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu_array_ref.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu_array_ref.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f5d273b6dfe5699d98d9b9cce2264263662b032 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu_array_ref.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_gpu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_gpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aeffd0c8418b5d8521d9f76ddfd4602ea7c6c4c8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_gpu.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_mps.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_mps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7a06e3c0ff36a6e9e3ba0f80b7ab67ac7be4ab5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpp_wrapper_mps.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpu_device_op_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpu_device_op_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f316a65b1b826c835e735cf309462dc1b00ceaa9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cpu_device_op_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cuda_combined_scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cuda_combined_scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78377d889b418447f4cf00c9b4a2908078a5c079 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/cuda_combined_scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/custom_extern_kernel_codegen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/custom_extern_kernel_codegen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c40046375aff65dd19290d8b0abf8d5369bef22 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/custom_extern_kernel_codegen.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/debug_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/debug_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdc8825adcfc873a7265dd87a7336da2f5e2f1d4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/debug_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/halide.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/halide.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7459875c335d82727879f0f4687230fe99519d1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/halide.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/memory_planning.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/memory_planning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8b2a706ff09f3857d5decc727c695e430a00f7f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/memory_planning.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/metal_flex_attention_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/metal_flex_attention_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04dd9c1a8f6a58ab534b1df8e5bfc6b3d29e43eb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/metal_flex_attention_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e233ab2379013fb8cbd7f08937a5d401f4fb3ac8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps_device_op_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps_device_op_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7418cc1d85929bab80c5d27a3904694befe2ef1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/mps_device_op_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/multi_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/multi_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b3991fb8b735c727bf81d070944222e33a6df11 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/multi_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/pallas.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/pallas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a14500427f5e21cb76ac5327f569d7a68a5d4143 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/pallas.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f819bbe4e1417e68614e4047a56347e87c59ee903eb63dcf552052505c86db3 +size 211817 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/python_wrapper_mtia.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/python_wrapper_mtia.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baef629bce0c924e1312bcd1cb2900a2b47b1ba6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/python_wrapper_mtia.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/segmented_tree.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/segmented_tree.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5eb5ddf7874c3a085d1264fadd1c5ee522ab12af Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/segmented_tree.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a32e1b9c0020d2031941ab29896bdf537dfe5c3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c78c72bc7463cb2838977be1d3a03c599489fe7fc0660998fad0d2fc8f80c2b7 +size 214585 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd_kernel_features.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd_kernel_features.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c19ef4724cd29d4d18349ead32fe87e39fcf7fdc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd_kernel_features.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/subgraph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/subgraph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66b2d9b26f011ef7930f4250dac1fb528e2bd4da Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/subgraph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5624821aa4556965c2a9825e0ad0f2794824231 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:05d6c248c591fa0e297fba04a0ec8b293eb381db0a7c87de1b6ffffa5de68fcb +size 378153 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_combo_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_combo_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84c53997a17a17b2e7148e9b354e8a6b665cea6b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_combo_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_split_scan.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_split_scan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2e27260f6e766177e763525d65edb7b0d73fc4d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_split_scan.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf67bdc7668c8e174d054eece4043d8301b65841 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8a29db0da56be4a0196783618f273834285ac95 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:901bc6bbd4c0e99ff473213312300d08be1a4793f2476340d37aedbeda591675 +size 261743 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper_fxir.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper_fxir.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aae2c285ac56c23506ea069519a88d61c33eab7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper_fxir.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_hipify_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_hipify_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bc6b5807c95f697bd8bb29666e4b9123de076094 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_hipify_utils.py @@ -0,0 +1,38 @@ +import re + +import torch + + +# It is not a good idea to directly apply hipify_torch to codegen, which will be vulnerable to cases like: +# "... +# from ..codecache import CudaKernelParamCache +# ..." +# In such cases, we do not need to hipify_torch the original class/file name in codegen/codecache + + +def maybe_hipify_code_wrapper(source_codes: str, force_hipify: bool = False) -> str: + if torch.version.hip is None and not force_hipify: + return source_codes + + try: + from torch.utils.hipify.hipify_python import PYTORCH_MAP, PYTORCH_TRIE + except ImportError: + # hipify not available for non-AMD builds + return source_codes + + def c2_repl(m: re.Match[str]) -> object: + return PYTORCH_MAP[m.group(0)] + + # We need to redefine RE_PYTORCH_PREPROCESSOR here since in hipify_torch, + # it will apply positive lookbehind (?<=\W) to the pattern to avoid matching + # keyword at the beginning of code line. However, this can happen in codegen, + # which will cause the pattern to not match. + + # Note that lookahead (?=\W|$) is still needed to keep hipification idempotent, for example + # we need to skip replacing "getStreamFromExternal" in "getStreamFromExternalMasqueradingAsCUDA". + # End-of-string must also count as a boundary so bare-token inputs like "CUfunction" + # (returned by device_codegen.cpp_kernel_type()) get hipified too. + RE_PYTORCH_PREPROCESSOR = re.compile(rf"({PYTORCH_TRIE.export_to_regex()})(?=\W|$)") + + source_codes = RE_PYTORCH_PREPROCESSOR.sub(c2_repl, source_codes) # type: ignore[arg-type] + return source_codes diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/interface.cpp b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/interface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a4416fba3d740509c23622c7cfd949b27a94903b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/interface.cpp @@ -0,0 +1,719 @@ +// Definition of AOTI runtime interface functions + +#include +#include + +#include +#include +#include +#include + +// Stores the last error message from a failed AOTI runtime call so that +// callers on the other side of the C ABI boundary can retrieve it via +// AOTInductorGetLastError(). Without this, exception messages (e.g. +// "CUDA error: an illegal memory access was encountered") are lost when +// CONVERT_EXCEPTION_TO_ERROR_CODE catches them and returns an error code. +static thread_local std::string g_aoti_last_error; + +#define CONVERT_EXCEPTION_TO_ERROR_CODE(...) \ + try { \ + g_aoti_last_error.clear(); \ + __VA_ARGS__ \ + } catch (const std::exception& e) { \ + g_aoti_last_error = e.what(); \ + std::cerr << "Error: " << e.what() << '\n'; \ + return AOTI_RUNTIME_FAILURE; \ + } catch (...) { \ + g_aoti_last_error = "Unknown exception"; \ + std::cerr << "Unknown exception occurred.\n"; \ + return AOTI_RUNTIME_FAILURE; \ + } \ + return AOTI_RUNTIME_SUCCESS; + +#define AOTI_VECTOR_SIZE_CHECK(actual_size, expected_size, name) \ + do { \ + AOTI_RUNTIME_CHECK( \ + actual_size == expected_size, \ + "expected " + std::string(name) + " vector size to be " + \ + std::to_string(expected_size) + ", but got " + \ + std::to_string(actual_size)); \ + } while (0) + +// AOTInductor uses at::addmm_out, which doesn't supports +// arguments that requires gradient. For this reason, we +// enforce no_grad context for run APIs. +// +// A RAII, thread local (!) guard that enables or disables grad mode upon +// construction, and sets it back to the original value upon destruction. +struct AOTINoGradGuard { + AOTINoGradGuard() { + aoti_torch_grad_mode_set_enabled(false); + } + AOTINoGradGuard(const AOTINoGradGuard&) = delete; + AOTINoGradGuard(AOTINoGradGuard&&) noexcept = delete; + ~AOTINoGradGuard() { + aoti_torch_grad_mode_set_enabled(prev_mode); + } + AOTINoGradGuard& operator=(const AOTINoGradGuard&) = delete; + AOTINoGradGuard& operator=(AOTINoGradGuard&&) noexcept = delete; + bool prev_mode{aoti_torch_grad_mode_is_enabled()}; +}; + +namespace { + +std::unordered_map constant_map_from_pairs( + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs) { + std::unordered_map input_map; + input_map.reserve(num_pairs); + for (size_t i = 0; i < num_pairs; ++i) { + input_map.emplace(pairs[i].name, pairs[i].handle); + } + return input_map; +} + +// Shared constructor for AOTInductorModelCreate / AOTInductorModelCreateV2. +// `populate(constant_map)` is called between model construction and +// optional embedded-blob loading. +template +AOTIRuntimeError createModelImpl( + AOTInductorModelHandle* model_handle, + bool load_constants_from_blob, + Populate&& populate) { + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto constant_map = std::make_shared(); + auto constant_array = std::make_shared< + std::vector>(); + auto* model = new torch::aot_inductor::AOTInductorModel( + constant_map, + constant_array, + // device_str is hardcoded, as AOTInductorModelCreate is only used + // for CPU models. + "cpu", + ""); + populate(*constant_map); + if (load_constants_from_blob) { + model->load_constants(); + } + *model_handle = reinterpret_cast(model); + }) +} + +} // namespace + +extern "C" { + +AOTIRuntimeError AOTInductorModelContainerCreate( + AOTInductorModelContainerHandle* container_handle, + size_t num_models, + bool is_cpu, + const char* cubin_dir) { + return AOTInductorModelContainerCreateWithDevice( + container_handle, + num_models, + is_cpu ? "cpu" : "cuda", + cubin_dir); +} + +AOTIRuntimeError AOTInductorModelContainerCreateWithDevice( + AOTInductorModelContainerHandle* container_handle, + size_t num_models, + const char* device_str, + const char* cubin_dir) { + + if (num_models == 0) { + std::cerr << "Error: num_models must be positive, but got 0\n"; + return AOTI_RUNTIME_FAILURE; + } + CONVERT_EXCEPTION_TO_ERROR_CODE({ + std::optional cubin_dir_opt; + if (cubin_dir != nullptr) { + cubin_dir_opt.emplace(cubin_dir); + } + auto* container = new torch::aot_inductor::AOTInductorModelContainer( + num_models, std::string(device_str), cubin_dir_opt); + *container_handle = + reinterpret_cast(container); + }) +} + + +AOTIRuntimeError AOTInductorModelContainerCreateWithExternalConstants( + AOTInductorModelContainerHandle* container_handle, + size_t num_models, + const char* device_str, + const char* cubin_dir, + const AOTInductorConstantMapEntry* constant_entries, + size_t num_constant_entries) { + if (num_models == 0) { + std::cerr << "Error: num_models must be positive, but got 0\n"; + return AOTI_RUNTIME_FAILURE; + } + if (num_constant_entries != 0 && constant_entries == nullptr) { + std::cerr << "Error: constant_entries is null but num_constant_entries is " + << num_constant_entries << "\n"; + return AOTI_RUNTIME_FAILURE; + } + CONVERT_EXCEPTION_TO_ERROR_CODE({ + std::optional cubin_dir_opt; + if (cubin_dir != nullptr) { + cubin_dir_opt.emplace(cubin_dir); + } + // Rebuild the std map on the DSO side of the boundary so no std container + // crosses the ABI; the entries are C-compatible (name + AtenTensorHandle). + std::unordered_map constants; + constants.reserve(num_constant_entries); + for (size_t i = 0; i < num_constant_entries; ++i) { + constants.emplace(constant_entries[i].name, constant_entries[i].handle); + } + auto* container = new torch::aot_inductor::AOTInductorModelContainer( + num_models, + std::string(device_str), + constants, + cubin_dir_opt); + *container_handle = + reinterpret_cast(container); + }) +} + +AOTIRuntimeError AOTInductorModelContainerDelete( + AOTInductorModelContainerHandle container_handle) { + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto* container = + reinterpret_cast( + container_handle); + delete container; + }); +} + +AOTIRuntimeError AOTInductorModelContainerRun( + AOTInductorModelContainerHandle container_handle, + AtenTensorHandle* input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + size_t num_inputs, + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + size_t num_outputs, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle) { + auto* container = + reinterpret_cast( + container_handle); + AOTI_VECTOR_SIZE_CHECK(num_inputs, container->num_inputs(), "inputs"); + AOTI_VECTOR_SIZE_CHECK(num_outputs, container->num_outputs(), "outputs"); + + auto stream = + reinterpret_cast(stream_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + AOTINoGradGuard guard; + container->run( + input_handles, output_handles, stream, proxy_executor_handle); + }) +} + +AOTIRuntimeError AOTInductorModelContainerRunSingleThreaded( + AOTInductorModelContainerHandle container_handle, + AtenTensorHandle* input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + size_t num_inputs, + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + size_t num_outputs, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle) { + auto* container = + reinterpret_cast( + container_handle); + AOTI_VECTOR_SIZE_CHECK(num_inputs, container->num_inputs(), "inputs"); + AOTI_VECTOR_SIZE_CHECK(num_outputs, container->num_outputs(), "outputs"); + + auto stream = + reinterpret_cast(stream_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + AOTINoGradGuard guard; + container->run_single_threaded( + input_handles, output_handles, stream, proxy_executor_handle); + }) +} + +AOTIRuntimeError AOTInductorModelContainerGetNumConstants( + AOTInductorModelContainerHandle container_handle, + size_t* num_constants) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *num_constants = container->num_constants(); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantName( + AOTInductorModelContainerHandle container_handle, + size_t idx, + const char** name) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *name = container->constant_name(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantOriginalFQN( + AOTInductorModelContainerHandle container_handle, + size_t idx, + const char** original_fqn) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *original_fqn = container->constant_original_fqn(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantFromFolded( + AOTInductorModelContainerHandle container_handle, + size_t idx, + bool* from_folded) { + auto* container = + reinterpret_cast(container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ *from_folded = container->constant_from_folded(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantType( + AOTInductorModelContainerHandle container_handle, + size_t idx, + int32_t* type) { + auto* container = + reinterpret_cast(container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ *type = container->constant_type(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantDtype( + AOTInductorModelContainerHandle container_handle, + size_t idx, + int32_t* dtype) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *dtype = container->constant_dtype(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantDataSize( + AOTInductorModelContainerHandle container_handle, + size_t idx, + size_t* data_size) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *data_size = container->constant_data_size(idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerExtractConstantsMap( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive) { + auto* container = + reinterpret_cast( + container_handle); + auto constants_map = reinterpret_cast*>(constant_map_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { const auto ret = container->extract_constants_map(use_inactive); + for (const auto& pair: ret) { + constants_map->emplace(pair.first, pair.second); + } + }) +} + +AOTIRuntimeError AOTInductorModelContainerExtractConstantsMapEntries( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry** entries, + size_t* num_entries, + bool use_inactive) { + if (!entries || !num_entries) { + return AOTI_RUNTIME_FAILURE; + } + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + const auto& extracted = + container->extract_constants_map_entries(use_inactive); + *entries = extracted.empty() ? nullptr : extracted.data(); + *num_entries = extracted.size(); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateUserManagedConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast( + container_handle); + auto input_map = reinterpret_cast*>(constant_map_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + *input_map, use_inactive, validate_full_update, /* user_managed = */ true); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateUserManagedConstantBufferPairs( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast(container_handle); + // Build a local unordered_map inside + std::unordered_map input_map; + input_map.reserve(num_pairs); + for (size_t i = 0; i < num_pairs; ++i) { + input_map.emplace(pairs[i].name, pairs[i].handle); + } + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + input_map, use_inactive, validate_full_update, /*user_managed=*/true); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast( + container_handle); + auto input_map = reinterpret_cast*>(constant_map_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + *input_map, use_inactive, validate_full_update); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateConstantBufferPairs( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast( + container_handle); + auto input_map = constant_map_from_pairs(pairs, num_pairs); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + input_map, use_inactive, validate_full_update); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateConstantBufferFromCpu( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast( + container_handle); + auto input_map = reinterpret_cast*>(constant_map_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + *input_map, + use_inactive, + validate_full_update, + /*user_managed=*/false, + /*allow_h2d_copy=*/true); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateConstantBufferFromCpuPairs( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs, + bool use_inactive, + bool validate_full_update) { + auto* container = + reinterpret_cast( + container_handle); + auto input_map = constant_map_from_pairs(pairs, num_pairs); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->update_constant_buffer( + input_map, + use_inactive, + validate_full_update, + /*user_managed=*/false, + /*allow_h2d_copy=*/true); + }) +} + +AOTIRuntimeError AOTInductorModelContainerUpdateInactiveConstantBuffer( + AOTInductorModelContainerHandle container_handle, + AOTInductorConstantMapHandle constant_map_handle) { + return AOTInductorModelContainerUpdateConstantBuffer( + container_handle, + constant_map_handle, + /*use_inactive=*/true, + /*validate_full_update=*/true); +} + +AOTIRuntimeError AOTInductorModelContainerUpdateInactiveConstantBufferPairs( + AOTInductorModelContainerHandle container_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs) { + return AOTInductorModelContainerUpdateConstantBufferPairs( + container_handle, + pairs, + num_pairs, + /*use_inactive=*/true, + /*validate_full_update=*/true); +} + +AOTIRuntimeError AOTInductorModelContainerFreeInactiveConstantBuffer( + AOTInductorModelContainerHandle container_handle) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->free_inactive_constant_buffer(); + }) +} + +AOTIRuntimeError AOTInductorModelContainerRunConstantFolding( + AOTInductorModelContainerHandle container_handle, + bool use_inactive, + AOTInductorStreamHandle stream_handle, + AOTIProxyExecutorHandle proxy_executor_handle) { + auto* container = + reinterpret_cast( + container_handle); + auto stream = + reinterpret_cast(stream_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + AOTINoGradGuard guard; + container->run_const_fold(use_inactive, stream, proxy_executor_handle); + }) +} + +AOTIRuntimeError AOTInductorModelContainerSwapConstantBuffer( + AOTInductorModelContainerHandle container_handle) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + container->swap_constant_buffer(); + }) +} + +AOTIRuntimeError AOTInductorModelContainerGetNumInputs( + AOTInductorModelContainerHandle container_handle, + size_t* ret_num_inputs) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *ret_num_inputs = container->num_inputs(); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetInputName( + AOTInductorModelContainerHandle container_handle, + size_t input_idx, + const char** ret_input_names) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *ret_input_names = container->input_name(input_idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetNumOutputs( + AOTInductorModelContainerHandle container_handle, + size_t* ret_num_outputs) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *ret_num_outputs = container->num_outputs(); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetOutputName( + AOTInductorModelContainerHandle container_handle, + size_t output_idx, + const char** ret_output_names) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *ret_output_names = container->output_name(output_idx); }) +} + +AOTIRuntimeError AOTInductorModelContainerGetCallSpec( + AOTInductorModelContainerHandle container_handle, + const char** in_spec, + const char** out_spec) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + *in_spec = container->get_in_spec(); + *out_spec = container->get_out_spec(); + }) +} + +AOTIRuntimeError AOTInductorModelCreate( + AOTInductorModelHandle* model_handle, + AOTInductorConstantMapHandle constant_map_handle) { + return createModelImpl( + model_handle, constant_map_handle == nullptr, [=](auto& constant_map) { + auto* input_map = reinterpret_cast< + std::unordered_map*>( + constant_map_handle); + if (input_map) { + for (const auto& kv : *input_map) { + constant_map.emplace(kv.first, kv.second); + } + } + }); +} + +AOTIRuntimeError AOTInductorModelCreateV2( + AOTInductorModelHandle* model_handle, + const AOTInductorConstantMapEntry* pairs, + size_t num_pairs) { + return createModelImpl( + model_handle, pairs == nullptr || num_pairs == 0, [=](auto& constant_map) { + if (pairs && num_pairs > 0) { + constant_map.reserve(num_pairs); + for (size_t i = 0; i < num_pairs; ++i) { + constant_map.emplace(pairs[i].name, pairs[i].handle); + } + } + }); +} + +AOTIRuntimeError AOTInductorModelRun( + AOTInductorModelHandle model_handle, + AtenTensorHandle* input_handles, + AtenTensorHandle* output_handles) { + auto model = + reinterpret_cast(model_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + AOTINoGradGuard guard; + model->run_impl( + input_handles, + output_handles, + (torch::aot_inductor::DeviceStreamType) nullptr, + nullptr); + }) +} + +AOTIRuntimeError AOTInductorModelDelete(AOTInductorModelHandle model_handle){ + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto model = reinterpret_cast( + model_handle); + delete model; + })} + +AOTIRuntimeError AOTInductorModelGetNumOutputs( + AOTInductorModelHandle model_handle, + size_t* ret_num_outputs) { + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto model = reinterpret_cast(model_handle); + *ret_num_outputs = model->num_outputs(); + }) +} + +AOTIRuntimeError AOTInductorModelUpdateConstantsMap( + AOTInductorModelHandle model_handle, + AOTInductorConstantMapHandle constant_map_handle) { + auto model = + reinterpret_cast(model_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto constant_map = std::make_shared(); + auto input_map = + reinterpret_cast*>( + constant_map_handle); + + for (auto const& kv : *input_map) { + constant_map->emplace(kv.first, kv.second); + } + model->update_constants_map(std::move(constant_map)); + }) +} + +// C-ABI-safe variant: uses an array of (name, handle) pairs instead of an +// opaque pointer to std::unordered_map, so the host and DSO can use +// different C++ standard libraries without ABI conflicts. +AOTIRuntimeError AOTInductorModelUpdateConstantsMapV2( + AOTInductorModelHandle model_handle, + const AOTInductorConstantMapEntry* pairs, + int32_t num_pairs) { + auto model = + reinterpret_cast(model_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + auto constant_map = std::make_shared(); + constant_map->reserve(num_pairs); + for (int32_t i = 0; i < num_pairs; ++i) { + constant_map->emplace(pairs[i].name, pairs[i].handle); + } + model->update_constants_map(std::move(constant_map)); + }) +} + +AOTIRuntimeError AOTInductorModelContainerGetConstantsBlobSize( + AOTInductorModelContainerHandle container_handle, + uint64_t* ret_size) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *ret_size = container->constant_blob_size(); }) +} + +AOTIRuntimeError AOTInductorModelContainerDidCallLoadConstants( + AOTInductorModelContainerHandle container_handle, + bool* did_call_load_constants) { + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + { *did_call_load_constants = container->did_call_load_constants(); }) +} + + +// Load weights from a single blob in weight_blob_ptr +AOTIRuntimeError AOTInductorModelUpdateConstantsFromBlob( + AOTInductorModelContainerHandle container_handle, + const uint8_t* weight_blob_ptr){ + auto* container = + reinterpret_cast( + container_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE( + {container->update_constants_from_blob(weight_blob_ptr); }) + } + +AOTIRuntimeError AOTInductorSetUsePinnedAsyncConstantsCopy(bool enabled) { + CONVERT_EXCEPTION_TO_ERROR_CODE({ + torch::aot_inductor::setUsePinnedAsyncConstantsCopy(enabled); + }) +} + +AOTIRuntimeError AOTInductorSetPinnedAsyncConstantsCopyStageBufferBytes( + size_t bytes) { + CONVERT_EXCEPTION_TO_ERROR_CODE({ + torch::aot_inductor::setPinnedAsyncConstantsCopyStageBufferBytes(bytes); + }) +} + +AOTIRuntimeError AOTInductorGetLastError( + const char** error_msg) { + *error_msg = g_aoti_last_error.c_str(); + return AOTI_RUNTIME_SUCCESS; +} + +} // extern "C" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/streams.h b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/streams.h new file mode 100644 index 0000000000000000000000000000000000000000..32e1c06459556c8ee7e85e16b0fac97728d908a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/aoti_runtime/streams.h @@ -0,0 +1,123 @@ +#ifndef AOTI_RUNTIME_STREAMS_H +#define AOTI_RUNTIME_STREAMS_H + +#include +#include +#include + +namespace torch::aot_inductor { + +struct AOTIPerThreadEventCache { + std::vector> events_by_device; + + std::vector& events(int device_idx) { + AOTI_RUNTIME_CHECK(device_idx >= 0, "AOTI event cache device index < 0"); + const auto slot = static_cast(device_idx); + if (events_by_device.size() <= slot) { + events_by_device.resize(slot + 1); + } + return events_by_device[slot]; + } + + void create(std::vector& events, std::size_t slot) { + AOTI_RUNTIME_CUDA_CHECK( + cudaEventCreateWithFlags(&events[slot], cudaEventDisableTiming)); + } + + cudaEvent_t get(int event_idx, int device_idx) { + AOTI_RUNTIME_CHECK(event_idx >= 0, "AOTI event cache event index < 0"); + auto& device_events = events(device_idx); + const auto slot = static_cast(event_idx); + if (device_events.size() <= slot) { + device_events.resize(slot + 1, nullptr); + } + if (device_events[slot] == nullptr) { + create(device_events, slot); + } + return device_events[slot]; + } + + ~AOTIPerThreadEventCache() { + for (auto& device_events : events_by_device) { + for (auto event : device_events) { + if (event == nullptr) { + continue; + } + auto code = cudaEventDestroy(event); + if (code != cudaSuccess) { + std::cerr + << "Failed to destroy CUDA event in AOTInductor stream cache: " + << cudaGetErrorString(code) << '\n'; + } + } + } + } +}; + +struct AOTIPerThreadStreamCache { + std::vector> streams_by_device; + + void check_not_capturing(cudaStream_t caller_stream) { + cudaStreamCaptureStatus capture_status; + AOTI_RUNTIME_CUDA_CHECK( + cudaStreamIsCapturing(caller_stream, &capture_status)); + AOTI_RUNTIME_CHECK( + capture_status == cudaStreamCaptureStatusNone, + "AOTI user streams are not supported during CUDA graph capture"); + } + + std::vector& streams(int device_idx) { + AOTI_RUNTIME_CHECK(device_idx >= 0, "AOTI stream cache device index < 0"); + const auto slot = static_cast(device_idx); + if (streams_by_device.size() <= slot) { + streams_by_device.resize(slot + 1); + } + return streams_by_device[slot]; + } + + void ensure(std::size_t count, int device_idx, cudaStream_t caller_stream) { + check_not_capturing(caller_stream); + auto& device_streams = streams(device_idx); + const std::size_t old_size = device_streams.size(); + if (old_size >= count) { + return; + } + device_streams.resize(count, nullptr); + for (std::size_t i = old_size; i < count; ++i) { + if (i == 0) { + continue; + } + AOTI_RUNTIME_CUDA_CHECK( + cudaStreamCreateWithFlags(&device_streams[i], cudaStreamNonBlocking)); + } + } + + cudaStream_t get(int stream_idx, int device_idx, cudaStream_t caller_stream) { + AOTI_RUNTIME_CHECK( + stream_idx > 0, + "AOTI aux stream cache slot 0 is reserved for the caller stream"); + const auto slot = static_cast(stream_idx); + ensure(slot + 1, device_idx, caller_stream); + return streams(device_idx)[slot]; + } + + ~AOTIPerThreadStreamCache() { + for (auto& device_streams : streams_by_device) { + for (auto stream : device_streams) { + if (stream == nullptr) { + continue; + } + auto code = cudaStreamDestroy(stream); + if (code != cudaSuccess) { + std::cerr + << "Failed to destroy CUDA stream in AOTInductor stream cache: " + << cudaGetErrorString(code) << '\n'; + } + } + } + } +}; + +} // namespace torch::aot_inductor + +#endif // AOTI_RUNTIME_STREAMS_H diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/block_analysis.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/block_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..adf9f293c4dc80358a5b2df30fdcff2ee1613124 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/block_analysis.py @@ -0,0 +1,222 @@ +import collections +import functools +import textwrap + +import sympy +from sympy import Expr, Symbol + +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import FloorDiv, ModularIndexing + +from ..utils import sympy_dot, sympy_subs +from ..virtualized import V + + +class BlockPatternMatcher: + """ + Matches block indexing expressions. + """ + + _indexing_wild_signed_int = functools.partial( + sympy.Wild, properties=[lambda x: x.is_integer] + ) + _indexing_wild_unsigned_int = functools.partial( + sympy.Wild, properties=[lambda x: x.is_integer and x.is_nonnegative] + ) + + @classmethod + def get_subexpr_involving_symbol(cls, expr: Expr, symbol: Symbol) -> Expr: + """ + Given a sympy expression, return the subexpression comprised only of terms + involving the specified symbol. + + For example, if `expr` is `x * 5 + x ** 2 + y * 2 + 5`, and `symbol` is `x`, + this returns `x * 5 + x ** 2`. + """ + expr = cls._preprocess(expr) + return sympy.S.Zero + sum( + term for term in sympy.Add.make_args(expr) if symbol in term.free_symbols + ) + + @staticmethod + def factor_index_expr(expr: sympy.Expr, index_var: Symbol) -> sympy.Expr: + """ + Given an index expression, factor the expression around + - FloorDiv(index_var, ...) + - ModularIndexing(index_var, ...) + - xindex + + e.g. FloorDiv(index_var, d0)*s0 + FloorDiv(index_var, d0)*s1 -> + FloorDiv(index_var, d0) * (s0 + s1) + """ + centres = OrderedSet() + for sub in sympy.preorder_traversal(expr): + if isinstance(sub, FloorDiv) and sub.args[0] == index_var: + centres.add(sub) + elif isinstance(sub, ModularIndexing) and sub.args[0] == index_var: + centres.add(sub) + centres.add(index_var) + + expr_out = expr + for c in centres: + expr_out = sympy.collect(expr_out, c) + return expr_out + + @staticmethod + def get_slice_numels(dims: list[Expr]) -> list[Expr]: + """ + Compute the cumulative size of each dimension's slice. + This proceeds from the last dim up to the second. + """ + numels = collections.deque([sympy.S.One]) + for dim in dims[:0:-1]: + numel = dim * numels[0] + numels.appendleft(numel) + return [*numels] + + @staticmethod + def _preprocess(expr: Expr) -> Expr: + # Remove any Identity nodes, e.g. expand x + (5 * y) to x + 5 * y. + # Disable mul and multinomial as those expansions affect op trees: + # e.g. sympy expects to match Mul(a, b), but expansion has simplified + # to Add(...). Even though they may be algebraically equivalent, + # sympy `match` performs structural pattern matching + return expr.expand(mul=False, multinomial=False, identity=True) + + @classmethod + def match_mod_div_block_expr( + cls, + index: Expr, + index_var: Symbol, + numel: Expr, + num_dims: int, + ) -> tuple[list[Expr], list[Expr], list[Expr]] | None: + """ + Matches modular indexing expressions, converting them to implied block dimensions and strides. + See triton.py for more information. + + Warning: this function requires that `index`, `numel` and any other sympy + expression does not have precomputed replacements since otherwise block + pattern matching may fail. + See [Note: Precomputed replacements with BlockPatternMatch] + """ + index = cls._preprocess(index) + + # Pattern match to find the strides and offset. + wild_unsigned_int = functools.partial( + cls._indexing_wild_unsigned_int, exclude=[index_var] + ) + wild_signed_int = functools.partial( + cls._indexing_wild_signed_int, exclude=[index_var] + ) + dims: list[Expr] = [ + wild_unsigned_int(f"dim_mod{idx}") for idx in range(num_dims) + ] + strides: list[Expr] = [ + wild_signed_int(f"stride_mod{idx}") for idx in range(num_dims) + ] + + # The first dimension's index is computed by division. + # The remaining are computed by modulo. + slice_numels = cls.get_slice_numels(dims[:num_dims]) + block_index_exprs = [FloorDiv(index_var, slice_numels[0])] + [ + ModularIndexing(index_var, numel, dim) + for dim, numel in zip(dims[1:], slice_numels[1:]) + ] + + # Calculate a linear index from block indices. + match_expr = sympy_dot(strides, block_index_exprs) + + # Heuristic: if the number of dimensions is high, check that the minimum requirements + # are met before attempting an expensive full match. see triton.py:match_mod_div_block + # for more details. In short, here we check that each subexpression in sympy.Add contains + # only FloorDiv or ModularIndexing expressions. + if num_dims >= 5: + stride = sympy.symbols("stride", cls=wild_signed_int) + denom, other = sympy.symbols("denominator other", cls=wild_unsigned_int) + mod_div_pattern = stride * ModularIndexing(index_var, denom, other) + floor_div_pattern = stride * FloorDiv(index_var, denom) + first_dim_floor_div_matched = False + match_failed = False + for arg in sympy.Add.make_args(index): + if arg.match(floor_div_pattern): + # There should only be a single FloorDiv(index, denom) expression + # corresponding to the first dimension + if first_dim_floor_div_matched: + match_failed = True + break + first_dim_floor_div_matched = True + elif arg.match(mod_div_pattern): + continue + else: + match_failed = True + break + + if match_failed: + return None + + # Pattern match. + match = index.match(match_expr) + if match is None: + return None + + # Provide default values for unmatched dims and strides. + for dim in dims[1:]: + if dim not in match: + match[dim] = sympy.S.One + for stride in strides[1:]: + if stride not in match: + match[stride] = sympy.S.Zero + + # Replace wildcards with matched expressions. + dims = [dims[0]] + [match[dim] for dim in dims[1:]] + strides = [match[stride] for stride in strides] + slice_numels = cls.get_slice_numels(dims) + block_index_exprs = [sympy_subs(expr, match) for expr in block_index_exprs] + + sizevars = V.graph.sizevars + + # The leading dimension is not directly matched in our expression. + # We solve for it by dividing the range tree numel by the product of + # all other dimensions. We quit if they are not known to be divisible. + if dims[0] in match: + raise AssertionError("Expected not to match the leading dimension!") + if not sizevars.statically_known_multiple_of(numel, slice_numels[0]): + return None + dims[0] = numel / slice_numels[0] + + # Sanity check that we can recover the index from the matched subexpressions. + matched_index = sympy_dot(strides, block_index_exprs) + if not sizevars.statically_known_equals( + matched_index, + index, + ): + raise AssertionError( + textwrap.dedent( + f""" + Invalid match! + Index: {index} + Matched expression: {matched_index} + """ + ) + ) + + return dims, strides, block_index_exprs + + @classmethod + def match_affine_block_expr( + cls, + index: Expr, + index_var: Symbol, + ) -> Expr | None: + """ + Matches simple expressions of the form stride * index, returning the + stride. + """ + index = cls._preprocess(index) + stride = cls._indexing_wild_signed_int(name="stride", exclude=[index_var]) + m = index.match(index_var * stride) + if m is None: + return None + + return m[stride] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/common.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/common.py new file mode 100644 index 0000000000000000000000000000000000000000..4a1470efee625867a3c9c476ad152e839996a461 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/common.py @@ -0,0 +1,3154 @@ +from __future__ import annotations + +import atexit +import contextlib +import dataclasses +import enum +import functools +import itertools +import logging +import math +import operator +import os +import re +import tempfile +import threading +from abc import ABC, abstractmethod +from enum import auto, Enum +from itertools import chain +from typing import Any, cast, ClassVar, Generic, NamedTuple, TYPE_CHECKING +from typing_extensions import Self, TypeVar + +import sympy + +import torch +import torch.fx +from torch._prims_common import ELEMENTWISE_TYPE_PROMOTION_KIND +from torch.utils import _pytree as pytree +from torch.utils._config_module import ConfigModule +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import Max +from torch.utils._sympy.numbers import int_oo +from torch.utils._sympy.printers import PythonPrinter as _PythonPrinter +from torch.utils._sympy.symbol import free_symbol_is_type, symbol_is_type, SymT +from torch.utils._sympy.value_ranges import bound_sympy, ValueRanges + +from .. import config, metrics +from ..dtype_propagation import DtypePropagationOpsHandler +from ..ops_handler import BasicMathOpsMixin, DefaultHandler +from ..shape_propagation import ShapePropagationOpsHandler +from ..utils import ( + boolean_ops, + DeferredLineBase, + generate_assert, + get_current_backend, + IndentedBuffer, + ir_dataclass, + ScopedDict, + sympy_dot, + sympy_index_symbol, + sympy_subs, + triton_type, + unique, +) +from ..virtualized import ( + NullHandler, + ops, + OpsHandler, + OpsValue, + ReductionType, + StoreMode, + V, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, MutableMapping, Sequence + + from torch.fx import GraphModule + + from ..custom_graph_pass import CustomGraphModulePass + from ..ir import Buffer, ChoiceCaller, FixedLayout, IRNode + from ..loop_body import LoopBody + from ..scheduler import BaseScheduling, Scheduler, SchedulerNode + from ..shape_propagation import BlockShapeType + from .wrapper import PythonWrapperCodegen + + _T = TypeVar("_T") + SchedulingConstructor = Callable[[Scheduler | None], BaseScheduling] + WrapperConstructor = type[PythonWrapperCodegen] + SymbolLike = str | sympy.Symbol + + # OpVarT should really be Union[CSEVariable, str], however this + # causes typing errors in subclasses (defined in other files). + OpVarT = str + +schedule_log = torch._logging.getArtifactLogger(__name__, "schedule") +log = logging.getLogger(__name__) + + +def data_type_logger(msg: str) -> None: + if schedule_log.isEnabledFor(logging.DEBUG): + schedule_log.debug("Data type propagation: %s", msg) + + +@dataclasses.dataclass +class FileBackedGraphModule: + """ + Output of FX wrapper codegen. Exposes the same methods as ModuleType, but these + map back to a GraphModule instead of Python source. + """ + + gm: GraphModule + compiled_fn: Callable[..., Any] + + def __post_init__(self) -> None: + # Write the code to a file for compatibility with debugging utilities. + # The file is deleted upon program termination. + self.tempfile = tempfile.NamedTemporaryFile( # noqa: SIM115 + mode="w+", suffix=".py", delete=False + ) + atexit.register(os.remove, self.tempfile.name) + with self.tempfile as f: + f.write(self.value) + + @property + def __file__(self) -> str: + return self.tempfile.name + + def call(self, args: list[Any]) -> Any: + return self.compiled_fn(*args) + + @property + def value(self) -> str: + return self.gm.code + + +class WorkspaceZeroMode(enum.Enum): + UNINITIALIZED = 0 + ZERO_ON_CALL = 1 # kernel may leave workspace dirty + ZERO_PER_GRAPH = 2 # must be re-zeroed by kernel + + @staticmethod + def combine(a: WorkspaceZeroMode, b: WorkspaceZeroMode) -> WorkspaceZeroMode: + if a == b or b == WorkspaceZeroMode.UNINITIALIZED: + return a + if a == WorkspaceZeroMode.UNINITIALIZED: + return b + raise NotImplementedError(f"WorkspaceZeroMode.combine({a!r}, {b!r})") + + @staticmethod + def from_bool(zero_fill: bool) -> WorkspaceZeroMode: + if zero_fill: + return WorkspaceZeroMode.ZERO_ON_CALL + return WorkspaceZeroMode.UNINITIALIZED + + +class CodegenSymbol(ABC): + """ + An IR object possibly corresponding to a variable in the wrapper code. + """ + + @abstractmethod + def get_name(self) -> str: + pass + + @abstractmethod + def get_example(self) -> torch.Tensor | sympy.Symbol: + pass + + +@ir_dataclass(frozen=True) +class WorkspaceArg(CodegenSymbol): + """A temporary buffer used for a single kernel, then discarded. + + Not registered as a traditional buffer since there are no users, + so it would be dead code eliminated. + + Args: + nbytes: The size of the buffer in bytes. + zero_fill: Whether the buffer should be initialized to zero. + + """ + + count: sympy.Expr + zero_mode: WorkspaceZeroMode + device: torch.device + outer_name: str + inner_name: str = "ws_ptr" + dtype: torch.dtype = torch.uint8 + + @staticmethod + def unique_name(prefix: str = "workspace_") -> str: + return f"{prefix}{next(V.graph.workspace_id)}" + + @staticmethod + def can_join(a: WorkspaceArg, b: WorkspaceArg) -> bool: + return ( + a.inner_name == b.inner_name and a.dtype == b.dtype and a.device == b.device + ) + + @staticmethod + def join(a: WorkspaceArg, b: WorkspaceArg) -> WorkspaceArg: + return WorkspaceArg( + count=a.count + b.count, + zero_mode=WorkspaceZeroMode.combine(a.zero_mode, b.zero_mode), + dtype=a.dtype, + device=a.device, + inner_name=a.inner_name, + outer_name=a.outer_name, + ) + + @staticmethod + def maximum(a: WorkspaceArg, b: WorkspaceArg) -> WorkspaceArg: + if not ( + a.dtype == b.dtype and a.device == b.device and a.inner_name == b.inner_name + ): + raise AssertionError( + "WorkspaceArg.maximum requires matching dtype, device, and inner_name" + ) + return WorkspaceArg( + count=Max(a.count, b.count), + zero_mode=WorkspaceZeroMode.combine(a.zero_mode, b.zero_mode), + dtype=a.dtype, + device=a.device, + inner_name=a.inner_name, + outer_name=a.outer_name, + ) + + # These methods let WorkspaceArg pretend it is a buffer to reuse allocation code + def get_device(self) -> torch.device: + return self.device + + get_device_or_error = get_device + + def get_dtype(self) -> torch.dtype: + return self.dtype + + def get_example(self) -> torch.Tensor | sympy.Symbol: + return self.get_layout().get_example() + + def get_layout(self) -> FixedLayout: + from ..ir import FixedLayout + + return FixedLayout( + device=self.device, + dtype=self.dtype, + size=[self.count], + stride=[1], + ) + + @property + def layout(self) -> FixedLayout: + return self.get_layout() + + get_output_spec = get_layout + maybe_get_output_spec = get_layout + maybe_get_layout = get_layout + + def get_offset(self) -> sympy.Expr: + return sympy.S.Zero + + def get_size(self) -> list[sympy.Expr]: + return [self.count] + + def get_stride(self) -> list[sympy.Expr]: + return [sympy.S.One] + + def get_name(self) -> str: + return self.outer_name + + def get_is_pinned(self) -> bool: + return False + + def get_inputs_that_alias_output(self) -> list[str]: + return [] + + +class TritonScratchWorkspace: + def __init__(self, size: int, generate_dtype_str: Callable[..., str]): + self.size = size + self._generate_dtype_str = generate_dtype_str + + def generate_dtype_str(self) -> str: + return self._generate_dtype_str() + + +@dataclasses.dataclass +class TensorArg: + name: str + buffer: str + dtype: torch.dtype + offset: sympy.Expr = sympy.S.Zero # c++ only + alias_of: str | None = None # halide only + + +@dataclasses.dataclass +class SizeArg: + name: str + expr: sympy.Expr + + @property + def alias_of(self) -> str | None: + return None + + +@dataclasses.dataclass +class ConstexprArg: + name: str + + +@dataclasses.dataclass +class TMADescriptorArg: + name: str + api_type: str # "experimental" or "stable" + block_shape: list[sympy.Expr] | None # only needed for "stable" + dtype: torch.dtype | None # only needed for "stable" + + +@dataclasses.dataclass +class DeviceCodegen: + scheduling: SchedulingConstructor + wrapper_codegen: WrapperConstructor + cpp_wrapper_codegen: WrapperConstructor | None = None + fx_wrapper_codegen: WrapperConstructor | None = None + + +KernelArgType = WorkspaceArg | TensorArg | SizeArg | TMADescriptorArg | ConstexprArg + +# Device index to emit into generated code: either a literal compile-time index, or a +# code expression evaluated at run time (e.g. current_device_idx_expr() under +# compile-on-one-rank). +DeviceIdx = int | str + +device_codegens: dict[str, DeviceCodegen] = {} + + +class DeviceOpOverrides: + def import_get_raw_stream_as(self, name: str) -> str: + raise NotImplementedError + + def set_device(self, device_idx: DeviceIdx) -> str: + raise NotImplementedError + + def synchronize(self) -> str: + raise NotImplementedError + + def device_guard(self, device_idx: DeviceIdx) -> str: + raise NotImplementedError + + def current_device_idx_expr(self) -> str: + # Runtime expression evaluating to the current device index. Used under + # compile-on-one-rank so the wrapper resolves its device at run time + # (rank-agnostic) instead of baking the compile-time index. Only CUDA/ROCm + # implements this today; raise something actionable rather than a bare + # NotImplementedError from deep inside device-context codegen. + raise RuntimeError( + f"compile-on-one-rank (device-as-parameter) is not supported on " + f"{type(self).__name__}: it has no current_device_idx_expr(), so the " + f"generated wrapper would bake the compile-time device index and not be " + f"rank-portable." + ) + + def current_stream(self) -> str: + raise NotImplementedError + + def stream_handle(self, stream_name: str) -> str: + return f"{stream_name}.native_handle" + + def cpp_device_guard(self) -> str: + raise NotImplementedError + + def cpp_aoti_device_guard(self) -> str: + raise NotImplementedError + + def cpp_stream_guard(self) -> str: + raise NotImplementedError + + def cpp_aoti_stream_guard(self) -> str: + raise NotImplementedError + + def cpp_getStreamFromExternal(self) -> str: + raise NotImplementedError + + def kernel_header(self) -> str: + raise NotImplementedError + + def kernel_driver(self) -> str: + raise NotImplementedError + + def cpp_stream_type(self) -> str: + raise NotImplementedError + + def aoti_get_stream(self) -> str: + raise NotImplementedError + + def cpp_kernel_type(self) -> str: + raise NotImplementedError + + def cpp_device_ptr(self) -> str: + raise NotImplementedError + + def tma_descriptor_helpers(self) -> str: + raise NotImplementedError + + def cpp_scratch( + self, idx: int, workspace: TritonScratchWorkspace, prefix: str | None = None + ) -> tuple[list[str], str] | None: + # optionally return (scratch definition, arg name) + raise NotImplementedError + + +# Thread-safe lazy initialization for device op overrides +device_op_overrides_lock = threading.RLock() +device_op_overrides_dict: dict[str, DeviceOpOverrides] = {} +_device_op_overrides_initialized = False +custom_backend_passes: dict[str, CustomGraphModulePass | None] = {} +custom_backend_codegen_configs: dict[str, ConfigModule | None] = {} + + +# The code generated by Inductor consists of two main parts: kernel code and wrapper code. +# For any new backend looking to integrate with Inductor, customization of these two main +# parts are necessary to generate its specific code. +# +# Kernel code generation is determined by different Scheduling. Consequently, a new +# backend needs to provide a custom Scheduling for its unique kernel code generation. Currently, +# CppScheduling and TritonScheduling serve the C++/OpenMP and Triton backends, respectively. +# +# For the Wrapper, Inductor provides a PythonWrapperCodegen class to generate the Python wrapper code +# that bridges kernels. This allows out-of-tree backends to inherit from PythonWrapperCodegen, +# and override specific member functions to create backend-specific Python wrapper code. +# +# Other classes, such as CppKernel and TritonKernel, used for code generation, typically form part +# of the logic for either Scheduling or PythonWrapperCodegen. So the Scheduling and PythonWrapperCodegen interfaces +# provide flexibility to the backend. A backend can choose to implement these classes from scratch, +# or reuse them by extending and overriding as necessary. And Inductor provides the registration API, +# register_backend_for_device, to equip a new backend at runtime. +# +# Intel has developed a new backend on top of Triton to support Intel GPUs, leveraging these interfaces. +# This backend can be used as a reference: +# https://github.com/intel/intel-extension-for-pytorch/blob/5dcc9d57e5422cf295e1a1ee97896d6b6a554a85/intel_extension_for_pytorch/_inductor/__init__.py#L9 +def register_backend_for_device( + device: str, + device_scheduling: SchedulingConstructor, + device_wrapper_codegen: WrapperConstructor, + device_cpp_wrapper_codegen: WrapperConstructor | None = None, + device_fx_wrapper_codegen: WrapperConstructor | None = None, + device_custom_pass: CustomGraphModulePass | None = None, + device_custom_config: ConfigModule | None = None, +) -> None: + device_codegens[device] = DeviceCodegen( + device_scheduling, + device_wrapper_codegen, + device_cpp_wrapper_codegen, + device_fx_wrapper_codegen, + ) + custom_backend_passes[device] = device_custom_pass + if device_custom_config: + if not ( + isinstance(device_custom_config, ConfigModule) + and device_custom_config is not config + ): + raise AssertionError( + f"{device_custom_config=} cannot be the same as the default inductor config {config=}" + ) + custom_backend_codegen_configs[device] = device_custom_config + + +class BackendFeature(Enum): + FOREACH = auto() + BUCKETIZE = auto() + INPLACE_BUFFERS = auto() + MASKED_SCATTER_WITH_INDEX = auto() + SCAN = auto() + SORT = auto() + TUPLE_REDUCTION = auto() + PREFER_STORE_LOOP_ORDER = auto() + TRITON_TEMPLATES = auto() + REDUCE_TO_SINGLE_ELEMENT = auto() + + +def get_backend_features( + device: torch.device | str | None, +) -> OrderedSet[BackendFeature]: + if device is None: + return OrderedSet() + init_backend_registration() + if isinstance(device, torch.device): + device_type = device.type + else: + if not isinstance(device, str): + raise AssertionError(type(device)) + device_type = device + device = torch.device(device_type) + scheduling_ctor = get_scheduling_for_device(device_type) + if not scheduling_ctor: + raise AssertionError(f"no scheduling registered for device {device_type}") + scheduling = scheduling_ctor(None) + return scheduling.get_backend_features(device) + + +def has_backend_feature( + device: torch.device | str | None, feature: BackendFeature +) -> bool: + """See also V.graph.has_feature""" + if not isinstance(feature, BackendFeature): + raise AssertionError(f"expected BackendFeature, got {type(feature)}") + return feature in get_backend_features(device) + + +def get_scheduling_for_device(device: str) -> SchedulingConstructor | None: + return device_codegens[device].scheduling if device in device_codegens else None + + +def get_wrapper_codegen_for_device( + device: str, cpp_wrapper: bool = False, fx_wrapper: bool = False +) -> WrapperConstructor | None: + if device in device_codegens: + wrapper_codegen_obj: DeviceCodegen = device_codegens[device] + if fx_wrapper: + return wrapper_codegen_obj.fx_wrapper_codegen + elif cpp_wrapper: + cpp_wrapper_codegen = wrapper_codegen_obj.cpp_wrapper_codegen + # allow_stack_allocation is a per-compile config, so the arrayref CPU + # wrapper must follow the current config value rather than whatever it + # happened to be at first registration (see init_backend_registration). + if device == "cpu" and config.aot_inductor.allow_stack_allocation: + from .cpp_wrapper_cpu import CppWrapperCpu + from .cpp_wrapper_cpu_array_ref import CppWrapperCpuArrayRef + + if cpp_wrapper_codegen is CppWrapperCpu: + return CppWrapperCpuArrayRef + return cpp_wrapper_codegen + else: + return wrapper_codegen_obj.wrapper_codegen + return None + + +def get_custom_backend_pass_for_device(device: str) -> CustomGraphModulePass | None: + return custom_backend_passes.get(device) + + +def get_custom_backend_config_for_device(device: str) -> ConfigModule | None: + return custom_backend_codegen_configs.get(device) + + +@functools.cache +def init_backend_registration() -> None: + """ + Register the backend for different devices, including the scheduling + for kernel code generation and the host side wrapper code generation. + """ + from .cpp import CppScheduling + from .cpp_wrapper_cpu import CppWrapperCpu + from .cpp_wrapper_gpu import CppWrapperGpu + from .cpp_wrapper_mps import CppWrapperMps + from .cuda_combined_scheduling import CUDACombinedScheduling + from .halide import HalideScheduling + from .mps import MetalScheduling + from .pallas import PallasScheduling + from .python_wrapper_mtia import PythonWrapperMtia + from .triton import TritonScheduling + from .wrapper import PythonWrapperCodegen + from .wrapper_fxir import WrapperFxCodegen + from .xpu.xpu_combined_scheduling import XPUCombinedScheduling + + if get_scheduling_for_device("cpu") is None: + cpu_backends = { + "cpp": CppScheduling, + "halide": HalideScheduling, + "triton": TritonScheduling, + "pallas": PallasScheduling, + } + register_backend_for_device( + "cpu", + lambda scheduling: cpu_backends[config.cpu_backend](scheduling), + PythonWrapperCodegen, + # allow_stack_allocation selects CppWrapperCpuArrayRef, but that is a + # per-compile config; the choice is made dynamically in + # get_wrapper_codegen_for_device rather than frozen here at the + # process's first registration. + CppWrapperCpu, + WrapperFxCodegen, + ) + + if get_scheduling_for_device("cuda") is None: + # CUDACombinedScheduling combines Triton and CUDA C++ scheduling for CUDA devices via delegation + cuda_backends = { + "triton": CUDACombinedScheduling, + "halide": HalideScheduling, + "pallas": PallasScheduling, + } + register_backend_for_device( + "cuda", + lambda scheduling: cuda_backends[config.cuda_backend](scheduling), + PythonWrapperCodegen, + CppWrapperGpu, + WrapperFxCodegen, + ) + + if get_scheduling_for_device("tpu") is None: + register_backend_for_device( + "tpu", + PallasScheduling, + PythonWrapperCodegen, + # CppWrapperGpu, + # WrapperFxCodegen, + ) + + if get_scheduling_for_device("xpu") is None: + register_backend_for_device( + "xpu", + XPUCombinedScheduling, + PythonWrapperCodegen, + CppWrapperGpu, + WrapperFxCodegen, + ) + + if get_scheduling_for_device("tpu") is None: + tpu_backends = { + "pallas": PallasScheduling, + } + register_backend_for_device( + "tpu", + lambda scheduling: tpu_backends[config.tpu_backend](scheduling), + PythonWrapperCodegen, + ) + + if get_scheduling_for_device("mps") is None: + register_backend_for_device( + "mps", + MetalScheduling, + PythonWrapperCodegen, + CppWrapperMps, + WrapperFxCodegen, + ) + + if get_scheduling_for_device("mtia") is None: + register_backend_for_device( + "mtia", + TritonScheduling, + PythonWrapperMtia, + CppWrapperGpu, + WrapperFxCodegen, + ) + + private_backend = torch._C._get_privateuse1_backend_name() + if ( + private_backend != "privateuseone" + and get_scheduling_for_device(private_backend) is None + ): + from torch.utils.backend_registration import _get_custom_mod_func + + try: + device_scheduling = _get_custom_mod_func("Scheduling") + wrapper_codegen = _get_custom_mod_func("PythonWrapperCodegen") + cpp_wrapper_codegen = _get_custom_mod_func("CppWrapperCodegen") + fx_wrapper_codegen = _get_custom_mod_func("WrapperFxCodegen") + if device_scheduling and wrapper_codegen and cpp_wrapper_codegen: + register_backend_for_device( + private_backend, + device_scheduling, + wrapper_codegen, + cpp_wrapper_codegen, + fx_wrapper_codegen, + ) + except RuntimeError: + pass + + +def index_prevent_reordering( + index: Sequence[sympy.Expr], + index_vars: Sequence[sympy.Expr], + sizes: Sequence[sympy.Expr], +) -> list[sympy.Expr]: + from ..ir import FlexibleLayout + + # added contiguous index prevents reordering + return [*index, sympy_dot(index_vars, FlexibleLayout.contiguous_strides(sizes))] + + +def register_device_op_overrides( + device: str, device_op_overrides: DeviceOpOverrides +) -> None: + with device_op_overrides_lock: + device_op_overrides_dict[device] = device_op_overrides + + +def _initialize_device_op_overrides(): + # Use a flag rather than checking device_op_overrides_dict, since external/test + # code may partially populate it before we are called. + global _device_op_overrides_initialized + if _device_op_overrides_initialized: + return + + with device_op_overrides_lock: + if _device_op_overrides_initialized: + return + + from . import mps_device_op_overrides # noqa: F401 + from .cpu_device_op_overrides import CpuDeviceOpOverrides + from .cuda import device_op_overrides # noqa: F401 + from .mtia import device_op_overrides as mtia_op_overrides # noqa: F401 + from .xpu import device_op_overrides as xpu_op_overrides # noqa: F401 + + # TPU uses Pallas for codegen and only needs no-op overrides + register_device_op_overrides("tpu", CpuDeviceOpOverrides()) + + _device_op_overrides_initialized = True + + +def get_device_op_overrides(device: str) -> DeviceOpOverrides: + if not isinstance(device, str): + raise AssertionError(type(device)) + _initialize_device_op_overrides() + return device_op_overrides_dict[device] + + +DTYPE_TO_COMPUTATION_DTYPE: dict[torch.dtype, torch.dtype] = { + torch.bfloat16: torch.float, + torch.float16: torch.float, + **{ + dtype: dtype + for dtype in [ + torch.bool, + torch.float32, + torch.float64, + torch.int8, + torch.int16, + torch.int32, + torch.int64, + torch.uint8, + torch.uint16, + torch.uint32, + torch.uint64, + ] + }, +} + + +def deduce_output_dtype_by_name( + op_name: str, + *args: Any, + **kwargs: Any, +) -> torch.dtype | None: + """ + Given op name and a list of input dtypes, deduce the output dtype + """ + if op_name in boolean_ops(): + return torch.bool + elif op_name in ( + "to_dtype", + "index_expr", + "value_expr", + ): + return kwargs["dtype"] if "dtype" in kwargs else args[-1] + elif op_name in ( + "rand", + "randn", + ): + return torch.float + elif op_name in ( + "get_index", + "randint64", + "load_seed", + ): + return torch.int64 + elif op_name == "reduction": + return kwargs["dtype"] if "dtype" in kwargs else args[1] + elif op_name == "constant": + return kwargs["dtype"] if "dtype" in kwargs else args[-1] + elif op_name in ( + "load", + "store", + "store_reduction", + ): + buf_name = args[1] + return V.graph.get_dtype(buf_name) # type: ignore[arg-type] + elif op_name == "to_dtype_bitcast": + return kwargs["dtype"] if "dtype" in kwargs else args[-2] + return None + + +def _is_runtime_triton_assert_target() -> bool: + return ( + get_current_backend() == "triton" + and V.graph.get_current_device_or_throw().type != "cpu" + and hasattr(V.kernel, "triton_tensor_ndim") + ) + + +def check_dtype( + buffer: IndentedBuffer, var: CSEVariableType, dtype: torch.dtype +) -> None: + backend = get_current_backend() + if ( + config.test_configs.runtime_triton_dtype_assert + and _is_runtime_triton_assert_target() + ): + buffer.writeline(f"tl.static_assert({var}.dtype == {triton_type(dtype)})") + elif config.test_configs.static_cpp_dtype_assert and backend == "cpp": + from .cpp_utils import CppCSEVariable, DTYPE_TO_CPP + + if not isinstance(var, CppCSEVariable): + raise AssertionError(type(var)) + if dtype == torch.bool: + if var.is_vec: + is_same_dt = f"IsVecMaskType::value" + else: + # operator&(bool, bool) returns int and it can be used as boolean in C++ + is_same_dt = f"std::is_same_v || std::is_same_v" + else: + c_var_type = f"decltype({var})" + if var.is_vec: + c_var_type = f"typename {c_var_type}::value_type" + is_same_dt = f"std::is_same_v<{c_var_type}, {DTYPE_TO_CPP[dtype]}>" + + buffer.writeline(f"static_assert({is_same_dt});") + + +def check_shape( + buffer: IndentedBuffer, var: CSEVariableType, shape: BlockShapeType +) -> None: + if shape is None: + raise AssertionError("expected shape to be not None") + if ( + config.test_configs.runtime_triton_shape_assert + and _is_runtime_triton_assert_target() + ): + shape_str = ( + ", ".join(str(d) for d in shape) if len(shape) != 1 else f"{shape[0]}," + ) + buffer.writeline(f"tl.static_assert({var}.shape == ({shape_str}))") + + +def check_nan(buffer: IndentedBuffer, var: CSEVariableType) -> None: + backend = get_current_backend() + if backend == "triton": + msg = "NaN or Inf found" + buffer.writeline( + f"tl.device_assert(({var} == {var}) & ({var} != float('inf')) & ({var} != float('-inf')), '{msg}')" + ) + + +class DataTypePropagation: + def __init__(self, body: LoopBody) -> None: + self.body = body + self.graphs: dict[Callable[..., Any] | str, Any] = { + "root": body.root_block.graph + } + for k, v in body.subblocks.items(): + self.graphs[k] = v.graph + + def deduce_node_dtype_by_inputs(self, node: torch.fx.Node) -> torch.dtype | None: + inputs = node.all_input_nodes + input_nodes = [ + n for n in inputs if isinstance(n, torch.fx.Node) and n.op != "placeholder" + ] + if len(input_nodes) == 0: + return None + + all_input_nodes_propagated = all( + OptimizationContext.key in n.meta + and n.meta[OptimizationContext.key].dtype is not None + for n in input_nodes + ) + if not all_input_nodes_propagated: + return None + + return functools.reduce( + torch.promote_types, + [n.meta[OptimizationContext.key].dtype for n in input_nodes], + ) + + def deduce_node_dtype_by_subgraph(self, node: torch.fx.Node) -> torch.dtype: + sub_graph = self.graphs[node.target] + dtype = self.propagate_graph(sub_graph) + if not dtype: + raise AssertionError("expected subgraph to propagate a dtype") + return dtype + + def deduce_node_dtype(self, node: torch.fx.Node) -> torch.dtype | None: + if node.op == "placeholder": + return None + + if node.target == "output" and len(node.args) != 1: + # we can infer output node if it only have 1 arg + return None + + if node.target is operator.getitem: + node_arg = node.args[0] + if not isinstance(node_arg, torch.fx.Node): + raise AssertionError(type(node_arg)) + return self.deduce_node_dtype(node_arg) + + if not isinstance(node.target, str): + raise AssertionError(type(node.target)) + + if node.target.startswith("masked_subblock"): + return self.deduce_node_dtype_by_subgraph(node) + + if ( + output_dtype := deduce_output_dtype_by_name( + node.target, + *node.args, + **node.kwargs, + ) + ) is not None: + return output_dtype + + return self.deduce_node_dtype_by_inputs(node) + + def propagate_graph(self, graph: torch.fx.Graph) -> torch.dtype | None: + if not graph.nodes: + raise AssertionError("expected graph to have nodes") + graph_dtype: torch.dtype | None = None + # For masked_subblock, we use output's dtype to represent + # the dtype of this subgraph. For other cases, graph_dtype + # might be None + for node in graph.nodes: + if OptimizationContext.key in node.meta: + opt_ctx = node.meta[OptimizationContext.key] + else: + opt_ctx = OptimizationContext() + + opt_ctx.dtype = self.deduce_node_dtype(node) + node.meta[OptimizationContext.key] = opt_ctx + if node.target == "output": + graph_dtype = opt_ctx.dtype + return graph_dtype + + def propagate(self) -> torch.dtype | None: + return self.propagate_graph(self.graphs["root"]) + + @classmethod + def propagate_loopbody(cls, body: LoopBody) -> torch.dtype | None: + return cls(body).propagate() + + @classmethod + def propagate_scheduler_node(cls, node: SchedulerNode) -> torch.dtype | None: + from ..loop_body import LoopBody + from ..scheduler import SchedulerNode + + if not isinstance(node, SchedulerNode): + raise AssertionError(type(node)) + if not isinstance(node._body, LoopBody): + raise AssertionError(type(node._body)) + return DataTypePropagation.propagate_loopbody(node._body) + + +class PythonPrinter(_PythonPrinter): + def doprint( + self, expr: sympy.Expr, *, simplify: bool = True, p: bool = True + ) -> str: + # TODO: why are people passing strings to the printer here :think: + if simplify and isinstance(expr, sympy.Expr) and hasattr(V.graph, "sizevars"): + expr = V.graph.sizevars.simplify(expr) + return super().doprint(expr) + + def parenthesize(self, item: sympy.Expr, level: int, strict: bool = False) -> str: + if isinstance(item, sympy.Mod): + # use parenthesis to enforce precedence. + # in sympy 1.13.3, -2*Mod(x,y) becomes -2*x%y, which is wrong. + # pyrefly: ignore [missing-attribute] + return f"({self._print(item)})" + else: + return super().parenthesize(item, level, strict) + + +class OpDecompositions: + """ + Decomposes inductor ops + """ + + @staticmethod + def identity(value: OpVarT) -> OpVarT: + # used to trigger cse + return value + + @staticmethod + def reciprocal(x: OpVarT) -> OpVarT: + # Use float32 constant so that div_rn can be applied when + # eager_numerics.division_rounding is enabled + return ops.truediv(ops.constant(1.0, torch.float32), x) + + @staticmethod + def square(x: OpVarT) -> OpVarT: + return ops.mul(x, x) + + @staticmethod + def erfc(x: OpVarT) -> OpVarT: + return ops.sub(ops.constant(1, torch.float32), ops.erf(x)) + + @staticmethod + def erfcx(x: OpVarT) -> OpVarT: + return ops.mul(ops.exp(ops.square(x)), ops.erfc(x)) + + @staticmethod + def expm1(x: OpVarT) -> OpVarT: + return ops.sub(ops.exp(x), ops.constant(1, torch.float32)) + + @staticmethod + def log10(x: OpVarT) -> OpVarT: + return ops.mul(ops.log(x), ops.constant(1 / math.log(10), torch.float32)) + + @staticmethod + def log2(x: OpVarT) -> OpVarT: + return ops.mul(ops.log(x), ops.constant(1 / math.log(2), torch.float32)) + + @staticmethod + def exp2(x: OpVarT) -> OpVarT: + return ops.exp(ops.mul(x, ops.constant(math.log(2), torch.float32))) + + @staticmethod + def log1p(x: OpVarT) -> OpVarT: + return ops.log(ops.add(x, ops.constant(1, torch.int32))) + + @staticmethod + def sigmoid(x: OpVarT) -> OpVarT: + one = ops.constant(1, torch.int32) + return ops.truediv(one, ops.add(one, ops.exp(ops.neg(x)))) + + @staticmethod + def relu(x: OpVarT) -> OpVarT: + return ops.maximum(x, ops.constant(0, torch.int32)) + + @staticmethod + def fma(x: OpVarT, y: OpVarT, z: OpVarT) -> OpVarT: + # for backends that don't override this (halide) + return ops.add(ops.mul(x, y), z) + + @staticmethod + def mul_rn(x: OpVarT, y: OpVarT) -> OpVarT: + # for backends that don't override this, just use regular mul + return ops.mul(x, y) + + @staticmethod + def div_rn(x: OpVarT, y: OpVarT) -> OpVarT: + # for backends that don't override this, just use regular div + return ops.truediv(x, y) + + @staticmethod + def floor_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.floor(a), dtype) + + @staticmethod + def ceil_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.ceil(a), dtype) + + @staticmethod + def trunc_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.trunc(a), dtype) + + @staticmethod + def remainder(a: OpVarT, b: OpVarT) -> OpVarT: + r = ops.mod(a, b) + cond = ops.and_( + ops.ne(r, ops.constant(0, torch.int32)), + ops.ne(ops.signbit(r), ops.signbit(b)), + ) + return ops.where(cond, ops.add(r, b), r) + + @staticmethod + def round_to_int(a: OpVarT, dtype: torch.dtype) -> OpVarT: + return ops.to_dtype(ops.round(a), dtype) + + +_RE_PAREN_NOT_NEEDED = re.compile(r"[a-z0-9_.]+|\([^)]*\)|", flags=re.IGNORECASE) + + +def _all_in_parens(string: str) -> bool: + if string[0] != "(" or len(string) < 2: + return False + count = 1 + for i, char in enumerate(string[1:]): + if char == "(": + count += 1 + elif char == ")": + count -= 1 + if count == 0 and i != len(string) - 2: + return False + if count != 0: + raise AssertionError(f"expected balanced count == 0, got {count}") + return True + + +# pyrefly: ignore [inconsistent-inheritance] +class OpOverrides(BasicMathOpsMixin, OpDecompositions, OpsHandler[Any]): + @staticmethod + def paren(string: OpVarT) -> OpVarT: + if ( + isinstance(string, CSEVariable) + or _RE_PAREN_NOT_NEEDED.fullmatch(string) + or _all_in_parens(string) + ): + # don't put extra parens for strings that are already wrapped in parens + + return string + return f"({string})" + + @staticmethod + def constant(value: bool | float | int, dtype: torch.dtype) -> OpVarT: + return repr(value) + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_not(x: OpVarT) -> OpVarT: + return f"~{OpOverrides.paren(x)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_not(a: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(a)} == 0" + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_and(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} & {OpOverrides.paren(y)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_or(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} | {OpOverrides.paren(y)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_xor(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} ^ {OpOverrides.paren(y)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_left_shift(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} << {OpOverrides.paren(y)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_right_shift(x: OpVarT, y: OpVarT) -> OpVarT: + return f"{OpOverrides.paren(x)} >> {OpOverrides.paren(y)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def int_truediv(a: OpVarT, b: OpVarT) -> OpVarT: + # TODO: this is wrong + # TODO: an easy bandaid is to generate runtime asserts that it's + # <= 2**53, which is when this equation is correct + return ops.truediv(a, b) + + @staticmethod + def load_seed(name: str, offset: OpVarT) -> OpVarT: + return ops.load(name, sympy.Integer(offset)) + + def indirect_indexing( + self, + var: OpVarT, + size: sympy.Expr | int, + check: bool = True, + wrap_neg: bool = True, + ) -> sympy.Symbol: + return sympy_index_symbol(str(var)) + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + raise NotImplementedError( + f"{type(self).__name__}: check_bounds should be handled by CSEProxy" + ) + + def load(self, name: str, index: sympy.Expr) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: load should be handled by CSEProxy" + ) + + def store( + self, name: str, index: sympy.Expr, value: OpVarT, mode: StoreMode = None + ) -> None: + raise NotImplementedError( + f"{type(self).__name__}: store should be handled by CSEProxy" + ) + + def device_assert_async(self, cond: CSEVariable, msg: str) -> None: + raise NotImplementedError( + f"{type(self).__name__}: device_assert_async should be handled by CSEProxy" + ) + + def store_reduction(self, name: str, index: sympy.Expr, value: OpVarT) -> None: + raise NotImplementedError( + f"{type(self).__name__}: store_reduction should be handled by CSEProxy" + ) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: OpVarT | tuple[OpVarT, ...], + ) -> OpVarT | tuple[OpVarT, ...]: + raise NotImplementedError( + f"{type(self).__name__}: reduction should be handled by CSEProxy" + ) + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[OpVarT, ...], tuple[OpVarT, ...]], + tuple[OpVarT, ...], + ], + values: tuple[OpVarT, ...], + ) -> tuple[OpVarT, ...]: + raise NotImplementedError( + f"{type(self).__name__}: scan should be handled by CSEProxy" + ) + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[OpVarT, ...], + stable: bool, + descending: bool, + ) -> tuple[OpVarT, ...]: + raise NotImplementedError( + f"{type(self).__name__}: sort should be handled by CSEProxy" + ) + + def bucketize( + self, + values: OpVarT, + boundaries: tuple[str, sympy.Expr, sympy.Expr, sympy.Expr], + boundary_indices: OpVarT, + indexing_dtype: torch.dtype, + right: bool, + sorter: tuple[str, sympy.Expr] | None = None, + sorter_indices: OpVarT | None = None, + ) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: bucketize should be handled by CSEProxy" + ) + + def halide_clamp(self, value: OpVarT, size: sympy.Expr, check: bool) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: halide_clamp only implemented for Halide backend" + ) + + def dot(self, x: OpVarT, y: OpVarT) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: dot only implemented for Triton backend" + ) + + def inline_asm_elementwise( + self, + *inputs: OpVarT, + 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, + ) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__}: inline_asm_elementwise only implemented for Triton backend" + ) + + def output(self, *args: OpVarT) -> None: + raise AssertionError( + f"{type(self).__name__}: ops.output should not appear at codegen time" + ) + + def placeholder(self, index: int) -> OpVarT: + raise AssertionError( + f"{type(self).__name__}: ops.placeholder should not appear at codegen time" + ) + + @staticmethod + def _unimplemented(name: str) -> Callable[..., OpVarT]: + def unimplemented(self: OpOverrides, *args: Any, **kwargs: Any) -> OpVarT: + raise NotImplementedError( + f"{type(self).__name__} does not implement ops.{name}" + ) + + unimplemented.__name__ = name + unimplemented.is_unimplemented = True # type: ignore[attr-defined] + return unimplemented + + @classmethod + def _is_unimplemented(cls, name: str) -> bool: + fn = getattr(cls, name, None) + default_fn = getattr(OpsHandler, name, None) + return not fn or fn == default_fn or getattr(fn, "is_unimplemented", False) + + @classmethod + def _initialize_pointwise_overrides(cls, target: str) -> None: + if target not in ("triton", "cpp", "cppvec", "halide", "mps"): + raise AssertionError(target) + + for funcname, data in pointwise_overrides_data.items(): + impl = getattr(data, target) + if impl is None: + if cls._is_unimplemented(funcname): + setattr(cls, funcname, cls._unimplemented(funcname)) + else: + if funcname in cls.__dict__: + raise AssertionError( + f"multiple definitions of {funcname} on {cls.__name__}" + ) + impl.__name__ = funcname + setattr(cls, funcname, staticmethod(impl)) + + +@dataclasses.dataclass +class OverridesData: + name: str + cpp: Callable[..., str] + # None when not impl in libdevice/triton + triton: Callable[..., str] | None = None + # None when not impl in aten/.../vec + cppvec: Callable[..., str] | None = None + type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND = ( + ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + halide: Callable[..., str] | None = None + mps: Callable[..., str] | None = None + + +def _triton_bessel(order: int, kind: str, x: str) -> str: + # PyTorch eager returns NaN for +/-inf, while libdevice returns + # the mathematical limit. x - x yields NaN in x's dtype + # (avoids fp32 literal promotion under tl.where for float64 inputs) + return ( + f"tl.where(tl_math.abs({x}) == float('inf'), " + f"{x} - {x}, " + f"libdevice.{kind}{order}({x}))" + ) + + +def _triton_cyl_bessel_i(order: int, x: str) -> str: + # PyTorch's Cephes-derived kernels return NaN for infinities; libdevice + # returns signed infinities, so synthesize a same-dtype NaN with x - x. + return ( + f"tl.where(tl.abs({x}) == float('inf'), " + f"{x} - {x}, " + f"libdevice.cyl_bessel_i{order}({x}))" + ) + + +# NB: if you add a new special function, don't forget to update +# torch._inductor.ops_handler too +pointwise_overrides_data: dict[str, OverridesData] = dict( + airy_ai=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"airy_ai_forward({x})", + name="special_airy_ai", + ), + bessel_j0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_j0_forward({x})", + triton=lambda x: _triton_bessel(0, "j", x), + name="special_bessel_j0", + ), + bessel_j1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_j1_forward({x})", + triton=lambda x: _triton_bessel(1, "j", x), + name="special_bessel_j1", + ), + bessel_y0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_y0_forward({x})", + triton=lambda x: _triton_bessel(0, "y", x), + name="special_bessel_y0", + ), + bessel_y1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"bessel_y1_forward({x})", + triton=lambda x: _triton_bessel(1, "y", x), + name="special_bessel_y1", + ), + digamma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_digamma({x})", + cppvec=lambda x: f"{x}.digamma()", + name="digamma", + ), + # no cpp nor triton implementation for entr, it is defined as decomposition + # erf, erfc + erfcx=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_erfcx({x})", + triton=lambda x: f"libdevice.erfcx({x})", + name="special_erfcx", + ), + fma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y, z: f"std::fma({x}, {y}, {z})", + cppvec=lambda x, y, z: f"fmadd({x}, {y}, {z})", + # NOTE: We use tl.fma instead of libdevice.fma because libdevice.fma + # has Flush-To-Zero (FTZ) behavior for subnormal values, which causes + # numerical differences compared to eager CUDA execution. tl.fma + # preserves subnormals and matches eager's FMA precision. + triton=lambda x, y, z: f"tl.fma({x}, {y}, {z})", + name="fma", + ), + # mul_rn: Multiplication with round-to-nearest. This prevents Triton's + # compiler from fusing the multiplication with subsequent operations, + # which is needed to match eager's rounding behavior in operations like + # addcmul where the product must be rounded before use. + # Note: libdevice.mul_rn is not supported on ROCm, so we fall back to + # regular multiplication there. + mul_rn=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + cpp=lambda x, y: f"({x}) * ({y})", # C++ doesn't need special handling + triton=lambda x, y: f"({x}) * ({y})" + if torch.version.hip + else f"libdevice.mul_rn({x}, {y})", + name="mul_rn", + ), + # erfinv, exp2, expit, gammaln + igamma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igamma({x}, {y})", + name="igamma", + ), + igammac=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igammac({x}, {y})", + name="igammac", + ), + gammainc=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igamma({x}, {y})", + name="special_gammainc", + ), + gammaincc=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"calc_igammac({x}, {y})", + name="special_gammaincc", + ), + i0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i0({x})", + triton=lambda x: _triton_cyl_bessel_i(0, x), + cppvec=lambda x: f"{x}.i0()", + name="i0", + ), + i0e=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i0e({x})", + cppvec=lambda x: f"{x}.i0e()", + name="special_i0e", + ), + i1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i1({x})", + triton=lambda x: _triton_cyl_bessel_i(1, x), + name="special_i1", + ), + i1e=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_i1e({x})", + name="special_i1e", + ), + log_ndtr=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_log_ndtr({x})", + name="special_log_ndtr", + ), + # logit + modified_bessel_i0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_i0_forward({x})", + triton=lambda x: _triton_cyl_bessel_i(0, x), + name="special_modified_bessel_i0", + ), + modified_bessel_i1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_i1_forward({x})", + triton=lambda x: _triton_cyl_bessel_i(1, x), + name="special_modified_bessel_i1", + ), + modified_bessel_k0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_k0_forward({x})", + name="special_modified_bessel_k0", + ), + modified_bessel_k1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"modified_bessel_k1_forward({x})", + name="special_modified_bessel_k1", + ), + # multigamma + ndtr=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_ndtr({x})", + name="special_ndtr", + ), + ndtri=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"calc_ndtri({x})", + name="special_ndtri", + ), + polygamma=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, + y: f"{x} == 0 ? calc_digamma({y}) : ({x} == 1 ? trigamma({y}) : calc_polygamma({y}, {x}))", + name="polygamma", + ), + # psi - alias to digamma + # round + scaled_modified_bessel_k0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"scaled_modified_bessel_k0_forward({x})", + name="special_scaled_modified_bessel_k0", + ), + scaled_modified_bessel_k1=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"scaled_modified_bessel_k1_forward({x})", + name="special_scaled_modified_bessel_k1", + ), + # sinc + spherical_bessel_j0=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x: f"spherical_bessel_j0_forward({x})", + name="special_spherical_bessel_j0", + ), + zeta=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"zeta({x}, {y})", + name="special_zeta", + ), + chebyshev_polynomial_t=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_t_forward({x}, {y})", + name="special_chebyshev_polynomial_t", + ), + chebyshev_polynomial_u=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_u_forward({x}, {y})", + name="special_chebyshev_polynomial_u", + ), + chebyshev_polynomial_v=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_v_forward({x}, {y})", + name="special_chebyshev_polynomial_v", + ), + chebyshev_polynomial_w=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"chebyshev_polynomial_w_forward({x}, {y})", + name="special_chebyshev_polynomial_w", + ), + legendre_polynomial_p=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"legendre_polynomial_p_forward({x}, {y})", + name="special_legendre_polynomial_p", + ), + shifted_chebyshev_polynomial_t=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_t_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_t", + ), + shifted_chebyshev_polynomial_u=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_u_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_u", + ), + shifted_chebyshev_polynomial_v=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_v_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_v", + ), + shifted_chebyshev_polynomial_w=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"shifted_chebyshev_polynomial_w_forward({x}, {y})", + name="special_shifted_chebyshev_polynomial_w", + ), + hermite_polynomial_h=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"hermite_polynomial_h_forward({x}, {y})", + name="special_hermite_polynomial_h", + ), + hermite_polynomial_he=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"hermite_polynomial_he_forward({x}, {y})", + name="special_hermite_polynomial_he", + ), + laguerre_polynomial_l=OverridesData( + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + cpp=lambda x, y: f"laguerre_polynomial_l_forward({x}, {y})", + name="special_laguerre_polynomial_l", + ), +) + + +def is_buffer_removed(name: str) -> bool: + return any( + name in x + for x in ( + V.graph.removed_buffers, + V.kernel.removed_buffers, + V.graph.inplaced_to_remove, + V.kernel.inplaced_to_remove, + ) + ) + + +class DeferredLine(DeferredLineBase): + """A line that can be 'unwritten' by adding name to V.graph.removed_buffers""" + + def __init__(self, name: str, line: str): + super().__init__(line) + self.name = name + if isinstance(line, DeferredLineBase): + raise AssertionError("line must not be a DeferredLineBase") + + def __call__(self) -> str | None: + if not is_buffer_removed(self.name): + return self.line + return None + + def _new_line(self, line: str) -> DeferredLine: + return DeferredLine(self.name, line) + + +class BracesBuffer(IndentedBuffer): + def indent(self, offset: int = 1) -> contextlib.AbstractContextManager[None]: + @contextlib.contextmanager + def ctx() -> Iterator[None]: + for _ in range(offset): + self.writeline("{") + self._indent += 1 + for _ in range(-offset): + self._indent -= 1 + self.writeline("}") + yield + for _ in range(-offset): + self.writeline("{") + self._indent += 1 + for _ in range(offset): + self._indent -= 1 + self.writeline("}") + + return ctx() + + +class InplacedBuffer(NamedTuple): + inner_name: str + other_names: list[str] + + +@dataclasses.dataclass +class ArgName: + name: str + # is_constexpr=True is used to attach a " : tl.constexpr" into the argument list + is_constexpr: bool = False + + def full_name(self) -> str: + return f"{self.name}{' : tl.constexpr' if self.is_constexpr else ''}" + + +class RemovedArg: + def __str__(self) -> str: + return "REMOVED" + + +REMOVED = RemovedArg() + + +class KernelArgs: + @staticmethod + def _lookup( + prefix: str, + odict: dict[_T, str | RemovedArg] | dict[_T, str], + name: _T, + ) -> str: + result: str | RemovedArg = odict.get(name, REMOVED) + if isinstance(result, RemovedArg): + odict[name] = new_result = f"{prefix}{len(odict)}" + return new_result + return result + + def __init__(self) -> None: + self.input_buffers: dict[str, str] = {} + self.output_buffers: dict[str, str | RemovedArg] = {} + self.inplace_buffers: dict[str, InplacedBuffer | RemovedArg] = {} + self.sizevars: dict[sympy.Expr, str] = {} + self.workspace_args: list[WorkspaceArg] = [] + + def __repr__(self) -> str: + return "KernelArgs({})".format( + ", ".join( + map( + repr, + [ + self.input_buffers, + self.output_buffers, + self.inplace_buffers, + self.sizevars, + ], + ) + ) + ) + + @staticmethod + def _buffer_is_marked_removed(name: Any) -> bool: + # this function is needed by MTIA + return isinstance(name, RemovedArg) + + def input(self, name: str) -> str: + if V.graph.scheduler: + name = V.graph.scheduler.mutation_real_name.get(name, name) + if name in V.graph.removed_buffers: + raise AssertionError(name) + if name in self.output_buffers: + return cast(str, self.output_buffers[name]) + if name in self.inplace_buffers: + return cast(InplacedBuffer, self.inplace_buffers[name]).inner_name + if name.startswith("seed"): + return self._lookup("seed", self.input_buffers, name) + return self._lookup("in_ptr", self.input_buffers, name) + + def output(self, name: str) -> str: + if V.graph.scheduler: + name = V.graph.scheduler.mutation_real_name.get(name, name) + if name in V.graph.removed_buffers: + raise AssertionError(name) + if name in self.inplace_buffers: + return cast(InplacedBuffer, self.inplace_buffers[name]).inner_name + return self._lookup("out_ptr", self.output_buffers, name) + + def make_inplace(self, input_name: str, output_name: str) -> None: + if input_name in V.graph.unaligned_buffers: + V.graph.unaligned_buffers.add(output_name) + if output_name in self.inplace_buffers: + raise AssertionError(output_name) + if input_name in self.inplace_buffers: + buf = self.inplace_buffers[input_name] + if isinstance(buf, RemovedArg): + raise AssertionError("buf must not be a RemovedArg") + buf.other_names.append(output_name) + self.inplace_buffers[output_name] = buf + else: + alive_buffers = [ + val + for val in self.inplace_buffers.values() + if not isinstance(val, RemovedArg) + ] + removed_buffers = [ + val + for val in self.inplace_buffers.values() + if isinstance(val, RemovedArg) + ] + inplace_buffer_idx = len(unique(alive_buffers)) + len(removed_buffers) + buf = InplacedBuffer( + f"in_out_ptr{inplace_buffer_idx}", + [input_name, output_name], + ) + self.inplace_buffers[input_name] = buf + self.inplace_buffers[output_name] = buf + + def workspace( + self, nelem: sympy.Expr, zero_fill: bool, dtype: torch.dtype = torch.uint8 + ) -> tuple[str, str, int]: + """ + Allocate or extend a workspace buffer of nelem elements. + + This function manages the allocation of a workspace buffer. It either creates + a new WorkspaceArg or extends an existing one. + + Note: + - Calling this function will in-place mutate the args by adding or updating + a WorkspaceArg. + - The codegen for generating the Python argdefs and call_defs will check + this field and allocate the buffer accordingly. + - A new argument "ws_ptr" will be present in the generated code. + + Args: + nelem (sympy.Expr): The number of elements to allocate. + zero_fill (bool): Whether to initialize the buffer to zero. + dtype (torch.dtype): the dtype of the workspace tensor + + Returns: + Tuple[str, str, int]: A tuple containing: + - "ws_ptr": A string identifier for the workspace pointer. + - "workspace_{i}": a graph level unique identifier for + the workspace tensor. + - offset: An integer representing the item offset in the workspace. + """ + arg = WorkspaceArg( + count=nelem, + zero_mode=WorkspaceZeroMode.from_bool(zero_fill), + device=V.graph.get_current_device_or_throw(), + outer_name=WorkspaceArg.unique_name(), + dtype=dtype, + ) + for i, existing_arg in enumerate(self.workspace_args): + if WorkspaceArg.can_join(existing_arg, arg): + offset = existing_arg.count + self.workspace_args[i] = WorkspaceArg.join(existing_arg, arg) + return existing_arg.inner_name, existing_arg.outer_name, offset + if not ( + existing_arg.inner_name != arg.inner_name + and existing_arg.outer_name != arg.outer_name + ): + raise AssertionError(existing_arg) + self.workspace_args.append(arg) + return arg.inner_name, arg.outer_name, 0 + + def semaphores(self, min_size: sympy.Expr) -> str: + """ + Lazily allocate a graph-wide semaphores buffer with at least min_size. This is a single buffer shared by + all kernels and zero initialized once at graph start. Each kernel must leave the buffer zeroed on exit. + + Warning: multiple calls to this function will return the same buffer. + + Args: + min_size: the number of int32 semaphores required + + Returns: + name of the semaphores buffer + """ + from torch.fx.experimental.proxy_tensor import _coor_enabled + + current_device = V.graph.get_current_device_or_throw() + # This name is emitted into the wrapper, so under compile-on-one-rank it cannot + # carry the rank's device index (the graph is single-device there, so the type + # alone still distinguishes buffers). + suffix = "" if _coor_enabled() else f"_{current_device.index}" + arg = WorkspaceArg( + count=min_size, + zero_mode=WorkspaceZeroMode.ZERO_PER_GRAPH, + dtype=torch.uint32, + inner_name="sem_ptr", + outer_name=f"semaphores_{current_device.type}{suffix}", + device=current_device, + ) + for existing_arg in self.workspace_args: + if existing_arg.inner_name == arg.inner_name: + if arg != existing_arg: + raise AssertionError((arg, existing_arg)) + self.workspace_args.append(arg) + return arg.inner_name + + def seed_offset(self, name: str, value: int) -> str: + if not isinstance(value, int): + raise AssertionError((type(value), value)) + # here we are lifting a constant integer into an arg to the kernel to try to get additional cache hits + value = sympy.Integer(value) + if value in self.sizevars: + return self.sizevars[value] + if name in self.sizevars.values(): + name = ( + f"{name}{sum(1 for v in self.sizevars.values() if v.startswith(name))}" + ) + self.sizevars[value] = name + return name + + def size(self, name: sympy.Symbol) -> str: + if not isinstance(name, sympy.Symbol): + raise AssertionError((type(name), name)) + if name.name == "seed": + self.sizevars[name] = "seed" # don't manage the name of seeds + return "seed" + return self._lookup("ks", self.sizevars, name) + + def call_names(self) -> Iterator[str]: + return chain( + self.input_buffers.keys(), self.output_buffers.keys(), self.sizevars.keys() + ) + + def arg_name(self, name: str) -> str | None: + """ + Returns inner name of a given outer name. + """ + inplaced = self.inplace_buffers.get(name, None) + if inplaced is not None and not isinstance(inplaced, RemovedArg): + return inplaced.inner_name + output_name = self.output_buffers.get(name, None) + if output_name is not None and not isinstance(output_name, RemovedArg): + return output_name + return self.input_buffers.get(name, None) + + def wrap_ptr_arg(self, buf: str, dtype: torch.dtype) -> str: + return buf + + def wrap_size_arg(self, size: SymbolLike) -> str: + return str(size) + + def cpp_argdefs( + self, dtype_to_cpp_type: dict[torch.dtype, str] | None = None + ) -> tuple[list[str], list[str], list[str]]: + from .cpp_utils import INDEX_TYPE + + if dtype_to_cpp_type is None: + from .cpp_utils import DTYPE_TO_CPP + + dtype_to_cpp_type = DTYPE_TO_CPP + + call_args = [] + arg_defs = [] + arg_types = [] + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + outer = inplaced.other_names[-1] + inner = inplaced.inner_name + dtype = V.graph.get_dtype(outer) + cpp_dtype = dtype_to_cpp_type[dtype] + arg_defs.append(f"{cpp_dtype}* {inner}") + call_args.append(self.wrap_ptr_arg(outer, dtype)) + arg_types.append(f"{cpp_dtype}*") + for outer, inner in self.input_buffers.items(): + if outer in self.inplace_buffers: + continue + dtype = V.graph.get_dtype(outer) + cpp_dtype = dtype_to_cpp_type[dtype] + arg_defs.append(f"const {cpp_dtype}* {inner}") + call_args.append(self.wrap_ptr_arg(outer, dtype)) + arg_types.append(f"const {cpp_dtype}*") + for outer, maybe_inner in self.output_buffers.items(): + if outer in self.inplace_buffers or isinstance(maybe_inner, RemovedArg): + continue + dtype = V.graph.get_dtype(outer) + cpp_dtype = dtype_to_cpp_type[dtype] + arg_defs.append(f"{cpp_dtype}* {maybe_inner}") + call_args.append(self.wrap_ptr_arg(outer, dtype)) + arg_types.append(f"{cpp_dtype}*") + for outer, inner in self.sizevars.items(): + if isinstance(outer, sympy.Symbol) and symbol_is_type( + outer, (SymT.UNBACKED_FLOAT) + ): + arg_defs.append(f"const float {inner}") + arg_types.append("const float") + else: + arg_defs.append(f"const {INDEX_TYPE} {inner}") + arg_types.append(f"const {INDEX_TYPE}") + call_args.append(self.wrap_size_arg(outer)) + if V.graph.wrapper_code: + V.graph.wrapper_code.ensure_size_computed(outer) + if self.workspace_args: + raise AssertionError("Workspace not supported on CPU ") + return arg_defs, call_args, arg_types + + def python_argdefs( + self, + ) -> tuple[list[ArgName], list[str], list[KernelArgType], list[Any]]: + arg_defs: list[ArgName] = [] + call_args: list[str] = [] + arg_types: list[Any] = [] + precompile_args: list[KernelArgType] = [] + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + arg_defs.append(ArgName(inplaced.inner_name)) + call_args.append(inplaced.other_names[-1]) + arg_types.append(V.graph.get_dtype(inplaced.other_names[-1])) + precompile_args.append( + TensorArg( + name=inplaced.inner_name, + buffer=inplaced.other_names[-1], + dtype=V.graph.get_dtype(inplaced.other_names[-1]), + ) + ) + for outer, inner in chain( + self.input_buffers.items(), + # pyrefly: ignore [bad-argument-type] + self.output_buffers.items(), + ): + if outer in self.inplace_buffers or isinstance(inner, RemovedArg): + continue + arg_defs.append(ArgName(inner)) + call_args.append(outer) + arg_types.append(V.graph.get_dtype(outer)) + precompile_args.append( + TensorArg( + name=inner, + buffer=outer, + dtype=V.graph.get_dtype(outer), + ) + ) + for outer, inner in self.sizevars.items(): + arg_defs.append(ArgName(inner)) + call_args.append(outer) + arg_types.append(type(outer)) + precompile_args.append(SizeArg(inner, outer)) + if V.graph.wrapper_code: + V.graph.wrapper_code.ensure_size_computed(outer) + for arg in self.workspace_args: + arg_defs.append(ArgName(arg.inner_name)) + call_args.append(arg.outer_name) + precompile_args.append(arg) + arg_types.append(arg.dtype) + return arg_defs, call_args, precompile_args, arg_types + + def aliases(self) -> Iterator[tuple[str, str]]: + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + for other in inplaced.other_names: + if ( + other in V.graph.inplaced_to_remove + or other in V.kernel.inplaced_to_remove + ): + continue + if other in self.input_buffers: + yield self.input_buffers[other], inplaced.inner_name + if other in self.output_buffers: + yield cast(str, self.output_buffers[other]), inplaced.inner_name + + def is_removed(self, name: str) -> bool: + return isinstance( + self.output_buffers.get(name, REMOVED), RemovedArg + ) and isinstance(self.inplace_buffers.get(name, REMOVED), RemovedArg) + + # Includes inplace buffers, excludes removed buffers. Essentially, + # after you do a call into this kernel, which buffers actually contain + # updated data? Modeled off of python_argdefs. + def live_output_buffers(self) -> OrderedSet[str]: + live_outs: OrderedSet[str] = OrderedSet() + for inplaced in unique(self.inplace_buffers.values()): + if isinstance(inplaced, RemovedArg): + continue + live_outs.add(inplaced.other_names[-1]) + for outer, inner in self.output_buffers.items(): + if outer in self.inplace_buffers or isinstance(inner, RemovedArg): + continue + live_outs.add(outer) + return live_outs + + +class CSEVariable: + """A CSEVariable is just a name for an expression but it is useful to be able to annotate them on a backend dependent basis. + To do so, the backends can simply overload `Kernel.create_cse_var` + The "CSEVariable.update_on_args" method gives you a hook for annotations + See example of TritonCSEVariable in triton.py + """ + + def __init__( + self, + name: str, + bounds: ValueRanges[Any], + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ): + super().__init__() + if not isinstance(bounds, ValueRanges): + raise AssertionError(type(bounds)) + self.name = name + self.bounds = bounds + self.use_count = 1 # track how many times this expression is used + self.dtype = dtype + self.shape = shape + + def __str__(self) -> str: + return self.name + + def __hash__(self) -> int: + return hash(self.name) + + def __eq__(self, other: object) -> bool: + return isinstance(other, CSEVariable) and other.name == self.name + + def update_on_args(self, name: str, args: Any, kwargs: Any) -> None: + pass + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.name!r})" + + +AugmentedKeyT = TypeVar("AugmentedKeyT", default=str) +CSEVariableType = TypeVar("CSEVariableType", bound=CSEVariable, default=CSEVariable) + +if TYPE_CHECKING: + ReductionCacheKey = tuple[ + torch.dtype, + ReductionType, + CSEVariable | tuple[CSEVariable, ...], + ] + + +class CSE(Generic[CSEVariableType, AugmentedKeyT]): + """Common subexpression elimination""" + + def __init__( + self, + prefix: str = "", + suffix: str = "", + name_prefix: str = "tmp", + iter_buffers: itertools.count[int] | None = None, + store_cache: MutableMapping[str, CSEVariableType] | None = None, + reduction_cache: MutableMapping[ReductionCacheKey, CSEVariableType] + | None = None, + varname_map: dict[str, CSEVariableType] | None = None, + ): + self.prefix = prefix + self.suffix = suffix + self._cache: MutableMapping[AugmentedKeyT, CSEVariableType] = {} + self.name_prefix = name_prefix + self.store_cache: MutableMapping[str, CSEVariableType] = store_cache or {} + self.reduction_cache: MutableMapping[ReductionCacheKey, CSEVariableType] = ( + reduction_cache or {} + ) + self.iter_buffer_ids: itertools.count[int] = iter_buffers or itertools.count() + self.invalidated_stores: OrderedSet[str] = OrderedSet() + self.varname_map: dict[str, CSEVariableType] = varname_map or {} + + def invalidate(self, keep_vars: OrderedSet[CSEVariable]) -> None: + for name, tmp in [*self.store_cache.items()]: + if tmp not in keep_vars: + del self.store_cache[name] + self.invalidated_stores.add(name) + if keep_vars: + self._cache = {k: v for k, v in self._cache.items() if v in keep_vars} + else: + self._cache = {} + + def clone(self) -> Self: + return type(self)( + prefix=self.prefix, + suffix=self.suffix, + name_prefix=self.name_prefix, + iter_buffers=self.iter_buffer_ids, + store_cache=self.store_cache, + varname_map=self.varname_map, + reduction_cache=self.reduction_cache, + ) + + def scoped_copy(self) -> Self: + """Return a copy of using ScopedDict so changes to *_cache aren't visible in self""" + new_cse = self.clone() + new_cse._cache = ScopedDict(self._cache) + new_cse.reduction_cache = ScopedDict(self.reduction_cache) + new_cse.store_cache = ScopedDict(self.store_cache) + return new_cse + + def augment_key(self, cache_key: str) -> AugmentedKeyT: + "Override this method to augment cache key with backend specifics" + return cast(AugmentedKeyT, cache_key) + + def put(self, cache_key: str, val: CSEVariableType) -> None: + self._cache[self.augment_key(cache_key)] = val + + def contains(self, cache_key: str) -> bool: + return self.augment_key(cache_key) in self._cache + + def try_get(self, cache_key: str) -> CSEVariableType | None: + return self._cache.get(self.augment_key(cache_key), None) + + def get(self, cache_key: str) -> CSEVariableType: + return self._cache[self.augment_key(cache_key)] + + def generate( + self, + buffer: IndentedBuffer, + expr: str | CSEVariable | OpsValue | IndentedBuffer | DeferredLineBase, + *, + bounds: ValueRanges[Any] = ValueRanges.unknown(), + write: bool = True, + assignment: bool = True, + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ) -> CSEVariableType: + if isinstance(expr, OpsValue): + expr = expr.value + + if not (write or assignment): + raise AssertionError("expected write or assignment to be set") + if isinstance(expr, CSEVariable): + # If the expressions were always created with all the information, we could + # assert expr.bounds == bounds, but sometimes the expression is created + # with the loose ValueRanges.unknown(), so we need to tighten the bounds + expr.bounds = expr.bounds.tighten(bounds) + expr.use_count += 1 + return cast(CSEVariableType, expr) + elif isinstance(expr, IndentedBuffer): + cache_key = expr.getvalue() + elif isinstance(expr, DeferredLineBase): + cache_key = expr.line + else: + if not isinstance(expr, str): + raise AssertionError(f"expected str, got {type(expr)}") + cache_key = expr + var = self.try_get(cache_key) + if shape is None and not assignment: + # since there's no assignment to a variable, use any shape here + # other than None to avoid the unknown shape failures + shape = () + if not var: + var = self.newvar(bounds, dtype, shape) + self.put(cache_key, var) + if write: + if V.kernel.current_node: + V.kernel.current_node.codegen_originating_info( + buffer, only_once=True + ) + if isinstance(expr, IndentedBuffer): + if assignment: + buffer.writeline(f"{self.prefix}{var} =") + buffer.splice(expr) + buffer.writeline(self.suffix) + elif isinstance(expr, DeferredLineBase): + if not assignment: + raise AssertionError("expected assignment to be set") + buffer.writeline( + expr._new_line(f"{self.prefix}{var} = {expr.line}{self.suffix}") + ) + else: + if assignment: + line = f"{self.prefix}{var} = {expr}{self.suffix}" + else: + line = f"{expr}{self.suffix}" + buffer.writeline(line) + + # cpp backend cannot determine is_vec at this point + if ( + assignment + and ( + config.test_configs.runtime_triton_dtype_assert + or config.test_configs.static_cpp_dtype_assert + ) + and dtype is not None + and get_current_backend() != "cpp" + ): + check_dtype(buffer, var, dtype) + + else: + var.bounds = var.bounds.tighten(bounds) + var.use_count += 1 + + return var + + def newvar( + self, + bounds: ValueRanges[Any] = ValueRanges.unknown(), + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ) -> CSEVariableType: + var_name = f"{self.name_prefix}{next(self.iter_buffer_ids)}" + var = cast( + "CSEVariableType", V.kernel.create_cse_var(var_name, bounds, dtype, shape) + ) + self.varname_map[var_name] = var + return var + + def namedvar( + self, + name: str, + bounds: ValueRanges[Any] = ValueRanges.unknown(), + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ) -> CSEVariableType: + torch._check_value( + name not in self.varname_map, lambda: f"duplicate name: {name}" + ) + var = cast( + "CSEVariableType", V.kernel.create_cse_var(name, bounds, dtype, shape) + ) + self.varname_map[name] = var + return var + + +class CodeGen: + def __init__(self) -> None: + super().__init__() + self.exit_stack = contextlib.ExitStack() + + def __enter__(self) -> Self: + self.exit_stack.__enter__() + return self + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + self.exit_stack.__exit__(exc_type, exc_val, exc_tb) + + +class Kernel(CodeGen, Generic[CSEVariableType]): + """Base class for generated kernels and their code buffers.""" + + newvar_prefix: str = "" + suffix: str = "" + overrides: Callable[[], OpsHandler[Any]] | None = None + + def __init__( + self, args: KernelArgs | None = None, increase_kernel_count: bool = True + ) -> None: + super().__init__() + if increase_kernel_count: + # pyrefly: ignore [bad-assignment] + metrics.generated_kernel_count += 1 + self.args = args or KernelArgs() + self.loads = IndentedBuffer() + self.compute = IndentedBuffer() + self.stores = IndentedBuffer() + + self.atomic_add_found = False + self.num_load = 0 + self.num_store = 0 + self.num_reduction = 0 + + self.cse: CSE[CSEVariableType, Any] = CSE(self.newvar_prefix, self.suffix) + self.must_keep_buffers: OrderedSet[str] = OrderedSet() + self.store_buffer_names: OrderedSet[str] = OrderedSet() + self._load_mask: str | None = None + self._load_other: None | int | float = None + # OrderedSet in set_current_node + self.current_node: SchedulerNode | None = None + self.node_to_bounds: dict[torch.fx.Node, ValueRanges[Any]] | None = None + + self.removed_buffers: OrderedSet[str] = OrderedSet() + self.inplaced_to_remove: OrderedSet[str] = OrderedSet() + + # key: the buffer to write + # value: the buffer to read and whose memory can be reused for + # the buffer specified by key + self.inplace_update_buffers: dict[str, str] = {} + # Set minimum number of elements processed per thread. + self.min_elem_per_thread = 1 + self.kernel_name: str | None = None + + @contextlib.contextmanager + def set_current_node(self, node: SchedulerNode) -> Iterator[None]: + prior = self.current_node + self.current_node = node + self.node_to_bounds = node._body.bounds().get_bounds() + try: + yield + finally: + self.current_node = prior + + @contextlib.contextmanager + def swap_buffers( + self, + lb: IndentedBuffer, + cb: IndentedBuffer | None = None, + sb: IndentedBuffer | None = None, + ) -> Iterator[None]: + if cb is None: + cb = lb + if disallow_stores := sb is None: + sb = IndentedBuffer() + loads = self.loads + compute = self.compute + stores = self.stores + cse = self.cse + self.loads = lb + self.compute = cb + self.stores = sb + self.cse = cse.scoped_copy() + try: + yield + finally: + self.loads = loads + self.compute = compute + self.stores = stores + self.cse = cse + # pyrefly: ignore [unbound-name] + if disallow_stores: + if sb: + raise AssertionError("unexpected store inside swap_buffers") + + def emit_kernel_override( + self, + wrapper, + src_code: str, + kernel_name: str, + node_schedule, + kernel_path: str, + get_kernel_metadata, + ) -> bool: + """Override kernel emission. Return True if overridden, False to use default. + + External template handlers (e.g. Helion) can override this method + to implement custom kernel emission to the wrapper. + """ + return False + + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + raise NotImplementedError + + def indirect_load(self, name: str, index: sympy.Expr) -> CSEVariable: + """A load that depends on an index we have read""" + prior = self.loads + try: + # put the load in the compute section as it might have deps + self.loads = self.compute + return self.load(name, index) + finally: + self.loads = prior + + def store_reduction(self, name: str, index: sympy.Expr, value: CSEVariable) -> None: + raise NotImplementedError + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + raise NotImplementedError + + def device_assert_async(self, cond: CSEVariable, msg: str) -> None: + raise NotImplementedError( + f"{type(self).__name__}: device_assert_async should be handled by CSEProxy" + ) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: + raise NotImplementedError + + def partial_accumulate( + self, + name: str, + reduction_type: ReductionType, + value: CSEVariable, + extra_meta: dict[str, Any], + ) -> None: + raise NotImplementedError + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[CSEVariable, ...], tuple[CSEVariable, ...]], tuple[CSEVariable, ...] + ], + values: tuple[CSEVariable, ...], + ) -> tuple[CSEVariable, ...]: + raise NotImplementedError + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[CSEVariable, ...], + stable: bool, + descending: bool, + ) -> tuple[CSEVariable, ...]: + raise NotImplementedError + + def var_ranges(self) -> dict[sympy.Symbol, sympy.Expr]: + raise NotImplementedError + + 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] + """ + raise NotImplementedError + + @property + def assert_function(self) -> str: + raise NotImplementedError + + def indirect_assert( + self, + var: CSEVariable | str, + lower: str | None, + upper: str | None, + mask: CSEVariable | str | None = None, + ) -> str: + if isinstance(var, CSEVariable): + var = str(var) + if not isinstance(var, str): + raise AssertionError(type(var)) + if not (lower is None or isinstance(lower, str)): + raise AssertionError(f"expected lower to be None or str, got {type(lower)}") + if not (upper is None or isinstance(upper, str)): + raise AssertionError(f"expected upper to be None or str, got {type(upper)}") + if lower and upper: + # The conditions need to be in parens because of Python's operator precedence. + # It'd be less error-prone to use and/or/not, which is supported by triton + cond = f"({lower} <= {var}) & ({var} < {upper})" + cond_print = f"{lower} <= {var} < {upper}" + elif lower: + cond = f"{lower} <= {var}" + cond_print = cond + else: + if not upper: + raise AssertionError("expected upper to be set") + cond = f"{var} < {upper}" + cond_print = cond + + if mask: + cond = f"({cond}) | ~({mask})" + + return f'{self.assert_function}({cond}, "index out of bounds: {cond_print}")' + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + raise NotImplementedError + + def index_to_str(self, index: sympy.Expr) -> str: + raise NotImplementedError + + def __enter__(self) -> Self: + super().__enter__() + if not self.overrides: + raise AssertionError("expected overrides to be set") + self.exit_stack.enter_context( + V.set_ops_handler(CSEProxy(self, self.overrides())) + ) + self.exit_stack.enter_context(V.set_kernel_handler(self)) + return self + + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + self.remove_kernel_local_buffers() + super().__exit__(exc_type, exc_val, exc_tb) + + def remove_kernel_local_buffers(self) -> None: + """ + Any buffers that are both created and have a last use in the + same kernel can be removed. + + Note that V.graph.scheduler can be None when codegening triton template + kernels. + """ + scheduler = V.graph.scheduler + if not scheduler: + return + fused_node_names = OrderedSet( + scheduler.name_to_buf[buf].defining_op_name() + for buf in self.store_buffer_names + if buf in scheduler.name_to_buf + ) + names_to_remove: OrderedSet[str] = OrderedSet() + for name in self.store_buffer_names: + if ( + name not in self.must_keep_buffers + and name not in self.args.input_buffers + and scheduler.can_buffer_be_removed_through_fusion( + name, fused_node_names + ) + ): + self.num_store -= 1 + names_to_remove.add(name) + + for name in names_to_remove: + if name in self.args.inplace_buffers: + buf = self.args.inplace_buffers[name] + if isinstance(buf, RemovedArg): + continue + remove = all(n in names_to_remove for n in buf.other_names) + if remove: + self.remove_inplace_buffer(name) + self.inplaced_to_remove.add(name) + else: + self.remove_buffer(name) + + def remove_buffer(self, name: str) -> None: + # Assign a special value instead of deleting the entry + # because we still rely on output_buffers's length to + # generate unique arg name. + log.debug("remove_buffer(%r)", name) + self.args.output_buffers[name] = REMOVED + self.removed_buffers.add(name) + + def remove_inplace_buffer(self, name: str) -> None: + log.debug("removing_inplace_buffer(%r)", name) + self.args.inplace_buffers[name] = REMOVED + self.removed_buffers.add(name) + + def rename_indexing( + self, index: list[sympy.Expr] | tuple[sympy.Expr, ...] | sympy.Expr + ) -> sympy.Expr: + # adds the necessary kernel args for index expressions + # and renames variables in index expressions to kernel arg names + if isinstance(index, (list, tuple)): + return [self.rename_indexing(x) for x in index] + index = V.graph.sizevars.simplify(index) + sorted_symbols = sorted(index.free_symbols, key=lambda s: s.name) + replacements = { + x: self.args.size(x) + for x in sorted_symbols + if symbol_is_type( + x, + ( + SymT.UNBACKED_INT, + SymT.SIZE, + SymT.PRECOMPUTED_SIZE, + SymT.UNBACKED_FLOAT, + ), + ) + } + return sympy_subs(index, replacements) + + def create_cse_var(self, *args: Any, **kwargs: Any) -> CSEVariable: + return CSEVariable(*args, **kwargs) + + def arg_name(self, node: IRNode) -> str | None: + """ + Returns arg name of a given input or output node. + """ + if node is None: + return None + return self.args.arg_name(node.get_name()) + + def record_op_trace( + self, + name: str, + args: tuple[Any, ...], + kwargs: dict[str, Any], + result: Any = None, + ) -> None: + pass + + +@dataclasses.dataclass +class OptimizationContext: + key: ClassVar[str] = "opt_ctx" + + dtype: torch.dtype | None = None + ops_name: str = "" + + +@functools.cache +def jinja2_env() -> Any: + try: + import jinja2 + + return jinja2.Environment( + undefined=jinja2.StrictUndefined, + ) + except ImportError: + return None + + +class KernelTemplate: + """ + Base class for defining kernel templates. + + Children classes: TritonTemplate, CUTLASSTemplate + """ + + @staticmethod + def indent_except_first( + source: str, num_indents: int, indents_spacing: int = 4 + ) -> str: + lines = source.splitlines(True) + if len(lines) > 1: + lines[1:] = [ + (" " * indents_spacing * num_indents) + line for line in lines[1:] + ] + return "".join(lines) + + @staticmethod + def _template_from_string(source: str) -> Any: + env = jinja2_env() + if env is None: + return None + env.filters["indent_except_first"] = KernelTemplate.indent_except_first + from jinja2 import TemplateSyntaxError + + try: + return env.from_string(source) + except TemplateSyntaxError as e: + + class DetailedTemplateSyntaxError(TemplateSyntaxError): + def __init__(self, original_error: TemplateSyntaxError) -> None: + super().__init__( + original_error.message, + original_error.lineno, + original_error.name, + original_error.filename, + ) + self.original_error = original_error + + def __str__(self) -> str: + error_info = f"Error in template at line {self.lineno}\n" + error_info += f"Error message: {self.message}\n" + if hasattr(self.original_error, "source"): + lines = self.original_error.source.split("\n") + error_info += "Context:\n" + start = max(0, self.lineno - 2) + end = min(len(lines), self.lineno + 2) + for i in range(start, end): + if i == self.lineno - 1: + error_info += f"{i + 1}: --> {lines[i]}\n" + if hasattr(self.original_error, "column"): + error_info += ( + " " + + " " * (self.original_error.column - 1) + + "^\n" + ) + else: + error_info += f"{i + 1}: {lines[i]}\n" + return error_info + + raise DetailedTemplateSyntaxError(e) from e + + @staticmethod + def _fake_get_dtype( + fake_outs: list[Buffer] | Buffer, + ) -> Callable[[str], torch.dtype]: + _get_dtype_real = V.graph.get_dtype + if isinstance(fake_outs, (list, tuple)): + lookup = {buf.get_name(): buf.get_dtype() for buf in fake_outs} + else: + lookup = {fake_outs.get_name(): fake_outs.get_dtype()} + + def get_dtype(name: str) -> torch.dtype: + result = lookup.get(name) + if result is not None: + return result + return _get_dtype_real(name) + + return get_dtype + + def __init__(self, name: str, hash: str | None = None) -> None: + self.name = name + self._hash = hash + + @property + def uid(self) -> str: + """ + entry point to override for templates to ensure a uid e.g. through a prefix + + the purpose of this is that every KernelTemplate/ExternKernelChoice is unique + in the system, but reproducible e.g. restarting pytorch should yield the same id + """ + # TODO(coconutruben): add some central registration to assert on global uniqueness + return self.name + + @property + def src_hash(self) -> str | None: + """ + source hash for a Template. + + Templates can optionally provide a src hash to make it easier to cache/validate that + a template has not changed from one version to another. Override this if that detection + is different for your specific Template + """ + return self._hash + + 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 self.generate() 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: + """ + 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: + choices.append(self.generate(**kwargs)) + 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 + + def generate(self, **kwargs: Any) -> ChoiceCaller: + """ + Generates a ChoiceCaller instance from the given arguments. + """ + + raise NotImplementedError + + +class CSEProxy(DefaultHandler): + """A ops handler that proxies calls to `kernel` and its + handler and returns `CSEVariable`s with correct shape and dtype. + """ + + name = "CSEProxy" + + def __init__(self, kernel: Kernel[Any], parent_handler: OpsHandler[Any]): + super().__init__() + from ..bounds import ValueRangeAnalysis + + self.vr_analysis = ValueRangeAnalysis() + self.kernel = kernel + self.parent_handler = parent_handler + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + bounds = self._bound_variable(name, *args, **kwargs) + + value = getattr(self.parent_handler, name)(*args, **kwargs) + dtype_handler = DtypePropagationOpsHandler() + shape_handler = ShapePropagationOpsHandler() + + backend = get_current_backend() + + shape_op = getattr(shape_handler, name) + output_dtype = None + output_shape = None + + if name == "masked" and backend == "triton": + output_dtype = value.dtype + output_shape = value.shape + elif name == "masked" and backend == "cpp": + output_dtype = V.interpreter.current_node.meta.get( + OptimizationContext.key, None + ).dtype + # TODO: fix me + output_shape = None + elif backend in ("triton", "cpp", "mps"): + dtype_op = getattr(dtype_handler, name) + output_dtype = dtype_op(*args, **kwargs) + output_shape = shape_op(*args, **kwargs) + + if backend in ("triton", "cpp"): + # maybe there are some exceptions on mps? + if output_dtype is None: + raise AssertionError("expected output_dtype to be not None") + + output_idx = 0 + + def do_cse(v: str | CSEVariable) -> CSEVariable: + # we tree_map over the output, so we need to fetch corresponding dtype + nonlocal output_idx + var_dtype: torch.dtype | None = ( + output_dtype[output_idx] + if isinstance(output_dtype, (list, tuple)) + else output_dtype + ) + var_shape: BlockShapeType = ( + output_shape[output_idx] # type: ignore[assignment] + if isinstance(output_shape, (list, tuple)) + and len(output_shape) > 0 + and isinstance(output_shape[0], (list, tuple)) + else output_shape + ) + output_idx += 1 + + # some cpp op implementations don't set the dtype + if isinstance(v, CSEVariable): + if backend == "cpp" and v.dtype is None: + v.dtype = var_dtype + if v.shape is None: + v.shape = var_shape + + csevar = V.kernel.cse.generate( + V.kernel.compute, + v, + bounds=bounds, + # pyrefly: ignore[bad-argument-type] + dtype=output_dtype, + shape=output_shape, + ) + + csevar.update_on_args(name, args, kwargs) + + if ( + config.test_configs.runtime_triton_dtype_assert + or config.test_configs.static_cpp_dtype_assert + ) and var_dtype is not None: + check_dtype(V.kernel.compute, csevar, var_dtype) + + if ( + config.test_configs.runtime_triton_shape_assert + and _is_runtime_triton_assert_target() + ): + shape_to_check = csevar.shape if csevar.shape is not None else var_shape + if shape_to_check is not None: + check_shape(V.kernel.compute, csevar, shape_to_check) + + if config.runtime_triton_nan_asserts: + check_nan(V.kernel.compute, csevar) + + return csevar + + result = pytree.tree_map(do_cse, value) + self.kernel.record_op_trace(name, args, kwargs, result) + return result + + def _bound_variable(self, name: str, *args: Any, **kwargs: Any) -> ValueRanges[Any]: + """ + If the variable comes from an FX node, we forward the bound we have already computed + Else, if the variable when codegen'ing another op, we try to compute its bounds + """ + from ..bounds import ValueRangeAnalysis + from ..select_algorithm import TritonTemplateKernel + from .cutlass.kernel import CUTLASSTemplateKernel + + if isinstance(V.kernel, TritonTemplateKernel): + return ValueRanges.unknown() + + if isinstance(V.kernel, CUTLASSTemplateKernel): + return ValueRanges.unknown() + + if isinstance(V.interpreter, NullHandler): + return ValueRanges.unknown() + + fx_node = V.interpreter.current_node + if fx_node.target == name and self.kernel.node_to_bounds is not None: + if not isinstance(self.kernel.node_to_bounds, dict): + raise AssertionError(type(self.kernel.node_to_bounds)) + return self.kernel.node_to_bounds.get(fx_node, ValueRanges.unknown()) + elif config.compute_all_bounds and hasattr(ValueRangeAnalysis, name): + # These create lots of inner strings. We would need to compute the bounds at the ops + # We will also likely not get much from computing VRs on these nodes + if any(s in fx_node.target for s in ("set_indirect", "reduction", "scan")): + return ValueRanges.unknown() + + # We assume that the inputs come from `ops.` and are not strings. If you want to generate + # intermediary strings, wrap them in CSE variables with properly initialised bounds. + + # If there is no FX bound but we know how to compute one we do so + if kwargs: + raise AssertionError("expected no kwargs") + + def arg_to_bound(x: Any) -> Any: + if isinstance(x, CSEVariable): + return x.bounds + elif isinstance(x, sympy.Expr): + return bound_sympy(x) + else: + return x + + arg_bounds = list(map(arg_to_bound, args)) + return getattr(self.vr_analysis, name)(*arg_bounds) + return ValueRanges.unknown() + + def indirect_indexing( + self, + var: CSEVariable, + size: sympy.Expr | int, + check: bool = True, + wrap_neg: bool = True, + ) -> sympy.Symbol: + if isinstance(size, int): + size = sympy.Integer(size) + if not isinstance(size, sympy.Expr): + raise AssertionError((type(size), size)) + # Skip CSE since this doesn't return an expression + + if var.bounds.lower < 0: + if wrap_neg: + stm = ops.add(var, ops.index_expr(size, torch.long)) + # Mixed negative and non-negative + if var.bounds.upper >= 0: + lt = ops.lt(var, 0) + stm = ops.where(lt, stm, var) + else: + stm = var + + # Propagate bounds as we know how to compute them properly. + # When wrap_neg=False, negative indices stay negative and must keep + # their original bounds so lower-bound checks are not elided. + new_bounds = var.bounds if not wrap_neg else ValueRanges.unknown() + if ( + wrap_neg + and var.bounds != ValueRanges.unknown() + and isinstance(size, sympy.Number) + ): + # Take the negative part of the bound and add size to it + # Then take union of that and the positive part + # This is a tighter bound than that of a generic ops.where, as we have info on the cond + neg_bounds = var.bounds & ValueRanges(-int_oo, -1) + new_bounds = ValueRanges( + neg_bounds.lower + size, neg_bounds.upper + size + ) + # We don't have a good way of representing the empty range + if var.bounds.upper >= 0: + pos = var.bounds & ValueRanges(0, int_oo) + new_bounds = new_bounds | pos + + var = self.kernel.cse.generate( + self.kernel.compute, + stm, + bounds=new_bounds, + dtype=var.dtype, + shape=var.shape, + ) + + sympy_var = self.parent_handler.indirect_indexing(var, size, check) + if generate_assert(check): + assert_lower = not (var.bounds.lower >= 0) + # value ranges cannot x < s when x and s are symbols + assert_upper = not isinstance(size, sympy.Number) or not ( + var.bounds.upper < size + ) + self.kernel.check_bounds(sympy_var, size, assert_lower, assert_upper) + return sympy_var + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + return self.kernel.check_bounds(expr, size, lower, upper) + + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + if name in self.kernel.cse.invalidated_stores: + # A load from an invalidated store requires us to + # keep the actual buffer around + V.kernel.must_keep_buffers.add(name) + if free_symbol_is_type(index, SymT.TMP): + return self.kernel.indirect_load(name, index) + store_cache = self.kernel.cse.store_cache + if name in store_cache: + return store_cache[name] + out = self.kernel.load(name, index) + # count load that is not in the store_cache, and also not in the + # cse cache. + if out.use_count == 1: + self.kernel.num_load += 1 + self.kernel.record_op_trace("load", (name, index), {}, out) + return out + + def _update_store_cache(self, name: str, value: CSEVariable) -> None: + self.kernel.cse.store_cache[name] = value + if self.kernel.current_node and name in V.graph.name_to_buffer: + buf = self.kernel.current_node.get_output(name) + for other_name in buf.get_mutations(): + self.kernel.cse.store_cache[other_name] = value + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + self.kernel.store_buffer_names.add(name) + # Update store cache when mode is None or "tma" + if mode != "atomic_add": + self._update_store_cache(name, value) + if name not in V.graph.removed_buffers: + self.kernel.store(name, index, value, mode=mode) + self.kernel.num_store += 1 + self.kernel.record_op_trace("store", (name, index, value, mode), {}) + + def device_assert_async(self, cond: CSEVariable, msg: str) -> None: + self.kernel.device_assert_async(cond, msg) + self.kernel.record_op_trace("device_assert_async", (cond, msg), {}) + + # pyrefly: ignore [bad-override] + def partial_accumulate(self, *args: Any) -> None: + self.kernel.partial_accumulate(*args) + + def store_reduction(self, name: str, index: sympy.Expr, value: CSEVariable) -> None: + self.kernel.store_buffer_names.add(name) + self._update_store_cache(name, value) + + if name not in V.graph.removed_buffers: + self.kernel.num_store += 1 + return self.kernel.store_reduction(name, index, value) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: + self.kernel.num_reduction += 1 + return self.kernel.reduction(dtype, src_dtype, reduction_type, value) + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[CSEVariable, ...], tuple[CSEVariable, ...]], + tuple[CSEVariable, ...], + ], + values: tuple[CSEVariable, ...], + ) -> tuple[CSEVariable, ...]: + return self.kernel.scan(dtypes, combine_fn, values) + + def sort( + self, + dtypes: tuple[torch.dtype, ...], + values: tuple[CSEVariable, ...], + stable: bool, + descending: bool, + ) -> tuple[CSEVariable, ...]: + return self.kernel.sort(dtypes, values, stable, descending) + + 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: + """ + [Note: Inductor bucketize op] + + Inputs: + ------- + values: the values to be bucketized. + boundaries: a tuple containing + (a) the name of the boundaries tensor (which must be sorted, unless + the sorting tensor is present), + (b) the length of the tensor in the last dimension (i.e. the length of + one set of boundaries), + (c) the number of elements in the underlying storage (i.e. the length + of the flattened tensor, ignoring striding), and + (d) the stride of the tensor in the last dimension. + boundary_indices: indices into a flattened version of the boundaries + tensor, of the same size and shape as "values". Each index points to + the first element in the set of boundaries to be used for the + corresponding value. + indexing_dtype: the dtype to use when indexing into the boundaries + tensor. This must be int64 or int32. This additionally specifies the + dtype of the return value. + right: see "Details" below. + sorter: an optional tuple containing + (a) the name of an optional sorting tensor, used to access unsorted + boundaries without reordering the boundaries tensor, and + (b) the stride of the tensor in the last dimension. + The values in the sorting tensor are used as indices into the *last* + dimension of the boundaries tensor, with all other indices matching. + The size of the sorting and boundaries tensors must be equivalent. + sorter_indices: must be present if the sorting array is present; see + "boundary_indices" for the equivalent definition for the boundaries + tensor. + + Output: + ------- + The buckets each value belongs in, within a given set of boundaries. 0 + indicates a position before the first boundary, and len(boundaries_set) + represents a position after the last boundary. + + Details: + -------- + Given a value and a set of boundaries, calculate the bucket that each + value belongs to. This works differently in 1-D and N-D cases. + + for values [[-1, 0, 1, 2], [3, 4, 5, 9]], boundaries [0, 4, 4, 8], right=True + return = [[ 0, 1, 1, 1], [1, 3, 3, 4]]. + + for values [[-1, 0, 1, 2], [3, 4, 5, 9]], boundaries [[0, 4], [4, 8]], right=True + return = [[ 0, 1, 1, 1], [0, 1, 1, 2]] + + Note that in the N-D boundaries case, the shape of "values" and + "boundaries" must match in every dimension _except_ the last. + + When right == False, bucket i refers to range (boundaries[i], boundaries[i+1]]. + When right == True, bucket i refers to range [boundaries[i], boundaries[i+1]). + + Boundaries must be non-decreasing, or a sorter must be provided which + would re-index offsets in a non-decreasing order (e.g. the second output + of torch.sort(offsets)). Otherwise, the result is undefined. + """ + return self.kernel.bucketize( + values, + boundaries, + boundary_indices, + indexing_dtype, + right, + sorter, + sorter_indices, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp.py new file mode 100644 index 0000000000000000000000000000000000000000..76ab9cadc22086daa43dffa51ff06724eb1d386f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp.py @@ -0,0 +1,6482 @@ +# mypy: allow-untyped-defs +import contextlib +import dataclasses +import functools +import itertools +import math +import operator +import os +import re +import sys +import warnings +from collections.abc import Callable, Sequence +from enum import Enum +from typing import Any, cast, ClassVar, Literal, Optional + +import sympy + +import torch +import torch.fx +from torch._inductor import dependencies +from torch._prims_common import is_float_dtype, is_integer_dtype +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import CeilDiv, FloorDiv, ModularIndexing +from torch.utils._sympy.symbol import free_symbol_is_type, symbol_is_type, SymT + +from ..._dynamo.utils import counters +from .. import config, cpp_builder, cpu_vec_isa, ir, metrics +from ..debug import set_kernel_post_grad_provenance_tracing +from ..loop_body import LoopBody +from ..scheduler import ( + BaseSchedulerNode, + BaseScheduling, + ExternKernelSchedulerNode, + ForeachKernelSchedulerNode, + FusedSchedulerNode, + Scheduler, + SchedulerNode, +) +from ..sizevars import stride_at_vec_range +from ..utils import ( + cache_on_self, + get_bounds_index_expr, + get_fused_kernel_name, + has_free_symbols, + is_multi_outputs_template, + is_welford_reduction, + parallel_num_threads, + Placeholder, + sympy_index_symbol, + sympy_index_symbol_with_prefix, + sympy_product, + sympy_subs, +) +from ..virtualized import NullKernelHandler, ops, OpsValue, V +from .common import ( + BackendFeature, + BracesBuffer, + CSE, + CSEVariable, + DataTypePropagation, + DeferredLine, + DTYPE_TO_COMPUTATION_DTYPE, + IndentedBuffer, + Kernel, + KernelArgs, + OpOverrides, + OptimizationContext, +) +from .cpp_utils import ( + _get_dtype_from_loopbodies, + _get_loop_body, + cexpr, + cexpr_index, + codegen_rand, + CppCSEVariable, + DTYPE_TO_CPP, + get_promote_dtype, + INDEX_TYPE, + LocalBufferContext, + may_unify_binary_op_mask_type, + promote_args, + template_fusion_with_epilogues_supported, + unify_mask_base_type, + value_to_cpp, +) + + +_IS_WINDOWS = sys.platform == "win32" + + +@functools.cache +def get_export_declaration(): + return "__declspec(dllexport)" if _IS_WINDOWS else "" + + +schedule_log = torch._logging.getArtifactLogger(__name__, "schedule") + +NATIVE_OMP_RTYPES = OrderedSet(["+", "*", "^", "||", "min", "max"]) +RTYPE_TO_CPP = { + "sum": "+", + "prod": "*", + "xor_sum": "^", + "min": "min", + "max": "max", + "argmin": "argmin", + "argmax": "argmax", + "any": "||", + "welford_reduce": "welford", + "welford_combine": "welford", +} +VECTORIZABLE_RTYPES = OrderedSet( + [ + "max", + "min", + "sum", + "prod", + "xor_sum", + "welford_reduce", + "welford_combine", + "argmin", + "argmax", + "any", + ] +) + +PYTHON_TO_CPP = { + "Tensor": "at::Tensor", + "int": "long", + "float": "double", + "bool": "bool", + "str": "std::string", + "ScalarType": "c10::ScalarType", + "MemoryFormat": "at::MemoryFormat", + "Layout": "at::Layout", + "Device": "at::Device", + "number": "at::Scalar", +} + +CONTAINER_PYTHON_TO_CPP = { + "List": "std::vector", + "Optional": "std::optional", +} + +DTYPE_LOWP_FP = [ + torch.bfloat16, + torch.float16, +] + +VECTORIZABLE_DTYPES: list[torch.dtype] = [ + torch.float64, + torch.float, + torch.bfloat16, + torch.float16, + torch.bool, + torch.uint8, + torch.int8, + torch.int32, + torch.int64, + torch.float8_e4m3fn, + torch.float8_e5m2, +] + + +def reduction_init(reduction_type, dtype): + if dtype in DTYPE_LOWP_FP: + # Since load promotes all half-precision inputs to float, the initial + # constant for reduction must be promoted as well + dtype = torch.float32 + if reduction_type in ("xor_sum", "sum", "any"): + return 0 + if reduction_type == "prod": + return 1 + if reduction_type in ("max", "argmax", "min", "argmin"): + cdtype = DTYPE_TO_CPP[dtype] + if dtype == torch.bool and reduction_type in ("argmin", "argmax"): + cdtype = DTYPE_TO_CPP[torch.float] + min_var = ( + f"-std::numeric_limits<{cdtype}>::infinity()" + if is_float_dtype(dtype) + else f"std::numeric_limits<{cdtype}>::min()" + ) + max_var = ( + f"std::numeric_limits<{cdtype}>::infinity()" + if is_float_dtype(dtype) + else f"std::numeric_limits<{cdtype}>::max()" + ) + init_var = min_var if reduction_type in ("max", "argmax") else max_var + return ( + init_var + if reduction_type in ("max", "min") + else f"IndexValue<{cdtype}>{{0, {init_var}}}" + ) + if is_welford_reduction(reduction_type): + return f"Welford<{DTYPE_TO_CPP[dtype]}>()" + raise AssertionError(reduction_type) + + +def reduction_acc_type(reduction_type, dtype): + scalar_type = DTYPE_TO_CPP[DTYPE_TO_COMPUTATION_DTYPE[dtype]] + if is_welford_reduction(reduction_type): + return f"Welford<{scalar_type}>" + if reduction_type in ("argmin", "argmax"): + if dtype == torch.bool: + scalar_type = DTYPE_TO_CPP[torch.float] + return f"IndexValue<{scalar_type}>" + return scalar_type + + +def reduction_combine( + reduction_type, + var, + next_value, + helper_val=None, + index: sympy.Expr | CSEVariable | None = None, + src_dtype=None, +): + is_bool = src_dtype == torch.bool + if reduction_type == "sum": + if helper_val: + return f"cascade_sum_combine({next_value}, &{helper_val})" + else: + conjunction = "|" if is_bool else "+" + return f"{var} {conjunction} {next_value}" + if reduction_type == "prod": + return f"{var} * {next_value}" + if reduction_type == "xor_sum": + return f"{var} ^ {next_value}" + if reduction_type == "any": + return f"{var} || {next_value}" + if reduction_type in ("min", "max"): + return f"{reduction_type}_propagate_nan({var}, {next_value})" + if reduction_type == "welford_reduce": + if helper_val: + return f"welford_combine({var}, {next_value}, &{helper_val})" + else: + return f"welford_combine({var}, {next_value})" + if reduction_type == "welford_combine": + if isinstance(next_value, tuple): + mean, m2, weight = next_value + else: + mean, m2, weight = reduction_project(reduction_type, next_value) + return f"welford_combine({var}, {{{mean}, {m2}, {weight}}})" + if reduction_type in ("argmin", "argmax"): + if ( + hasattr(next_value, "dtype") + and next_value.dtype == torch.bool + and not next_value.is_vec + ): + if index is not None: + return f"{reduction_type}_combine({var}, static_cast({next_value}), {index})" + else: + return ( + f"{reduction_type}_combine({var}, static_cast({next_value}))" + ) + if index is not None: + return f"{reduction_type}_combine({var}, {next_value}, {index})" + else: + return f"{reduction_type}_combine({var}, {next_value})" + raise AssertionError(reduction_type) + + +def reduction_project(reduction_type, acc): + if is_welford_reduction(reduction_type): + return f"{acc}.mean", f"{acc}.m2", f"{acc}.weight" + elif reduction_type in ("argmin", "argmax"): + return f"{acc}.index" + return acc + + +def move_code_under_inner_loop( + code: IndentedBuffer, + iter_var: sympy.Expr, + new_iter_var: str, + loop_start: sympy.Expr, + loop_end: sympy.Expr, +) -> BracesBuffer: + r""" + f(iter_var) is transformed to f(new_iter_var) under the inner loop + \/ + for (new_iter_var = loop_start; new_iter_var < loop_end; new_iter_var++) { + f(new_iter_var) + } + Please be careful while using this function, + as the variable defined in f(iter_var) will be invalid outside the for loop. + For example: + auto tmp0 = in_ptr[x0]; -> + for (new_x0 = start; new_x0 < end; new_x0++){ + auto tmp0 = in_ptr[new_x0]; + } + The tmp0 is invalid outside the loop. + """ + transformed_code = BracesBuffer() + with contextlib.ExitStack() as stack: + transformed_code.writeline( + f"for ({INDEX_TYPE} {new_iter_var} = {cexpr_index(loop_start)};" + + f"{new_iter_var} < {cexpr_index(loop_end)}; {new_iter_var}++)" + ) + stack.enter_context(transformed_code.indent()) + for _, line in enumerate(code._lines): + if not ( + isinstance( + line, + ( + str, + DeferredLine, + ), + ) + ): + raise AssertionError( + "expected isinstance( line, ( str, DeferredLine, ), )" + ) + deferred_name = None + if isinstance(line, DeferredLine): + deferred_name = line.name + line = line.line + new_line = re.sub(r"\b" + f"{iter_var}" + r"\b", f"{new_iter_var}", line) + if deferred_name: + new_line = DeferredLine(deferred_name, new_line) # type: ignore[assignment] + transformed_code.writeline(new_line) + return transformed_code + + +def reduction_prefix_array( + acc_var: str | CSEVariable, + acc_type: str, + reduction_type: str, + dtype: torch.dtype, + len: str | int, + init_fn, +): + """ + MSVC don't support dynamic array(VLA). So we use std::unique_ptr here. + Ref: https://stackoverflow.com/questions/56555406/creating-dynamic-sized-array-using-msvc-c-compiler + MSVC is the only one compiler without VLA. support. Since MSVC can't get good performance here. + We just use unique_ptr make it works on MSVC. + For other compilers, we continue to use VLA to get best performance. + """ + code_buffer = IndentedBuffer() + acc_decl = ( + f"auto {acc_var}_arr = std::make_unique<{acc_type}[]>({len});" + if cpp_builder.is_msvc_cl() + else f"{acc_type} {acc_var}_arr[{len}];" + ) + code_buffer.writeline(f"{acc_decl}") + code_buffer.writelines( + [ + f"for (int i = 0; i < {len}; i++)", + "{", + f" {acc_var}_arr[i] = {init_fn(reduction_type, dtype)};", + "}", + ], + ) + return code_buffer + + +def replace_acc_name(buffer: IndentedBuffer, name: str, new_name: str): + for i, line in enumerate(buffer._lines): + if not ( + isinstance( + line, + ( + str, + DeferredLine, + ), + ) + ): + raise AssertionError("expected isinstance( line, ( str, DeferredLine, ), )") + if isinstance(line, DeferredLine): + line.line = re.sub(r"\b" + f"{name}" + r"\b", f"{new_name}", line.line) + else: + buffer._lines[i] = re.sub(r"\b" + f"{name}" + r"\b", f"{new_name}", line) + + +def replace_cascade_sum_with_add(buffer: IndentedBuffer): + """ + Replaces `acc = cascade_sum_combine(value, ...)` with `acc = acc + value;` + """ + + pattern = r"(.*?)\s*=\s*cascade_sum_combine\(([^,]+),.*?\);" + for i, line in enumerate(buffer._lines): + if not ( + isinstance( + line, + ( + str, + DeferredLine, + ), + ) + ): + raise AssertionError("expected isinstance( line, ( str, DeferredLine, ), )") + content = line.line if isinstance(line, DeferredLine) else line + match = re.search(pattern, content) + if match: + acc, value = match.groups() + new_content = re.sub(pattern, f"{acc} = {acc} + {value};", content) + if isinstance(line, DeferredLine): + line.line = new_content + else: + buffer._lines[i] = new_content + + +@dataclasses.dataclass +class ParallelDepth: + """ + A class representing parallel depth. + Includes the starting depth of parallelism and the depth of parallelism. + """ + + parallel_depth: int + start_depth: int + + +class OuterLoopFusedSchedulerNode(FusedSchedulerNode): + @classmethod + def fuse( # type: ignore[override] + cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode, outer_loop_fusion_depth + ): + if node1.scheduler is not node2.scheduler: + raise AssertionError("expected node1.scheduler is node2.scheduler") + if not ( + all( + type(node) + in ( + OuterLoopFusedSchedulerNode, + SchedulerNode, + FusedSchedulerNode, + ) + for node in (node1, node2) + ) + ): + raise AssertionError( + "expected all nodes to be OuterLoopFusedSchedulerNode, " + "SchedulerNode, or FusedSchedulerNode" + ) + if any(type(node) is OuterLoopFusedSchedulerNode for node in (node1, node2)): + return cls( + node1.scheduler, + # pyrefly: ignore [bad-argument-type] + ( + list(node1.get_outer_nodes()) + if type(node1) is OuterLoopFusedSchedulerNode + else [ + node1, + ] + ) + + ( + list(node2.get_outer_nodes()) + if type(node2) is OuterLoopFusedSchedulerNode + else [ + node2, + ] + ), + outer_loop_fusion_depth, + ) + else: + return cls(node1.scheduler, [node1, node2], outer_loop_fusion_depth) # type: ignore[list-item] + + def __init__( + self, + scheduler: "Scheduler", + outer_fused_nodes: list[FusedSchedulerNode | SchedulerNode], + outer_loop_fusion_depth, + ): + self.outer_fused_nodes: list[FusedSchedulerNode | SchedulerNode] = ( + outer_fused_nodes + ) + self.outer_loop_fusion_depth = outer_loop_fusion_depth + flatten_snodes = [] + for _node in self.outer_fused_nodes: + if not isinstance(_node, (SchedulerNode, FusedSchedulerNode)): + raise AssertionError( + "expected isinstance(_node, (SchedulerNode, FusedSchedulerNode))" + ) + flatten_snodes.extend(list(_node.get_nodes())) + super().__init__(scheduler, flatten_snodes) # type: ignore[arg-type] + + def get_outer_nodes(self): + return self.outer_fused_nodes + + def check_outer_fusion_loop_level_attr( + self, cpp_kernel_proxy_list, outer_loop_fusion_depth + ): + # This function ensures that the same tiling split is applied at each loop level within the outer loop fusion depth. + # In the fusion stage, we only examine nodes with same vars and reduce. + # However, for nodes with same vars and reduce, the loops may still have different tile splits. + # For example (test_expr_vec_non_contiguous in test_cpu_repro.py): + # * buf0 tiling along the 2nd loop level, buf1 tiling along the 3rd loop level. + # If the check failed, we should fall back to standard loop codegen. + def _inner( + left_loop_nest: LoopNest, + right_loop_nest: LoopNest, + loop_fusion_depth: int, + current_checking_depth: int, + ) -> bool: + if not left_loop_nest.loops: + raise AssertionError("expected left_loop_nest.loops") + if not right_loop_nest.loops: + raise AssertionError("expected right_loop_nest.loops") + left_loop_level = left_loop_nest.loops[current_checking_depth] + right_loop_level = right_loop_nest.loops[current_checking_depth] + # Check if same loop level attr + outer_loops_attr_compare_list = [ + "var", + "size", + "offset", + "steps", + ] + if not ( + all( + getattr(left_loop_level, attr_compare) + == getattr(right_loop_level, attr_compare) + for attr_compare in outer_loops_attr_compare_list + ) + ): + return False + + if loop_fusion_depth < 1: + raise AssertionError("expected loop_fusion_depth >= 1") + if (loop_fusion_depth := loop_fusion_depth - 1) > 0: + # Check next loop level attr + current_checking_depth = current_checking_depth + 1 + if current_checking_depth >= len(left_loop_nest.loops): + raise AssertionError( + "expected current_checking_depth < len(left_loop_nest.loops)" + ) + if current_checking_depth >= len(right_loop_nest.loops): + raise AssertionError( + "expected current_checking_depth < len(right_loop_nest.loops)" + ) + if not _inner( + left_loop_nest, + right_loop_nest, + loop_fusion_depth, + current_checking_depth, + ): + return False + + return True + + for idx in range(len(cpp_kernel_proxy_list) - 1): + left_loop_nest = cpp_kernel_proxy_list[idx].loop_nest + right_loop_nest = cpp_kernel_proxy_list[idx + 1].loop_nest + if not _inner( + left_loop_nest, + right_loop_nest, + outer_loop_fusion_depth, + 0, + ): + return False + + for cpp_kernel_proxy in cpp_kernel_proxy_list: + outer_ranges = functools.reduce( + operator.mul, + cpp_kernel_proxy.ranges[:outer_loop_fusion_depth], + ) + # When the range of the first inner loop is much larger than the range of + # all outer loops, do not fuse outer loop and fallback to standard loop codegen, + # so that the inner loops with larger range have a chance to be parallelized. + # We set a conservative threshold here: + # First inner loop range / all outer loops range > 300. + if ( + len(cpp_kernel_proxy.ranges) > outer_loop_fusion_depth + and isinstance(outer_ranges, sympy.Integer) + and isinstance( + cpp_kernel_proxy.ranges[outer_loop_fusion_depth], + sympy.Integer, + ) + and outer_ranges * 300 + < cpp_kernel_proxy.ranges[outer_loop_fusion_depth] + ): + return False + + return True + + def merge_outer_fusion_kernels( + self, + cpp_kernel_proxy_list, + ): + kernel_group = cpp_kernel_proxy_list[0].kernel_group + outer_loop_fused_kernel = OuterLoopFusedKernel(kernel_group) + outer_loop_fused_kernel.inner = [ + proxy.loop_nest.from_loop_level(self.outer_loop_fusion_depth) + for proxy in cpp_kernel_proxy_list + ] + outer_fused_proxy = cpp_kernel_proxy_list[0] + outer_fused_proxy.loop_nest.kernel = outer_loop_fused_kernel + outer_fused_proxy.loop_nest.loops = outer_fused_proxy.loop_nest.loops[ + : self.outer_loop_fusion_depth + ] + return outer_fused_proxy + + +class RecordOptimizationContext: + def __init__(self, func_name: str = ""): + self.func_name = func_name + self.current_node: torch.fx.Node | None = None + self.opt_ctx: OptimizationContext | None = None + + def __enter__(self): + if not V.interpreter: + raise AssertionError("expected V.interpreter") + if not V.interpreter.current_node: + raise AssertionError("expected V.interpreter.current_node") + + self.current_node = V.interpreter.current_node + if self.current_node is None: + raise AssertionError("expected self.current_node is not None") + if OptimizationContext.key in self.current_node.meta: + self.opt_ctx = self.current_node.meta[OptimizationContext.key] + else: + self.opt_ctx = OptimizationContext() + if self.opt_ctx is None: + raise AssertionError("expected self.opt_ctx is not None") + self.opt_ctx.ops_name = self.func_name + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if not self.current_node: + raise AssertionError("expected self.current_node") + if not self.opt_ctx: + raise AssertionError("expected self.opt_ctx") + self.current_node.meta[OptimizationContext.key] = self.opt_ctx + + def get_opt_ctx(self): + return self.opt_ctx + + def get_fx_node(self): + if not self.current_node: + raise AssertionError("expected self.current_node") + return self.current_node + + +def arith_promoted(op, a, b): + args = (a, b) + if any(isinstance(arg, CppCSEVariable) and arg.is_vec for arg in args): + raise AssertionError("Promotion of vector types is not supported") + + dtype = get_promote_dtype(args) + cpp_type = DTYPE_TO_CPP[dtype] if dtype is not None else f"decltype({a})" + if dtype in (torch.int32, torch.int64): + # signed overflow is UB in C++; int8/int16 promote to int and cannot overflow + cast = f"static_cast>" + return f"{cpp_type}({cast}({a}) {op} {cast}({b}))" + return f"{cpp_type}({a} {op} {b})" + + +class CppOverrides(OpOverrides): + """Map element-wise ops to C++""" + + @staticmethod + def add(a, b): + return arith_promoted("+", a, b) + + @staticmethod + def sub(a, b): + return arith_promoted("-", a, b) + + @staticmethod + def mul(a, b): + return arith_promoted("*", a, b) + + @staticmethod + def to_dtype(x, dtype, src_dtype=None, use_compute_types=True): + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if src_dtype is None: + src_dtype = x.dtype + expr = V.kernel.get_to_dtype_expr(x, dtype, src_dtype) + csevar = V.kernel.cse.generate(V.kernel.compute, expr) + csevar.update_on_args("to_dtype", (x, dtype), {"src_dtype": src_dtype}) + if ( + use_compute_types + and dtype in DTYPE_LOWP_FP + and src_dtype == torch.float + and not config.emulate_precision_casts + ): + """ + https://github.com/pytorch/pytorch/issues/115260 + For FusedSchedulerNode[node1, node2], the node2 loads what node1 stores and the buffer is + in low-precision floating point data type. When the output of node1 also serves as the output of the + kernel, the result of nodes would be different from the case when output of node1 is not the output + of the kernel (where we don't need to insert `to_dtype` for legalization). To address the problem, on + storing the lowp node1 output, we also add the inverse dtype conversion to high precision data type + to the cse cache. + + Example (pseudo code): + node1_output = ... + node1_output_lowp = to_dtype(node1_output, dtype=torch.bfloat16) + store(buf, node1_output_lowp) + node2_input_lowp = load(buf) + node2_input = to_dtype(node2_input_lowp, dtype=torch.float) + + Without cse cache trick: + node1_output = ... + node1_output_lowp = to_dtype(node1_output, dtype=torch.bfloat16) + store(buf, node1_output_lowp) + node2_input_lowp = node_output_lowp # hit store cache + node2_input = to_dtype(node2_input_lowp, dtype=torch.float) + + With cse cache trick: + node1_output = ... + node1_output_lowp = to_dtype(node1_output, dtype=torch.bfloat16) + # also add `to_dtype(node1_input_lowp, dtype=torch.float)` -> `node1_output` to cse cache + store(buf, node1_output_lowp) + node2_input_lowp = node_output_lowp # hit store cache + node2_input = node1_output # hit cse cache + + This cache trick skips the lowp->fp32 round-trip rounding, so it is + disabled under emulate_precision_casts, where that rounding must be + preserved (e.g. an explicit fp32->fp16->fp32 user cast). See #185337. + """ + V.kernel.cache_dtype_convert(x, src_dtype, csevar, dtype) + return csevar + + @staticmethod + # pyrefly: ignore [bad-override] + def round_to_int(x, dtype, src_dtype=None, use_compute_types=True): + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if src_dtype is None: + src_dtype = x.dtype + expr = V.kernel.get_to_dtype_expr(x, dtype, src_dtype, rounding=True) + csevar = V.kernel.cse.generate(V.kernel.compute, expr) + csevar.update_on_args("round_to_int", (x, dtype), {"src_dtype": src_dtype}) + if ( + dtype in DTYPE_LOWP_FP + and src_dtype == torch.float + and not config.emulate_precision_casts + ): + V.kernel.cache_dtype_convert(x, src_dtype, csevar, dtype) + return csevar + + @staticmethod + def to_dtype_bitcast(x, dtype, src_dtype): + if dtype not in DTYPE_TO_CPP: + raise AssertionError(f"{dtype} missing from {__name__}.DTYPE_TO_CPP") + return f"c10::bit_cast<{DTYPE_TO_CPP[dtype]}>({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def abs(x): + if isinstance(x, CppCSEVariable) and x.dtype in ( + torch.uint8, + torch.uint16, + torch.uint32, + torch.uint64, + ): + # abs(x) == x for unsigned types; return identity to avoid + # -Wtautological-compare and unsigned unary minus warnings. + return f"{x}" + return f"std::abs({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sin(x): + return f"std::sin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cos(x): + return f"std::cos({x})" + + @staticmethod + def neg(x): + return f"decltype({x})(-{x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def exp(x): + # return f"Sleef_expf_u10({x})" + return f"std::exp({x})" + + @staticmethod + def exp2(x): + return f"std::exp2({x})" + + @staticmethod + def expm1(x): + return f"std::expm1({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def erf(x): + return f"std::erf({x})" + + @staticmethod + def erfc(x): + return f"std::erfc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def erfinv(x): + return f"calc_erfinv({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sqrt(x): + return f"std::sqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def rsqrt(x): + return f"1 / std::sqrt({x})" + + @staticmethod + def log1p(x): + bug = config.cpp.inject_log1p_bug_TESTING_ONLY + if bug == "accuracy": + return f"{x} + decltype({x})(1)" + elif bug is None: + return f"std::log1p({x})" + else: + raise AssertionError( + f"unrecognized config cpp.inject_log1p_bug_TESTING_ONLY = {bug!r}" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def tan(x): + return f"std::tan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tanh(x): + return f"std::tanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def signbit(x): + """ + On windows std::signbit only support float type. + Ref: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/signbit?view=msvc-170 + """ + return ( + f"std::signbit(static_cast({x}))" + if _IS_WINDOWS + else f"std::signbit({x})" + ) + + @staticmethod + def pow(a, b): + return f"std::pow({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def log(x): + return f"std::log({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def round(x): + return f"std::nearbyint({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def floor(x): + return f"std::floor({x})" + + @staticmethod + def floordiv(a, b): + # a and b are integer type + return f"floor_divide_integral({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def ceil(x): + return f"std::ceil({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def trunc(x): + return f"std::trunc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def truncdiv(a, b): + # a and b are integer type + return f"{a} / {b}" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmod(a, b): + return f"std::fmod({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def isinf(x): + return f"std::isinf({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def isnan(x): + return f"std::isnan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def lgamma(x): + return f"std::lgamma({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acos(x): + return f"std::acos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acosh(x): + return f"std::acosh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cosh(x): + return f"std::cosh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sinh(x): + return f"std::sinh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asin(x): + return f"std::asin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asinh(x): + return f"std::asinh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan2(x, y): + return f"std::atan2({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan(x): + return f"std::atan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atanh(x): + return f"std::atanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def copysign(x, y): + return f"std::copysign({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def frexp(x): + cache_keys = f"frexp({x})[0]", f"frexp({x})[1]" + if all(V.kernel.cse.try_get(cache_key) is not None for cache_key in cache_keys): + return tuple(V.kernel.cse.try_get(cache_key) for cache_key in cache_keys) + + code = BracesBuffer() + exponent = V.kernel.cse.newvar(dtype=torch.int32, shape=x.shape) + mantissa = V.kernel.cse.newvar(dtype=x.dtype, shape=x.shape) + code.writeline(f"int32_t {exponent};") + code.writeline(f"auto {mantissa} = std::frexp({x}, &{exponent});") + V.kernel.compute.splice(code) + cse_vars = (mantissa, exponent) + for cache_key, cse_var in zip(cache_keys, cse_vars): + V.kernel.cse.put(cache_key, cse_var) + return mantissa, exponent + + @staticmethod + # pyrefly: ignore [bad-override] + def hypot(x, y): + return f"std::hypot({x}, {y})" + + @staticmethod + def log10(x): + return f"std::log10({x})" + + @staticmethod + def log2(x): + return f"std::log2({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def ldexp(x, n): + return f"std::ldexp({x}, {n})" + + @staticmethod + # pyrefly: ignore [bad-override] + def nextafter(x, y): + return f"std::nextafter({x}, {y})" + + @staticmethod + def relu(x): + bug = config.cpp.inject_relu_bug_TESTING_ONLY + if bug == "compile_error": + return "compile error!" + elif bug == "runtime_error": + return f"{x}; throw 1" + elif bug == "accuracy": + return f"{x} + decltype({x})(1)" + elif bug is None: + return f"std::max({x}, decltype({x})(0))" + else: + raise AssertionError( + f"unrecognized config cpp.inject_relu_bug_TESTING_ONLY = {bug!r}" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def minimum(a, b): + return f"min_propagate_nan({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def maximum(a, b): + return f"max_propagate_nan({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmaximum(a, b): + return f"std::max({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def where(a, b, c): + return f"{a} ? {b} : {c}" + + @staticmethod + def mod(a, b): + return f"mod({a}, {b})" + + @staticmethod + def constant(val, dtype): + return value_to_cpp(val, DTYPE_TO_CPP[dtype]) + + @staticmethod + def index_expr(expr, dtype): + idx_str = cexpr(V.kernel.rename_indexing(expr)) + var = V.kernel.cse.generate( + V.kernel.compute, idx_str, bounds=get_bounds_index_expr(expr) + ) + return ops.to_dtype(var, dtype) + + @staticmethod + def value_expr(expr, dtype): + # C++ index_expr already emits the requested dtype, so value_expr has + # the same lowering here. + return CppOverrides.index_expr(expr, dtype) + + @staticmethod + def masked(mask, body, other): + code = BracesBuffer() + + # Write masked operation into a lambda + body_var = V.kernel.cse.newvar() + code.writeline(f"auto {body_var} = [&]") + with V.kernel.swap_buffers(code), code.indent(): + result = body() + code.writeline(f"return {result};") + code.writeline(";") + V.kernel.compute.splice(code) + + # Use the lambda's return type as the type of other + other_code = value_to_cpp(other, f"decltype({body_var}())") + return f"{mask} ? {body_var}() : {other_code}" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_and(a, b): + return f"{a} && {b}" + + @staticmethod + def logical_not(a): + return f"!{a}" + + @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"decltype({a})({a} & {b})" + + @staticmethod + def bitwise_not(a): + return f"decltype({a})(~{a})" + + @staticmethod + def bitwise_or(a, b): + return f"decltype({a})({a} | {b})" + + @staticmethod + def bitwise_xor(a, b): + return f"decltype({a})({a} ^ {b})" + + @staticmethod + def bitwise_left_shift(a, b): + code = BracesBuffer() + code.writeline("[&]()") + with code.indent(): + scalar_t = DTYPE_TO_CPP[a.dtype] + code.writeline( + f"constexpr decltype({b}) max_shift = sizeof({scalar_t}) * CHAR_BIT;" + ) + code.writeline( + f"if ((static_cast>({b}) < 0) || ({b} >= max_shift))" + ) + with code.indent(): + code.writeline(f"return decltype({a})(0);") + code.writeline( + f"return decltype({a})(static_cast>({a}) << {b});" + ) + code.writeline("()") + return code + + @staticmethod + def bitwise_right_shift(a, b): + code = BracesBuffer() + code.writeline("[&]()") + with code.indent(): + scalar_t = DTYPE_TO_CPP[a.dtype] + code.writeline( + f"constexpr decltype({b}) max_shift = sizeof({scalar_t}) * CHAR_BIT - std::is_signed_v<{scalar_t}>;" + ) + code.writeline( + f"if ((static_cast>({b}) < 0) || ({b} >= max_shift))" + ) + with code.indent(): + code.writeline(f"return decltype({a})({a} >> max_shift);") + code.writeline(f"return decltype({a})({a} >> {b});") + code.writeline("()") + return code + + @staticmethod + def rand(seed: sympy.Expr, offset: sympy.Expr): + return f"normalized_rand_cpu({seed}, {offset})" + + @staticmethod + def rand_eager( + seed: sympy.Expr, + base_offset: sympy.Expr, + threads_per_round: sympy.Expr, + tid: sympy.Expr, + vec: sympy.Expr, + ): + # NOTE: This is a codegen fallback used by the C++ backend for eager random. + # It is not intended to provide CPU parity; parity target is CUDA eager vs compiled. + # Keep this hook to satisfy codegen paths and CI. + return f"normalized_rand_cpu({seed}, {base_offset})" + + @staticmethod + def randn(seed: sympy.Expr, offset: sympy.Expr): + return f"randn_cpu({seed}, {offset})" + + @staticmethod + def randint64(seed: sympy.Expr, offset: sympy.Expr, low, high): + return f"randint64_cpu({seed}, {offset}, {low}, {high})" + + @staticmethod + def sigmoid(x): + return f"decltype({x})(1) / (decltype({x})(1) + std::exp(-{x}))" + + @staticmethod + # pyrefly: ignore [bad-override] + def sign(x): + code = BracesBuffer() + scalar_zero = f"decltype({x})(0)" + scalar_one = f"decltype({x})(1)" + code.writeline("[&]()") + with code.indent(): + code.writeline(f"auto left = {x} > 0 ? {scalar_one} : {scalar_zero};") + code.writeline(f"auto right = {x} < 0 ? {scalar_one} : {scalar_zero};") + code.writeline("return left - right;") + code.writeline("()") + return code + + def partial_accumulate( + self, + name: str, + reduction_type: str, + value: CSEVariable, + extra_meta: dict[str, Any], + ) -> None: + raise NotImplementedError + + +CppOverrides._initialize_pointwise_overrides("cpp") + + +class CppVecOverrides(CppOverrides): + """Map element-wise ops to aten vectorization C++""" + + def __new__(cls, *args, **kargs): + self = super().__new__(cls) + + def wrap(func): + # `CppVecKernel` generates both scalar ops and vector ops according to + # whether the inputs are scalars or vectors while all ops in `CppVecOverrides` + # (except for some ops explained below) assume the inputs are vectors. We wrap the ops in + # `CppVecOverrides` to broadcast scalar inputs to vectors if needed or fallback to + # `CppOverrides` when all inputs are scalars. + # + # Notes on ops handled separately in their own functions: + # `ops.masked`: + # needs recursive handling of masked body. + # `ops.index_expr`: + # needs to further analyze the dependency of the index expression on + # the tiling itervar. + def wrapper(*args, **kwargs): + scalars = [ + arg + for arg in args + if isinstance(arg, (int, sympy.Expr)) + or (isinstance(arg, CppCSEVariable) and not arg.is_vec) + ] + vectors = [ + arg + for arg in args + if isinstance(arg, CppCSEVariable) and arg.is_vec + ] + new_args = list(args) + if scalars and vectors: + new_args = [] + for arg in args: + if isinstance(arg, (int, sympy.Expr)): + if isinstance(arg, sympy.Expr) and not arg.is_number: + arg = ops.index_expr(arg, torch.int64) + else: + arg = ops.constant(arg, torch.int64) + arg = arg.value if isinstance(arg, OpsValue) else arg + new_args.append(arg) + + # DType Promotion + if vectors: + # We have saw several data type mismatch issues related with index_expr in + # the lowering phase of torch.int8. torch.int32, torch.int64. + # 1. int32 and int64 in test_torchinductor.py::test_max_pool2d_with_indices_backward3_cpu + # 2. int8 and int32 in test_torchinductor.py::test_max_pool2d5_cpu + # 3. int32 and fp32 in test_torchinductor_dynamic_shapes.py::test_avg_pool2d8_dynamic_shapes_cpu + if len(new_args) == 2: + new_args = promote_args(new_args) + elif func is CppVecOverrides.where: + new_args[1:] = promote_args(new_args[1:]) + + # Broadcast scalar args to vector + if scalars and vectors: + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError( + "expected isinstance(V.kernel, CppVecKernel)" + ) + new_args = [ + ( + V.kernel.broadcast(new_arg) + if ( + isinstance(new_arg, CppCSEVariable) + and not new_arg.is_vec + and func + not in [ + CppVecOverrides.rand, + CppVecOverrides.randn, + CppVecOverrides.randint64, + ] + ) + else new_arg + ) + for new_arg in new_args + ] + + if vectors: + return func(*new_args, **kwargs) + else: + # fallback to scalar ops + scalar_ops = super(CppVecOverrides, self) + scalar_func = getattr(scalar_ops, func.__name__) + if scalar_func is None: + raise AssertionError("expected scalar_func is not None") + return scalar_func(*args, **kwargs) + + return wrapper + + for name, method in vars(CppVecOverrides).items(): + if getattr(method, "__class__", None) is staticmethod and name not in [ + "masked", + "index_expr", + "value_expr", + ]: + setattr(self, name, wrap(method.__func__)) + + return self + + @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 truediv(a, b): + return f"{a} / {b}" + + @staticmethod + def abs(x): + if isinstance(x, CppCSEVariable) and x.dtype in ( + torch.uint8, + torch.uint16, + torch.uint32, + torch.uint64, + ): + # Unsigned identity bypass for vectorized path + return f"{x}" + return f"{x}.abs()" + + @staticmethod + def sin(x): + return f"{x}.sin()" + + @staticmethod + def cos(x): + return f"{x}.cos()" + + @staticmethod + def exp(x): + return f"{x}.exp()" + + @staticmethod + def exp2(x): + return f"{x}.exp2()" + + @staticmethod + def expm1(x): + return f"{x}.expm1()" + + @staticmethod + def erf(x): + return f"{x}.erf()" + + @staticmethod + def erfc(x): + return f"{x}.erfc()" + + @staticmethod + def erfinv(x): + return f"{x}.erfinv()" + + @staticmethod + def sqrt(x): + return f"{x}.sqrt()" + + @staticmethod + def eq(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} == {y})" + + @staticmethod + def ne(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype == torch.bool: + if y.dtype != torch.bool: + raise AssertionError("expected y.dtype == torch.bool") + x_cast, y_cast = unify_mask_base_type(V.kernel.compute, (x, y)) + return f"{x_cast} != {y_cast}" + else: + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} != {y})" + + @staticmethod + def lt(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} < {y})" + + @staticmethod + def gt(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} > {y})" + + @staticmethod + def le(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} <= {y})" + + @staticmethod + def ge(x, y): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + if x.dtype is None: + raise AssertionError("expected x.dtype is not None") + return f"{V.kernel._get_mask_type(x.dtype)}({x} >= {y})" + + @staticmethod + def and_(x, y): + return f"{x} & {y}" + + @staticmethod + def rsqrt(x): + return f"{x}.rsqrt()" + + @staticmethod + def pow(a, b): + return f"{a}.pow({b})" + + @staticmethod + def log(x): + return f"{x}.log()" + + @staticmethod + def round(x): + return f"{x}.round()" + + @staticmethod + def floor(x): + return f"{x}.floor()" + + @staticmethod + def ceil(x): + return f"{x}.ceil()" + + @staticmethod + def trunc(x): + return f"{x}.trunc()" + + @staticmethod + def fmod(a, b): + return f"{a}.fmod({b})" + + @staticmethod + def lgamma(x): + return f"{x}.lgamma()" + + @staticmethod + def logical_and(a, b): + a, b = may_unify_binary_op_mask_type(a, b) + return f"{a} & {b}" + + @staticmethod + def logical_not(a): + return f"~{a}" + + @staticmethod + def logical_or(a, b): + a, b = may_unify_binary_op_mask_type(a, b) + return f"{a} | {b}" + + @staticmethod + def logical_xor(a, b): + a, b = may_unify_binary_op_mask_type(a, b) + return f"{a} ^ {b}" + + @staticmethod + def bitwise_and(a, b): + a, b = may_unify_binary_op_mask_type(a, b) + return f"{a} & {b}" + + @staticmethod + def bitwise_not(a): + return f"~{a}" + + @staticmethod + def bitwise_or(a, b): + a, b = may_unify_binary_op_mask_type(a, b) + return f"{a} | {b}" + + @staticmethod + def bitwise_xor(a, b): + a, b = may_unify_binary_op_mask_type(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 load_seed(name, offset): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + return f"{V.kernel.load(name, offset)}" + + @staticmethod + def rand(seed, offset): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + code = BracesBuffer() + rand_function = ( + f"result[offset_idx] = normalized_rand_cpu({seed}, offset[offset_idx]);" + ) + return codegen_rand(offset, code, rand_function) + + @staticmethod + def randn(seed, offset): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + code = BracesBuffer() + rand_function = f"result[offset_idx] = randn_cpu({seed}, offset[offset_idx]);" + return codegen_rand(offset, code, rand_function) + + @staticmethod + def randint64(seed, offset, low, high): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + code = BracesBuffer() + rand_function = f"result[offset_idx] = randint64_cpu({seed}, offset[offset_idx], {low}, {high});" + return codegen_rand(offset, code, rand_function, torch.int64) + + @staticmethod + def remainder(a, b): + if a.dtype != b.dtype: + raise AssertionError( + "remainder vec implementation expect the same inputs' dtype." + ) + if is_integer_dtype(a.dtype): + # Doing blend to set the remaining bits of b to non-zero + _t = f"decltype({a})" + if V.kernel._get_raw_num_vectors(b.dtype) < 1: + b = f"{_t}::blend<{(1 << V.kernel.tiling_factor) - 1}>({_t}(1), {b})" + return f"remainder_integral({a}, {b})" + return f"{a} - ({CppVecOverrides.floordiv(a, b)}) * {b}" + + @staticmethod + def tan(a): + return f"{a}.tan()" + + @staticmethod + def tanh(a): + if config.cpp.use_decompose_tanh: + vec_one = f"decltype({a})(1)" + vec_two = f"decltype({a})(2)" + vec_minus_two = f"decltype({a})(-2)" + return ( + f"{vec_two} / ({vec_one} + ({vec_minus_two} * {a}).exp()) - {vec_one}" + ) + else: + return f"{a}.tanh()" + + @staticmethod + def reciprocal(a): + return f"{a}.reciprocal()" + + @staticmethod + def atan(x): + return f"{x}.atan()" + + @staticmethod + def acos(x): + return f"{x}.acos()" + + @staticmethod + def asin(x): + return f"{x}.asin()" + + @staticmethod + def cosh(x): + return f"{x}.cosh()" + + @staticmethod + def sinh(x): + return f"{x}.sinh()" + + @staticmethod + def log10(x): + return f"{x}.log10()" + + @staticmethod + def log2(x): + return f"{x}.log2()" + + @staticmethod + def nextafter(x, y): + return f"{x}.nextafter({y})" + + @staticmethod + def copysign(a, b): + return f"{a}.copysign({b})" + + @staticmethod + def atan2(a, b): + return f"{a}.atan2({b})" + + @staticmethod + def hypot(a, b): + return f"{a}.hypot({b})" + + @staticmethod + def atanh(x): + # For real x, atanh(x) = 1/2 * log((1+x)/(1-x)) + vec_one = f"decltype({x})(1)" + vec_one_half = f"decltype({x})(0.5)" + return f"{vec_one_half} * (({vec_one} + {x})/({vec_one} - {x})).log()" + + @staticmethod + def asinh(x): + vec_t = f"decltype({x})" + code = BracesBuffer() + code.writeline("[&]()") + with code.indent(): + # Avoid Vectorized::asinh/SLEEF here: it overflows internally for + # large finite fp32 inputs where eager std::asinh remains finite. + # This is asinh(x) = sign(x) * log(abs(x) + sqrt(abs(x)^2 + 1)), + # rewritten with 1 / abs(x) to avoid squaring large values. + code.writeline(f"auto abs_x = {x}.abs();") + code.writeline(f"auto one = {vec_t}(1);") + code.writeline("auto inv_abs_x = one / abs_x;") + code.writeline( + "auto correction = " + "(one / (one + inv_abs_x)) / " + "((one + inv_abs_x * inv_abs_x).sqrt() + inv_abs_x);" + ) + code.writeline("auto result = abs_x.log1p() + correction.log1p();") + code.writeline(f"return result.copysign({x});") + code.writeline("()") + return code + + @staticmethod + def acosh(x): + return f"{x}.acosh()" + + @staticmethod + def relu(x): + bug = config.cpp.inject_relu_bug_TESTING_ONLY + if bug == "compile_error": + return "compile error!" + elif bug == "runtime_error": + return f"{x}; throw 1" + elif bug == "accuracy": + return f"{x} + decltype({x})(1)" + elif bug is None: + return f"at::vec::clamp_min({x}, decltype({x})(0))" + else: + raise AssertionError( + f"unrecognized config cpp.inject_relu_bug_TESTING_ONLY = {bug!r}" + ) + + # TODO: this seems to be dead + @staticmethod + def sigmoid(x): + return f"decltype({x})(1)/(decltype({x})(1) + {x}.neg().exp())" + + @staticmethod + def neg(x): + return f"{x}.neg()" + + @staticmethod + def floordiv(a, b): + if is_float_dtype(a.dtype): + if a.dtype != b.dtype: + raise AssertionError( + "div_floor_floating_vec implementation expect the same inputs' dtype." + ) + return f"div_floor_floating_vec({a}, {b})" + else: + if not (all(is_integer_dtype(item.dtype) for item in [a, b])): + raise AssertionError( + "expected all(is_integer_dtype(item.dtype) for item in [a, b])" + ) + # a and b are integer type + _t = f"decltype({b})" + b = f"{_t}::set({_t}(1), {b}, {cexpr_index(V.kernel.num_elems)})" + return f"floor_divide_integral({a}, {b})" + + @staticmethod + def truncdiv(a, b): + # a and b are integer type + _t = f"decltype({b})" + b = f"{_t}::set({_t}(1), {b}, {cexpr_index(V.kernel.num_elems)})" + return f"{a} / {b}" + + @staticmethod + def minimum(a, b): + if a.dtype == torch.bool: + if b.dtype != torch.bool: + raise AssertionError("expected b.dtype == torch.bool") + a_cast, b_cast = unify_mask_base_type(V.kernel.compute, (a, b)) + return f"{a_cast} & {b_cast}" + else: + return f"at::vec::minimum({a}, {b})" + + @staticmethod + def maximum(a, b): + if a.dtype == torch.bool: + if b.dtype != torch.bool: + raise AssertionError("expected b.dtype == torch.bool") + a_cast, b_cast = unify_mask_base_type(V.kernel.compute, (a, b)) + return f"{a_cast} | {b_cast}" + else: + return f"at::vec::maximum({a}, {b})" + + @staticmethod + def fmaximum(a, b): + return f"decltype({a})::blendv({a}, {b}, {a} < {b})" + + @staticmethod + def square(a): + return f"{a} * {a}" + + @staticmethod + def where(a, b, c): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + if b.dtype == torch.bool: + if c.dtype != torch.bool: + raise AssertionError("expected c.dtype == torch.bool") + blendv_a, blendv_b, blendv_c = unify_mask_base_type( + V.kernel.compute, (a, b, c) + ) + return f"decltype({blendv_b})::blendv({blendv_c}, {blendv_b}, {blendv_a})" + else: + return f"decltype({b})::blendv({c}, {b}, {V.kernel._get_mask_cast(a, b.dtype)})" + + @staticmethod + def sign(x): + code = BracesBuffer() + vec_zero = f"decltype({x})(0)" + vec_one = f"decltype({x})(1)" + blendv_l = f"decltype({x})::blendv({vec_zero}, {vec_one}, {vec_zero} < {x})" + blendv_r = f"decltype({x})::blendv({vec_zero}, {vec_one}, {x} < {vec_zero})" + code.writeline("[&]()") + with code.indent(): + code.writeline(f"auto left = {blendv_l};") + code.writeline(f"auto right = {blendv_r};") + code.writeline("return left - right;") + code.writeline("()") + return code + + @staticmethod + def to_dtype(x, dtype, src_dtype=None, use_compute_types=True): + if dtype not in [ + torch.bool, + torch.float64, + torch.float, + torch.bfloat16, + torch.float16, + torch.uint8, + torch.int8, + torch.int32, + torch.int64, + torch.float8_e4m3fn, + torch.float8_e5m2, + ]: + raise AssertionError(f"{__name__} does not support {dtype}") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + src_dtype = x.dtype + expr = V.kernel.get_to_dtype_expr(x, dtype, src_dtype) + csevar = V.kernel.cse.generate(V.kernel.compute, expr) + csevar.update_on_args("to_dtype", (x, dtype), {"src_dtype": src_dtype}) + if ( + use_compute_types + and dtype in DTYPE_LOWP_FP + and src_dtype == torch.float + and not config.emulate_precision_casts + ): + V.kernel.cache_dtype_convert(x, src_dtype, csevar, dtype) + return csevar + + @staticmethod + def round_to_int(x, dtype, src_dtype=None, use_compute_types=True): + if dtype not in [ + torch.uint8, + torch.int8, + torch.int32, + ]: + raise AssertionError(f"{__name__} does not support {dtype}") + if not isinstance(x, CppCSEVariable): + raise AssertionError("expected isinstance(x, CppCSEVariable)") + src_dtype = x.dtype + expr = V.kernel.get_to_dtype_expr(x, dtype, src_dtype, rounding=True) + csevar = V.kernel.cse.generate(V.kernel.compute, expr) + csevar.update_on_args("round_to_int", (x, dtype), {"src_dtype": src_dtype}) + if ( + dtype in DTYPE_LOWP_FP + and src_dtype == torch.float + and not config.emulate_precision_casts + ): + V.kernel.cache_dtype_convert(x, src_dtype, csevar, dtype) + return csevar + + @staticmethod + def log1p(x): + bug = config.cpp.inject_log1p_bug_TESTING_ONLY + if bug == "accuracy": + return f"{x} + decltype({x})(1)" + elif bug is None: + return f"{x}.log1p()" + else: + raise AssertionError( + f"unrecognized config cpp.inject_log1p_bug_TESTING_ONLY = {bug!r}" + ) + + @staticmethod + def masked(mask, body, other): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + code = BracesBuffer() + var = V.kernel.cse.newvar() + with V.kernel.masked(mask) as new_mask: + code.writeline(f"auto {var} = [&]") + with V.kernel.swap_buffers(code), code.indent(): + result = body() + code.writeline(f"return {result};") + code.writeline(";") + V.kernel.compute.splice(code) + + dtype = result.dtype + body_code = f"{var}()" + + def maskify_or_vecify(code): + return ( + f"{V.kernel._get_mask_type()}::from({code})" + if dtype == torch.bool + else f"{V.kernel._get_vec_type(dtype)}({code})" + ) + + if result.is_vec: + body_code_vec = body_code + else: + body_code_vec = maskify_or_vecify(body_code) + other_code = value_to_cpp(other, DTYPE_TO_CPP[dtype]) + # loading bool as VecMask + other_code_vec = maskify_or_vecify(other_code) + if not isinstance(new_mask, CppCSEVariable): + raise AssertionError(new_mask) + if new_mask.is_vec: + code = BracesBuffer() + code.writeline("[&]") + with V.kernel.swap_buffers(code), code.indent(): + code.writeline(f"if ({new_mask}.all_zero())") + with code.indent(): + code.writeline(f"return {other_code_vec};") + code.writeline("else") + with code.indent(): + # Create cse variable to reuse kernel.overrides.where + body_vec_var = V.kernel.cse.generate( + V.kernel.compute, + body_code_vec, + ) + other_vec_var = V.kernel.cse.generate( + V.kernel.compute, + other_code_vec, + ) + if not isinstance(body_vec_var, CppCSEVariable): + raise AssertionError(body_vec_var) + if not isinstance(other_vec_var, CppCSEVariable): + raise AssertionError(other_vec_var) + body_vec_var.dtype = dtype + other_vec_var.dtype = dtype + overrides: type[CppOverrides | CppVecOverrides] = ( + # pyrefly: ignore [bad-assignment] + V.kernel.overrides + ) # type: ignore[has-type] + code.writeline( + f"return {overrides.where(new_mask, body_vec_var, other_vec_var)};" + ) + code.writeline("()") + csevar = V.kernel.cse.generate( + V.kernel.compute, + code, + ) + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + csevar.is_vec = True + elif result.is_vec: + csevar = V.kernel.cse.generate( + V.kernel.compute, f"{mask} ? {body_code_vec} : {other_code_vec}" + ) + else: + csevar = V.kernel.cse.generate( + V.kernel.compute, f"{mask} ? {body_code} : {other_code}" + ) + # `result` is explicitly added to the args for correct propagation + # of relevant itervars and vectorization status. + csevar.update_on_args("masked", (mask, body, other, result), {}) + return csevar + + @staticmethod + def index_expr(expr, dtype): + if not isinstance(V.kernel, CppVecKernel): + raise AssertionError("expected isinstance(V.kernel, CppVecKernel)") + index = V.kernel.rename_indexing(expr) + tiling_var = V.kernel.itervars[V.kernel.tiling_idx] + stride = V.kernel._try_get_const_stride(index, tiling_var) + if stride == 0: + return CppOverrides.index_expr(expr, dtype) + elif stride is not None: + idx = V.kernel.cse.generate( + V.kernel.compute, cexpr(index), bounds=get_bounds_index_expr(expr) + ) + value = ops.to_dtype(idx, dtype) + if isinstance(value, OpsValue): + value = value.value + csevar = V.kernel.arange(value, stride) + else: + csevar = V.kernel._load_or_store_non_contiguous( # type: ignore[assignment] + None, index, dtype, V.kernel.compute + ) + # pyrefly: ignore [missing-attribute] + csevar.update_on_args("index_expr", (expr, dtype), {}) + return csevar + + @staticmethod + def value_expr(expr, dtype): + # C++ index_expr already emits the requested dtype, so value_expr has + # the same lowering here. + return CppVecOverrides.index_expr(expr, dtype) + + @staticmethod + def frexp(x): + cache_keys = f"frexp({x})[0]", f"frexp({x})[1]" + if all(V.kernel.cse.try_get(cache_key) is not None for cache_key in cache_keys): + return tuple(V.kernel.cse.try_get(cache_key) for cache_key in cache_keys) + + cdtype = DTYPE_TO_CPP[x.dtype] + size = V.kernel.tail_size if V.kernel.tail_size else V.kernel.tiling_factor + code = BracesBuffer() + exponent = V.kernel.cse.newvar(dtype=torch.int32) + mantissa = V.kernel.cse.newvar(dtype=x.dtype) + exponent.update_on_args("frexp", (x,), kwargs={}) + mantissa.update_on_args("frexp", (x,), kwargs={}) + n_vec = V.kernel._get_num_vectors(x.dtype) + mantissa_t = ( + f"at::vec::Vectorized<{cdtype}>" + if n_vec == 1 + else f"at::vec::VectorizedN<{cdtype}, {n_vec}>" + ) + code.writeline( + f"at::vec::Vectorized {exponent};" + if n_vec == 1 + else f"at::vec::VectorizedN {exponent};" + ) + code.writeline(f"{mantissa_t} {mantissa};") + code.writeline("[&]()") + with code.indent(): + code.writeline( + f"__at_align__ std::array<{cdtype}, {V.kernel.tiling_factor}> tmpbuf;" + ) + code.writeline(f"{x}.store(tmpbuf.data(), {cexpr_index(size)});") + code.writeline( + f"__at_align__ std::array tmpbuf_exponent;" + ) + code.writeline( + f"__at_align__ std::array<{cdtype}, {V.kernel.tiling_factor}> tmpbuf_mantissa;" + ) + code.writeline(f"for (int i = 0; i < {cexpr_index(size)}; i++)") + with code.indent(): + code.writeline( + "tmpbuf_mantissa[i] = std::frexp(tmpbuf[i], &tmpbuf_exponent[i]);" + ) + code.writeline( + f"{exponent} = at::vec::Vectorized::loadu(tmpbuf_exponent.data(), {cexpr_index(size)});" + if n_vec == 1 + else f"{exponent} = at::vec::VectorizedN::loadu(tmpbuf_exponent.data(), {cexpr_index(size)});" + ) + code.writeline( + f"{mantissa} = {mantissa_t}::loadu(tmpbuf_mantissa.data(), {cexpr_index(size)});" + ) + code.writeline("();") + V.kernel.compute.splice(code) + cse_vars = (mantissa, exponent) + for cache_key, cse_var in zip(cache_keys, cse_vars): + V.kernel.cse.put(cache_key, cse_var) + return mantissa, exponent + + @classmethod + def _scalarize(cls, scalar_func): + def inner(*args, **kwargs): + if kwargs: + raise AssertionError("expected not kwargs") + kernel = V.kernel + if not isinstance(kernel, CppVecKernel): + raise AssertionError("expected isinstance(kernel, CppVecKernel)") + code = BracesBuffer() + code.writeline("[&]()") + vec_dtype = args[0].dtype + n_vec = kernel._get_num_vectors(vec_dtype) + size = kernel.tail_size if kernel.tail_size else kernel.tiling_factor + scalar_args = [] + cdtype = DTYPE_TO_CPP[vec_dtype] + output_mask = scalar_func.__name__ in ( + "isinf", + "isnan", + "signbit", + ) + octype = "bool" if output_mask else cdtype + octype = ( + DTYPE_TO_CPP[args[-2]] + if (scalar_func.__name__ == "to_dtype_bitcast") + else octype + ) + with code.indent(): + for argidx, arg in enumerate(args): + if isinstance(arg, CppCSEVariable): + if not arg.is_vec: + raise AssertionError("expected arg.is_vec") + if arg.dtype != vec_dtype: + raise AssertionError("expected arg.dtype == vec_dtype") + code.writeline( + f"__at_align__ std::array<{cdtype}, {kernel.tiling_factor}> tmpbuf{argidx};" + ) + code.writeline( + f"{arg}.store(tmpbuf{argidx}.data(), {cexpr_index(size)});" + ) + scalar_args.append(f"tmpbuf{argidx}[i]") + else: + scalar_args.append(arg) + code.writeline( + f"__at_align__ std::array<{octype}, {kernel.tiling_factor}> tmpbuf_out;" + ) + res = scalar_func(*scalar_args) + code.writeline(f"for (int i = 0; i < {cexpr_index(size)}; i++)") + with code.indent(): + code.writeline(f"tmpbuf_out[i] = {res};") + load_args = f"tmpbuf_out.data(), {cexpr_index(size)}" + if output_mask: + load_fn = f"at::vec::VecMask<{cdtype},{n_vec}>::from" + elif n_vec == 1: + load_fn = f"at::vec::Vectorized<{octype}>::loadu" + else: + load_fn = f" at::vec::VectorizedN<{octype}, {n_vec}>::loadu" + code.writeline(f"return {load_fn}({load_args});") + code.writeline("()") + return code + + return inner + + @classmethod + def _initialize_scalarize(cls): + vec_vars = vars(CppVecOverrides) + for name, method in vars(CppOverrides).items(): + if isinstance(method, staticmethod) and name not in vec_vars: + func = cls._scalarize(method.__func__) + func.__name__ = name + setattr(cls, name, staticmethod(func)) + + +CppVecOverrides._initialize_pointwise_overrides("cppvec") +CppVecOverrides._initialize_scalarize() + + +class CppTile2DOverrides(CppVecOverrides): + @staticmethod + def index_expr(expr, dtype): + if not isinstance(V.kernel, CppTile2DKernel): + raise AssertionError("expected isinstance(V.kernel, CppTile2DKernel)") + expr = V.kernel.transform_indexing(expr) + return CppVecOverrides.index_expr(expr, dtype) + + @staticmethod + def value_expr(expr, dtype): + # C++ index_expr already emits the requested dtype, so value_expr has + # the same lowering here. + return CppTile2DOverrides.index_expr(expr, dtype) + + +class CppKernel(Kernel): + """ + Base class for C++ kernel code generation in PyTorch Inductor. + This class is responsible for generating C++ code from the intermediate representation. + + Args: + args: Kernel arguments used for code generation + num_threads: Number of threads for parallel execution + """ + + overrides = CppOverrides # type: ignore[assignment] + sexpr = cexpr + newvar_prefix = "auto " + suffix = ";" + + def __init__(self, args, num_threads): + super().__init__(args) + # Indicate when this kernel is active, for example + # {x0, {24, 26}} -> this kernel is active when x0 >= 24 and x0 < 26 + self.active_ranges: dict[sympy.Expr, tuple[sympy.Expr, ...]] = {} + # Indicate this kernel will be moved under the inner for-loop + # See move_code_under_inner_loop + self.inner_itervars: list[sympy.Symbol] = [] + self.call_ranges: tuple[sympy.Expr, ...] | None = None + self.ranges: list[sympy.Expr] = [] + self.itervars: list[sympy.Symbol] = [] + self.reduction_depth = None + self.reduction_prefix = IndentedBuffer() + # We need this because when we run "reduction" nodes here, we lack + # "loop" information to decide whether we need a scalar init or an array init + # in the reduction prefix. Meanwhile, we have other information like + # reduction types and dtype to generate the reduction prefix. We record the information + # with a callable lambda function, and when we have enough information to finalize + # the reduction prefix, we can invoke the functions here with additional information. + self.reduction_prefix_generators: list[Callable] = [] # type: ignore[type-arg] + self.reduction_suffix = IndentedBuffer() + self.parallel_reduction_prefix = IndentedBuffer() + self.parallel_reduction_suffix = IndentedBuffer() + self.local_reduction_init = IndentedBuffer() + self.local_reduction_stores = IndentedBuffer() + self.is_reduction = False + self.non_parallel_reduction_prefix = IndentedBuffer() + self.non_parallel_reduction_suffix = IndentedBuffer() + self.reduction_cse = CSE(self.newvar_prefix, self.suffix, name_prefix="tmp_acc") + self.welford_helper_cse = CSE( + self.newvar_prefix, self.suffix, name_prefix="welford_helper" + ) + self.cascade_helper_cse = CSE( + self.newvar_prefix, self.suffix, name_prefix="cascade_helper" + ) + self.preloads = IndentedBuffer() + self.poststores = IndentedBuffer() + self.num_threads = num_threads # num_threads the kernel specialized for + self.reduction_omp_dec: dict[tuple[str, str], str] = {} + self.reduction_var_names: list[str] = [] + + def _gen_parallel_reduction_buffers( + self, + acc, + acc_type, + reduction_type, + dtype, + reduction_combine_fn=reduction_combine, + reduction_init_fn=reduction_init, + ): + if config.cpp.dynamic_threads and not self.parallel_reduction_prefix: + self.parallel_reduction_prefix.writeline( + "int max_threads = omp_get_max_threads();" + ) + acc_local = f"{acc}_local" + num_threads = ( + "max_threads" if config.cpp.dynamic_threads else parallel_num_threads() + ) + acc_local_in_array = f"{acc}_arr[tid]" + self.local_reduction_init.writeline( + f"{acc_type} {acc_local} = {reduction_init_fn(reduction_type, dtype)};" + ) + self.parallel_reduction_prefix.splice( + reduction_prefix_array( + acc, + acc_type, + reduction_type, + dtype, + num_threads, + reduction_init_fn, + ) + ) + self.local_reduction_stores.writeline(f"{acc_local_in_array} = {acc_local};") + self.parallel_reduction_suffix.writelines( + [ + f"for (int tid = 0; tid < {num_threads}; tid++)", + "{", + f" {acc} = {reduction_combine_fn(reduction_type, acc, acc_local_in_array, src_dtype=dtype)};", + "}", + ], + ) + + def update_stores_with_parallel_reduction(self): + for var_name in self.reduction_var_names: + replace_acc_name(self.stores, var_name, f"{var_name}_local") + + def gen_body(self, code: BracesBuffer | None = None): + if code is not None: + raise AssertionError("expected code is None") + code = BracesBuffer() + with contextlib.ExitStack() as stack: + if hasattr(self, "codegen_inner_loops"): + code.splice(self.preloads) + self.codegen_inner_loops(code) + stack.enter_context(code.indent()) + code.splice(self.loads) + code.splice(self.compute) + code.splice(self.stores) + if hasattr(self, "codegen_inner_loops"): + code.splice(self.poststores) + + if self.inner_itervars: + for idx in self.inner_itervars: + start, end = self.active_ranges[idx] + code = move_code_under_inner_loop(code, idx, f"{idx}_tail", start, end) + return code + + @contextlib.contextmanager + def masked(self, mask): + """Context manager to add an additional mask to loads and stores.""" + prior = self._load_mask + if prior: + mask = ops.and_(mask, prior) + if isinstance(mask, OpsValue): + mask = mask.value + if not isinstance(mask, CppCSEVariable): + raise AssertionError("expected isinstance(mask, CppCSEVariable)") + # see NOTE [dtype of CppCSEVariable] + # mask's dtype should be bool + mask.dtype = torch.bool + + self._load_mask = mask + try: + yield mask + finally: + self._load_mask = prior + + def scale_index_with_offset( + self, index: sympy.Expr, scale=1, itervar_idx=-1, offset=0 + ): + var = self.itervars[itervar_idx] + replacement = {var: var * scale + offset} + new_index = sympy_subs(index, replacement) + return new_index + + def index_to_str(self, index: sympy.Expr) -> str: + """ + Convert an index expr to a string that can be used in cpp code. + e.g. a sympy expression "s2" may actually appear as "ks1" in the cpp kernel. + """ + return cexpr(self.rename_indexing(index)) + + def index_indirect_depends_on(self, index: sympy.Expr, itervar: sympy.Symbol): + """ + Check if an index has free symbol CppCSEVariable that depends on `itervar`. + """ + return any( + self.cse.varname_map[s.name].depends_on(itervar) # type: ignore[attr-defined] + for s in index.free_symbols + if s.name in self.cse.varname_map # type: ignore[attr-defined] + and isinstance(self.cse.varname_map[s.name], CppCSEVariable) # type: ignore[attr-defined] + ) + + def index_depends_on(self, index: sympy.Expr, itervar: sympy.Symbol): + return itervar in index.free_symbols or self.index_indirect_depends_on( + index, itervar + ) + + def var_ranges(self): + return dict(zip(self.itervars, self.ranges)) + + def check_bounds( + self, + expr: sympy.Expr, + size: sympy.Expr, + lower: bool, + upper: bool, + ): + if not (lower or upper): + return + + indirect = free_symbol_is_type(expr, SymT.TMP) + if indirect: + # indexing in compute + csevar = ops.index_expr(expr, torch.int64).value + buffer = V.kernel.compute + else: + # Prefer to put the assert in loads so it runs before the actual + # memory access. However, if the index expression may have already + # been CSE'd into compute by a prior ops.index_expr call, placing a + # reference to it in loads would be a forward reference (loads are + # emitted before compute in the kernel body). In that case fall + # back to compute. + idx_str = cexpr(self.rename_indexing(expr)) + if self.cse.try_get(idx_str) is not None: + csevar = ops.index_expr(expr, torch.int64).value + buffer = V.kernel.compute + else: + prior_compute = V.kernel.compute + try: + V.kernel.compute = self.loads + csevar = ops.index_expr(expr, torch.int64).value + finally: + V.kernel.compute = prior_compute + buffer = self.loads + + size_str = V.kernel.sexpr(self.rename_indexing(size)) if upper else None + + line = self.indirect_assert( + csevar, "0" if lower else None, size_str, self._load_mask + ) + self.cse.generate(buffer, line, assignment=False) + + def load(self, name: str, index: sympy.Expr): + var = self.args.input(name) + index = self.rename_indexing(index) + line = f"{var}[{cexpr_index(index)}]" + csevar = self.cse.generate(self.loads, line, dtype=V.graph.get_dtype(name)) + csevar.update_on_args("load", (self, name, index), {}) + return csevar + + def _use_parallel_atomic_add(self): + return config.cpp.dynamic_threads or self.num_threads != 1 + + def store(self, name, index, value, mode=None): + if "buf" not in name: + raise AssertionError('expected "buf" in name') + var = self.args.output(name) + index = self.rename_indexing(index) + if mode is None: + line = f"{var}[{cexpr_index(index)}] = {value};" + elif mode == "atomic_add": + if not self._use_parallel_atomic_add(): + line = f"{var}[{cexpr_index(index)}] += {value};" + else: + dtype = V.graph.get_dtype(name) + # mirroring static_cast(...) in load: + value = f"static_cast<{DTYPE_TO_CPP[dtype]}>({value})" + line = f"atomic_add(&{var}[{cexpr_index(index)}], {value});" + else: + raise NotImplementedError(f"store mode={mode}") + self.stores.writeline(DeferredLine(name, line)) + + def device_assert_async(self, cond, msg): + self.compute.writeline( + f'({cond} ? 0 : (throw std::runtime_error("{msg}"), 0));' + ) + + def _gen_reduction_prefix( + self, + acc: CSEVariable | str, + acc_type: str, + rtype: str, + dtype: torch.dtype, + init_fn, + ): + # Generate reduction prefix + # If size is None, we will define and initialize a single reduction variable + # => float tmp_acc0 = 0; + # Otherwise, we will define and initialize a reduction array + # => float tmp_acc0_arr[size]; + # => for (int i = 0; i < size; i++) tmp_acc0_arr[i] = 0; + def inner(size: int | None = None): + if size is None: + return f"{acc_type} {acc} = {init_fn(rtype, dtype)};" + else: + return reduction_prefix_array( + acc, + acc_type, + rtype, + dtype, + size, + init_fn, + ) + + return inner + + def finalize_reduction_prefix(self, size: int | None = None): + for gen_fn in self.reduction_prefix_generators: + self.reduction_prefix.splice(gen_fn(size)) + + def need_use_acc_helper(self, reduction_type, dtype, use_scalar): + # Check if we need accumulate helper for the reduction operation. + # using accumulate helper generates the necessary code to improve precision for + # sum and welford + # Note: using helper has non-negligible impact on performance + + if reduction_type == "welford_reduce": + return True + + # TODO add supports for more data types when needed + if reduction_type == "sum" and dtype == torch.float: + if self.call_ranges is None: + raise AssertionError("expected self.call_ranges is not None") + reduction_size = functools.reduce( + operator.mul, self.call_ranges[self.reduction_depth :] + ) + + # chunk size to balance accuracy and performance + chunk_size = 4096 + + return V.graph.sizevars.guard_or_false(sympy.Gt(reduction_size, chunk_size)) + return False + + def _acc_helper_init( + self, + reduction_type, + helper_val, + helper_range, + dtype, + num_threads=None, + use_scalar=False, + ): + num_range_thread = ( + CeilDiv(helper_range, num_threads) if num_threads else helper_range + ) + num_range_thread_expr = cexpr_index(num_range_thread) + if reduction_type not in ["welford_reduce", "sum"]: + raise AssertionError('expected reduction_type in ["welford_reduce", "sum"]') + chunk_size = 4096 + num_chunks = CeilDiv(num_range_thread, chunk_size) + helper_type = ( + "WelfordHelper" + if reduction_type == "welford_reduce" + else "CascadeSumHelper" + ) + if use_scalar: + h_type = DTYPE_TO_CPP[dtype] + else: + h_type = ( + self._get_vec_type(dtype) + if hasattr(self, "_get_vec_type") + else DTYPE_TO_CPP[dtype] + ) + helper_init_line = ( + f"{helper_type}<{h_type}, {chunk_size}> {helper_val}" + f"(" + f"{num_range_thread_expr}" + f");" + ) + if reduction_type == "sum": + return helper_init_line + if isinstance(num_chunks, sympy.Integer) and num_chunks <= 1: + # When the number of chunks <= 1, there is no need to use cascade summation to improve + # reduction accuracy. We can initialize a static WelfordHelper to improve performance. + return f"static {helper_init_line}" + else: + return helper_init_line + + def _use_acc_helper( + self, reduction_type, acc, helper_val, helper_range, dtype, use_scalar=False + ): + num_threads = ( + "max_threads" if config.cpp.dynamic_threads else parallel_num_threads() + ) + self.non_parallel_reduction_prefix.writeline( + self._acc_helper_init( + reduction_type, helper_val, helper_range, dtype, None, use_scalar + ) + ) + self.local_reduction_init.writeline( + self._acc_helper_init( + reduction_type, helper_val, helper_range, dtype, num_threads, use_scalar + ) + ) + result = acc if use_scalar else f"{acc}_vec" + if reduction_type == "welford_reduce": + self.non_parallel_reduction_suffix.writeline( + f"{result} = welford_combine({result}, &{helper_val});" + ) + self.local_reduction_stores.writeline( + f"{result}_local = welford_combine({result}_local, &{helper_val});" + ) + else: + self.non_parallel_reduction_suffix.writeline( + f"{result} = cascade_sum_final(&{helper_val});" + ) + self.local_reduction_stores.writeline( + f"{result}_local = cascade_sum_final(&{helper_val});" + ) + + def reduction(self, dtype, src_dtype, reduction_type, value): + argmax_or_argmin = reduction_type in ("argmax", "argmin") + logical_index = None + if argmax_or_argmin and isinstance(value, tuple): + value, logical_index = value + + if logical_index is not None: + logical_index_key = cast(CSEVariable, logical_index) + reduction_key = src_dtype, reduction_type, (value, logical_index_key) + else: + reduction_key = src_dtype, reduction_type, value + if reduction_key in self.reduction_cse.reduction_cache: + return self.reduction_cse.reduction_cache[reduction_key] + + acc = self.reduction_cse.generate( + self.loads, f"reduction {reduction_key}", write=False + ) + self.reduction_var_names.append(f"{acc}") + self.is_reduction = True + init_dtype = src_dtype if argmax_or_argmin else dtype + acc_type = reduction_acc_type(reduction_type, init_dtype) + self.reduction_prefix_generators.append( + self._gen_reduction_prefix( + acc, acc_type, reduction_type, init_dtype, reduction_init + ) + ) + + if self.need_use_acc_helper(reduction_type, dtype, True): + # use cascade_helper for vec kernel + reduction_size = functools.reduce( + operator.mul, self.ranges[self.reduction_depth :] + ) + # use welford_helper/cascade_helper for vec kernel + if reduction_type == "welford_reduce": + helper_val = self.welford_helper_cse.generate( + self.compute, f"reduction {reduction_key}", write=False + ) + else: + helper_val = self.cascade_helper_cse.generate( + self.compute, f"reduction {reduction_key}", write=False + ) + # rename the helper variable to distinguish it from vectorized version + scalar_helper_val = f"scalar_{helper_val}" + self._use_acc_helper( + reduction_type, + acc, + scalar_helper_val, + reduction_size, + dtype, + use_scalar=True, + ) + self.stores.writeline( + f"{acc} = {reduction_combine(reduction_type, acc, value, scalar_helper_val)};" + ) + else: + if logical_index is not None: + index = logical_index + else: + if self.reduction_depth is None: + raise AssertionError("expected self.reduction_depth is not None") + index = self.itervars[self.reduction_depth] + for i in range(self.reduction_depth + 1, len(self.itervars)): + index = index * self.ranges[i] + self.itervars[i] + self.stores.writeline( + f"{acc} = {reduction_combine(reduction_type, acc, value, index=index)};" + ) + + self._gen_parallel_reduction_buffers(acc, acc_type, reduction_type, init_dtype) + result = reduction_project(reduction_type, acc) + self.reduction_cse.reduction_cache[reduction_key] = result + return result + + def store_reduction(self, name, index, value): + index = self.rename_indexing(index) + var = self.args.output(name) + self.reduction_suffix.writeline( + DeferredLine(name, f"{var}[{cexpr_index(index)}] = {value};") + ) + + def set_ranges(self, lengths, reduction_lengths): + if self.call_ranges: + if self.call_ranges != tuple(lengths) + tuple(reduction_lengths): + raise AssertionError( + f"{self.call_ranges} == {tuple(lengths)} + {tuple(reduction_lengths)}" + ) + if self.reduction_depth != len(lengths): + raise AssertionError("expected self.reduction_depth == len(lengths)") + else: + self.call_ranges = tuple(lengths) + tuple(reduction_lengths) + self.ranges = [self.rename_indexing(x) for x in self.call_ranges] + self.itervars = [ + sympy_index_symbol_with_prefix(SymT.XBLOCK, n) + for n in range(len(self.ranges)) + ] + # pyrefly: ignore [bad-assignment] + self.reduction_depth = len(lengths) + return ( + self.itervars[: self.reduction_depth], + self.itervars[self.reduction_depth :], + ) + + def size_hint(self): + if self.call_ranges is None: + raise AssertionError("expected self.call_ranges is not None") + expr = sympy_product(self.call_ranges) + return V.graph.sizevars.optimization_hint(expr) + + def codegen_loops_impl(self, loop_nest, code, worksharing): + if not isinstance(self, CppKernelProxy): + raise AssertionError("expected isinstance(self, CppKernelProxy)") + threads = parallel_num_threads() + if self.call_ranges is None: + raise AssertionError("expected self.call_ranges is not None") + if isinstance(loop_nest.kernel, OuterLoopFusedKernel): + par_depth = loop_nest.kernel.decide_parallel_depth( + loop_nest.max_parallel_depth(), threads + ) + else: + par_depth = self.decide_parallel_depth( + loop_nest.max_parallel_depth(), threads + ) + + is_reduction_loop = ( + loop_nest.loops is not None + and loop_nest.loops[par_depth.start_depth].is_reduction + ) + with contextlib.ExitStack() as stack: + if par_depth.parallel_depth: + if is_reduction_loop: + # need to close the worksharing scope to define reduction vars outside it + worksharing.close() + else: + worksharing.parallel(threads) + loop_nest.mark_parallel(par_depth) + elif threads > 1: + if worksharing.single(): + stack.enter_context(code.indent()) + + def gen_kernel(_loop_nest: LoopNest): + def is_parallel_reduction(): + if not _loop_nest.loops: + raise AssertionError("expected _loop_nest.loops") + root = _loop_nest.loops[par_depth.start_depth] + return root.is_reduction and root.parallel + + kernel = _loop_nest.get_kernel() + if isinstance(kernel, OuterLoopFusedKernel): + for _loop_nest in kernel.inner: + gen_loop_nest(_loop_nest) + else: + if not isinstance(kernel, CppKernelProxy): + raise AssertionError( + "expected isinstance(kernel, CppKernelProxy)" + ) + if _loop_nest.loops is not None and is_parallel_reduction(): + kernel.update_stores_with_parallel_reduction() + with contextlib.ExitStack() as stack: + stack.enter_context(code.indent()) + kernel.gen_body(code) + + def get_reduction_prefix_suffix(kernel, parallel=False, is_suffix=False): + if is_suffix: + suffix = kernel.reduction_suffix + if parallel: + suffix = kernel.parallel_reduction_suffix + suffix + else: + suffix = kernel.non_parallel_reduction_suffix + suffix + return suffix + else: + prefix = kernel.reduction_prefix + if parallel: + prefix = prefix + kernel.parallel_reduction_prefix + else: + prefix = prefix + kernel.non_parallel_reduction_prefix + return prefix + + def gen_loop_with_reduction( + _loop_nest: LoopNest, depth: int = 0, in_reduction=False + ): + kernel = _loop_nest.get_kernel() + if not _loop_nest.loops: + raise AssertionError("expected _loop_nest.loops") + loop = _loop_nest.loops[depth] + with contextlib.ExitStack() as stack_outer: + if loop.is_reduction and not in_reduction: + reduction_prefix = get_reduction_prefix_suffix( + kernel, loop.parallel, is_suffix=False + ) + if reduction_prefix: + stack_outer.enter_context(code.indent()) + code.splice(reduction_prefix) + if is_reduction_loop and loop.parallel: + worksharing.parallel(threads) + if kernel.local_reduction_init: + if not kernel.local_reduction_stores: + raise AssertionError( + "expected kernel.local_reduction_stores" + ) + code.splice(kernel.local_reduction_init) + + gen_loop_at(_loop_nest, depth) + + if is_reduction_loop and loop.parallel: + if kernel.local_reduction_stores: + code.splice(kernel.local_reduction_stores) + worksharing.close() + if loop.is_reduction and not in_reduction: + code.splice( + get_reduction_prefix_suffix( + kernel, loop.parallel, is_suffix=True + ) + ) + + def gen_loop_at(_loop_nest: LoopNest, depth: int = 0): + with contextlib.ExitStack() as stack: + if not _loop_nest.loops: + raise AssertionError("expected _loop_nest.loops") + loop = _loop_nest.loops[depth] + loop_lines = loop.lines() + if loop_lines is None: + return + code.writelines(loop_lines) + stack.enter_context(code.indent()) + gen_loop_nest(_loop_nest, depth + 1, loop.is_reduction) + + def gen_loop_nest( + _loop_nest: LoopNest, + depth: int = 0, + in_reduction: bool = False, + ): + if _loop_nest.loops is None or depth == len(_loop_nest.loops): # type: ignore[arg-type] + gen_kernel(_loop_nest) + else: + gen_loop_with_reduction(_loop_nest, depth, in_reduction) + + stack.enter_context(code.indent()) + + if ( + isinstance(loop_nest.kernel, OuterLoopFusedKernel) + and isinstance(V.local_buffer_context, LocalBufferContext) + and V.local_buffer_context.local_buffers + ): + # Allocate local buffer + local_buffers = V.local_buffer_context.local_buffers + for local_buffer in local_buffers.values(): + # For dynamic size, rename s to ks + local_buf_size = sympy_product( + [ + self.rename_indexing(size_val) + for size_val in local_buffer.get_layout().size + ] + ) + local_buf_dtype = DTYPE_TO_CPP[local_buffer.get_layout().dtype] + allocate = f"std::make_unique<{local_buf_dtype} []>({cexpr(local_buf_size)})" + local_buffer_name = local_buffer.get_name() + code.splice( + f"std::unique_ptr<{local_buf_dtype} []> buf_{local_buffer_name} = {allocate};" + ) + code.splice( + f"{local_buf_dtype}* {local_buffer_name} = buf_{local_buffer_name}.get();" + ) + gen_loop_nest(loop_nest) + + def codegen_loops(self, code, worksharing): + loop_nest = LoopNest.build(self) + self.codegen_loops_impl(loop_nest, code, worksharing) + + @property + def assert_function(self) -> str: + if V.graph.aot_mode: + return "AOTI_TORCH_CHECK" + else: + return "TORCH_CHECK" + + def decide_parallel_depth(self, max_parallel_depth, threads): + if self.call_ranges is None: + raise AssertionError("expected self.call_ranges is not None") + ranges = self.call_ranges[ + max_parallel_depth.start_depth : ( + max_parallel_depth.start_depth + max_parallel_depth.parallel_depth + ) + ] + seq = self.size_hint() + par = 1 + depth = 0 + for expr in ranges: + hint = V.graph.sizevars.optimization_hint(expr, fallback=8192) + if par >= 2 * threads or par == threads: + break + if seq // threads < config.cpp.min_chunk_size: + # not enough work + break + depth += 1 + par *= hint + seq /= hint + # if we assume thread number is dynamic, make sure we + # have at least one parallel scope and let OMP runtime + # to manage the serial vs. parallel. + if config.cpp.dynamic_threads and depth == 0 and len(ranges) > 0: + depth = 1 + return ParallelDepth( + parallel_depth=depth, start_depth=max_parallel_depth.start_depth + ) + + @contextlib.contextmanager + def write_to_suffix(self): + prior = (self.loads, self.compute, self.stores, self.cse) + self.loads = IndentedBuffer() + self.compute = IndentedBuffer() + self.stores = IndentedBuffer() + self.cse = self.cse.clone() + yield + self.reduction_suffix.splice(self.loads) + self.reduction_suffix.splice(self.compute) + self.reduction_suffix.splice(self.stores) + (self.loads, self.compute, self.stores, self.cse) = prior + + def create_cse_var(self, *args, **kwargs): + return CppCSEVariable(*args, **kwargs) + + def get_to_dtype_expr(self, src, dtype, src_dtype, rounding=False): + if ( + rounding + and dtype in [torch.int8, torch.uint8] + and src_dtype in [torch.float, torch.double] + ): + return f"c10::convert<{DTYPE_TO_CPP[dtype]}>(std::round({src}))" + return f"c10::convert<{DTYPE_TO_CPP[dtype]}>({src})" + + def cache_dtype_convert(self, dst, dst_dtype, src, src_dtype): + expr = self.get_to_dtype_expr(src, dst_dtype, src_dtype) + self.cse.put(expr, dst) + + def codegen_conditions( + self, + code: BracesBuffer, + prefix: str | None = None, + var: sympy.Symbol | None = None, + ): + if prefix is None: + prefix = "" + if not self.active_ranges: + return True + conditions = [] + + def gen(start, end, var): + if start == end: + return False + var_id = None + for i, _var in enumerate(self.itervars): + if var == _var: + var_id = i + break + if ( + type(self) is CppKernel + and var_id + and start == 0 + and end == self.ranges[var_id] + ): + end = 1 + # pyrefly: ignore [bad-argument-type] + conditions.append(f"{var} >= {cexpr_index(start)}") + # pyrefly: ignore [bad-argument-type] + conditions.append(f"{var} < {cexpr_index(end)}") + return True + + if var is not None: + if var not in self.active_ranges: + raise AssertionError("expected var in self.active_ranges") + start, end = self.active_ranges[var] + if not gen(start, end, var): + return False + else: + for _var, _range in self.active_ranges.items(): + start, end = _range + if not gen(start, end, _var): + return False + joined_conditions = " && ".join(conditions) + if joined_conditions: + code.writeline(f"if({prefix}({joined_conditions}))") + return True + else: + return False + + +class CppVecKernel(CppKernel): + overrides = CppVecOverrides # type: ignore[assignment] + + def __init__( + self, + args, + num_threads, + tiling_factor, + tiling_idx, + tail_size=None, + ): + super().__init__(args, num_threads) + self.vec_isa = cpu_vec_isa.pick_vec_isa() + if not self.vec_isa: + raise AssertionError("expected self.vec_isa") + if tiling_factor <= 0: + raise AssertionError("Expect pass in Non-Zero tiling_factor explicitly") + self.tiling_factor = tiling_factor + self.tiling_idx = tiling_idx + self.tail_size = tail_size + self.num_elems = tail_size if tail_size else tiling_factor + + def _try_get_const_stride(self, index: sympy.Expr, itervar: sympy.Symbol): + if self.index_indirect_depends_on(index, itervar): + return None + for indirect_var in ( + self.cse.varname_map[s.name] # type: ignore[attr-defined] + for s in index.free_symbols + if symbol_is_type(s, SymT.TMP) + ): + if not isinstance(indirect_var, CppCSEVariable): + raise AssertionError( + "expected isinstance(indirect_var, CppCSEVariable)" + ) + if indirect_var.is_vec: + return None + stride = stride_at_vec_range(index, itervar, self.tiling_factor) + return stride if stride.is_number else None + + def _get_num_vectors(self, dtype: torch.dtype) -> int: + num_vectors = math.ceil( + self.tiling_factor * dtype.itemsize * 8 / self.vec_isa.bit_width() + ) + if num_vectors < 1: + raise AssertionError("expected num_vectors >= 1") + return num_vectors + + def _get_raw_num_vectors(self, dtype: torch.dtype) -> float: + # This utility function is used to check if the vector lanes has been + # fully utilized. For example, uint8 will only use 1/4 of the vector lanes. + return self.tiling_factor * dtype.itemsize * 8 / self.vec_isa.bit_width() + + def _get_vec_type(self, dtype: torch.dtype) -> str: + num_vectors = self._get_num_vectors(dtype) + if num_vectors == 1: + return f"at::vec::Vectorized<{DTYPE_TO_CPP[dtype]}>" + else: + return f"at::vec::VectorizedN<{DTYPE_TO_CPP[dtype]},{num_vectors}>" + + def _get_mask_type(self, dtype: torch.dtype = torch.float) -> str: + if dtype == torch.bool: + return "" + num_vectors = self._get_num_vectors(dtype) + return f"at::vec::VecMask<{DTYPE_TO_CPP[dtype]},{num_vectors}>" + + def _get_mask_cast(self, mask: CppCSEVariable, dtype: torch.dtype) -> str: + if mask.dtype != torch.bool: + raise AssertionError(repr(mask)) + num_vectors = self._get_num_vectors(dtype) + return f"{mask}.template cast<{DTYPE_TO_CPP[dtype]},{num_vectors}>()" + + def _get_vec_load_line( + self, + var: str, + index: sympy.Expr, + dtype: torch.dtype, + load_mask: CppCSEVariable | None = None, + ): + """ + Get a load line str that loads a vector from `var` at `index` of type `dtype`. + If `load_mask` is not None, we do a masked load accordingly. + Notes on the `dtype`: + 1. We always load `self.tiling_factor` number of elements regardless of the `dtype`. + It means we load half of the vector lanes for 16-bit data types and quarter of the + vector lanes for 8-bit data types. + 2. `torch.bool` and `torch.uint8` could mean masks and we load them as float mask vectors. + """ + cpp_type = DTYPE_TO_CPP[dtype] + num_vectors = self._get_num_vectors(dtype) + load_mask_str = None + if load_mask: + if not load_mask.is_vec: + # TODO: avoid hard-code torch.float + load_mask_str = f"{self._get_mask_type(torch.float)}::from({load_mask})" + else: + load_mask_str = f"{self._get_mask_cast(load_mask, torch.float)}" + loadbuf = f"{var} + {cexpr_index(index)}" if index != 0 else var + if dtype == torch.bool: + # TODO: should we consider load mask here? + line = f"{self._get_mask_type()}::from({loadbuf}, {cexpr_index(self.num_elems)})" + else: + line = ( + f"{load_mask_str}.template loadu<{cpp_type},{num_vectors}>({loadbuf})" + if load_mask_str + else f"{self._get_vec_type(dtype)}::loadu({loadbuf}, {cexpr_index(self.num_elems)})" + ) + return line + + def _load_or_store_non_contiguous( + self, + var: str | None, + index: sympy.Expr, + dtype: torch.dtype, + buffer: IndentedBuffer | None = None, + store_value: str | CppCSEVariable | None = None, + accu_store: bool = False, + ) -> CppCSEVariable | None: + """ + Load or store a vector in a non-contiguous way. The vector is initialized from an array that is + filled in an inner loop over the tiling factor. + :param var: buffer to load from or store to, i.e. `var[transformed(index)]`. If None, we load the index + as index expression, i.e. `transformed(index)`. + :param index: index into the `var` or the index expression by its own if `var` is None. + The `index` could contain indirect indexing or the tiling itervar. When used in + the inner loop, the index is transformed as follows: + 1. the index is linearized along the tiling dim. + 2. the indirect indexing vector variables are transformed into arrays over the tiling dim. + :param dtype: data type of `var` or `index` if `var` is None. + :param buffer: the code buffer to write the generated code to. If None, we write to `self.loads`. + :param store_value: the value to store. If None, we load the vector. + :param accu_store: whether accumulate the store_value to store_ptr. If True, a store_value should be provided + :return: a CppCSEVariable that represents the loaded vector or None if it is a store. + """ + if store_value and var is None: + raise AssertionError("store var must be provided") + if accu_store: + if not store_value: + raise AssertionError("expected store_value") + if buffer is None: + buffer = self.loads + + def get_result_size(dtype: torch.dtype) -> int: + if dtype.itemsize < 4: + return self.num_elems * (4 // dtype.itemsize) + else: + return self.num_elems + + def get_tiling_size(dtype: torch.dtype) -> int: + if dtype.itemsize < 4: + return self.tiling_factor * (4 // dtype.itemsize) + else: + return self.tiling_factor + + def vec_to_array(vec_var: CppCSEVariable) -> CppCSEVariable: + if not vec_var.is_vec: + raise AssertionError("expected vec_var.is_vec") + code = BracesBuffer() + code.writeline("[&]") + with code.indent(): + vec_dtype = vec_var.dtype + if vec_dtype is None: + raise AssertionError("expected vec_dtype is not None") + if vec_dtype == torch.bool: + vec_dtype = torch.float + result_size = get_result_size(vec_dtype) + tiling_size = get_tiling_size(vec_dtype) + code.writeline( + f"__at_align__ std::array<{DTYPE_TO_CPP[vec_dtype]}, {tiling_size}> tmpbuf;" + ) + line = f"{vec_var}.store(tmpbuf.data(), {cexpr_index(result_size)});" + code.writeline(line) + code.writeline("return tmpbuf;") + code.writeline("()") + csevar = self.cse.generate(buffer, code) + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + return csevar + + code = BracesBuffer() + code.writeline("[&]") + with code.indent(): + result_size = get_result_size(dtype) + tiling_size = get_tiling_size(dtype) + result_declare = ( + f"__at_align__ std::array<{DTYPE_TO_CPP[dtype]}, {tiling_size}> tmpbuf;" + ) + code.writeline(result_declare) + if store_value: + code.writeline( + f"{store_value}.store(tmpbuf.data(), {cexpr_index(result_size)});" + ) + itervar_inner = sympy_index_symbol( + f"{self.itervars[self.tiling_idx]}_inner" + ) + replacements = {} + for indirect_var in ( + self.cse.varname_map[s.name] # type: ignore[attr-defined] + for s in index.free_symbols + if symbol_is_type(s, SymT.TMP) + ): + if not isinstance(indirect_var, CppCSEVariable): + raise AssertionError( + "expected isinstance(indirect_var, CppCSEVariable)" + ) + if indirect_var.is_vec: + array_var = vec_to_array(indirect_var) + replacements[indirect_var] = f"{array_var}[{itervar_inner}]" + index = self.scale_index_with_offset( + index, itervar_idx=self.tiling_idx, offset=itervar_inner + ) + load_mask = None + if self._load_mask is not None: + if store_value: + raise AssertionError("unexpected store with load mask") + if not isinstance(self._load_mask, CppCSEVariable): + raise AssertionError(self._load_mask) + if self._load_mask.is_vec: + load_mask = f"{self._load_mask}.is_masked({itervar_inner})" + else: + load_mask = f"{self._load_mask} != 0" + if cpp_builder.is_gcc(): + code.writeline(f"#pragma GCC unroll {self.tiling_factor}") + else: + code.writeline(f"#pragma unroll {self.tiling_factor}") + code.writeline( + f"for (long {itervar_inner} = 0; " + + f"{itervar_inner} < {cexpr_index(self.num_elems)}; " + + f"{itervar_inner}++)" + ) + with code.indent(), contextlib.ExitStack() as stack: + index_c = cexpr_index(index) + # pyrefly: ignore [bad-assignment] + for indirect_var in replacements: + index_c = re.sub( + r"\b" + f"{indirect_var}" + r"\b", + replacements[indirect_var], + index_c, + ) + rhs = f"{var}[{index_c}]" if var is not None else f"{index_c}" + if load_mask: + code.writeline(f"if ({load_mask})") + stack.enter_context(code.indent()) + if store_value: + conjunction = "+=" if accu_store else "=" + code.writeline(f"{rhs} {conjunction} tmpbuf[{itervar_inner}];") + else: + code.writeline(f"tmpbuf[{itervar_inner}] = {rhs};") + if not store_value: + load_line = self._get_vec_load_line("tmpbuf.data()", 0, dtype) # type: ignore[arg-type] + code.writeline(f"return {load_line};") + code.writeline("()") + if store_value: + code.writeline(";") + buffer.splice(code) + return None + else: + csevar = self.cse.generate(buffer, code, dtype=dtype) + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + csevar.is_vec = True + return csevar + + def load(self, name: str, index: sympy.Expr): + var = self.args.input(name) + index = self.rename_indexing(index) + dtype = V.graph.get_dtype(name) + tiling_var = self.itervars[self.tiling_idx] + stride = self._try_get_const_stride(index, tiling_var) + if stride == 0: + # load scalar and lazily broadcast it on demand + return super().load(name, index) + elif stride == 1: + # load contiguously + line = self._get_vec_load_line(var, index, dtype, self._load_mask) # type: ignore[arg-type] + csevar = self.cse.generate(self.loads, line, dtype=dtype) # type: ignore[assignment] + else: + csevar = self._load_or_store_non_contiguous(var, index, dtype) # type: ignore[assignment] + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + csevar.update_on_args("load", (self, name, index), {}) + csevar.is_vec = True + return csevar + + def _get_store_line( + self, + value: str | CppCSEVariable, + var: str, + index: sympy.Expr, + dtype: torch.dtype, + accu_store: bool = False, + ): + """ + Get a store line buffer that stores `value` into `var` at `index` of `dtype`. It handles + both contiguous and non-contiguous store cases. + :param value: Vectorized type templaterized on `dtype`. + :param var: buffer to store into. + :index: index into the `var`. + """ + # when value's type is str (e.g., welford reduction), caller should make sure + # it is a vector + if not ( + isinstance(value, str) + or (isinstance(value, CppCSEVariable) and value.is_vec) + ): + raise AssertionError(value) + tiling_var = self.itervars[self.tiling_idx] + var_expr = f"{var} + {cexpr_index(index)}" + stride = self._try_get_const_stride(index, tiling_var) + code = IndentedBuffer() + if stride == 1: + if accu_store: + load = ( + f"{self._get_vec_type(dtype)}::loadu({var_expr})" + if dtype == torch.float and self.tail_size is None + else f"{self._get_vec_type(dtype)}::loadu({var_expr}, {cexpr_index(self.num_elems)})" + ) + value = f"({value} + {load})" + if dtype == torch.float and self.tail_size is None: + code.writeline(f"{value}.store({var_expr});") + else: + code.writeline( + f"{value}.store({var_expr}, {cexpr_index(self.num_elems)});" + ) + else: + self._load_or_store_non_contiguous( + var, index, dtype, buffer=code, store_value=value, accu_store=accu_store + ) + return code + + def store(self, name, index, value, mode=None): + if "buf" not in name: + raise AssertionError('expected "buf" in name') + if not isinstance(value, CppCSEVariable): + raise AssertionError(value) + if not value.is_vec: + # this happens when we store a scalar into a vectorized buffer like "fill" + value = self.broadcast(value) + var = self.args.output(name) + index = self.rename_indexing(index) + dtype = V.graph.get_dtype(name) + if mode is None: + code = self._get_store_line(value, var, index, dtype) + self.stores.splice(code.map(lambda x: DeferredLine(name, x))) + elif mode == "atomic_add": + if not self._use_parallel_atomic_add(): + code = self._get_store_line( + f"{value}", + var, + index, + dtype, + accu_store=True, + ) + self.stores.splice(code.map(lambda x: DeferredLine(name, x))) + else: + n_src = self._get_num_vectors(dtype) + n_idx = self._get_num_vectors(torch.int64) + cdtype = DTYPE_TO_CPP[dtype] + # ops.index_expr re-applies subclass index transforms, so a caller + # that already transformed must pass the untransformed index + index = ops.index_expr(index, torch.int64).value + if isinstance(index, CppCSEVariable) and not index.is_vec: + index = self.broadcast(index) + if not (isinstance(index, CppCSEVariable) and index.is_vec): + raise AssertionError( + "expected isinstance(index, CppCSEVariable) and index.is_vec" + ) + if self.tail_size: + line = f"atomic_add_vec<{cdtype}, {n_idx}, {n_src}>({var}, {index}, {value}, {cexpr_index(self.tail_size)});" + else: + line = f"atomic_add_vec<{cdtype}, {n_idx}, {n_src}>({var}, {index}, {value});" + self.stores.writeline(DeferredLine(name, line)) + else: + raise NotImplementedError(f"store mode={mode}") + + def _adjust_argreduce_index(self, index: sympy.Expr) -> sympy.Expr: + return index + + def reduction(self, dtype, src_dtype, reduction_type, value): + """ + Perform vectorized reduction operation. + + This method handles vectorized reduction for different reduction types. + It manages special cases for low-precision floating point types and + employs precision improvement techniques for certain reduction operations. + + Args: + dtype: The output data type for the reduction result + src_dtype: The source data type of the input value + reduction_type: Type of reduction operation (sum, min, max, etc.) + value: The input value to reduce + + Returns: + The result of the reduction operation + """ + # Note: For argmax and argmin on bool type, we always convert bool to float. + # Fix issue: https://github.com/pytorch/pytorch/issues/143568 + if reduction_type not in VECTORIZABLE_RTYPES: + raise AssertionError("expected reduction_type in VECTORIZABLE_RTYPES") + argmax_or_argmin = reduction_type in ("argmax", "argmin") + logical_index = None + if argmax_or_argmin and isinstance(value, tuple): + value, logical_index = value + + horizontal_reduction = self.tiling_idx >= self.reduction_depth + init_dtype = src_dtype if argmax_or_argmin else dtype + if not isinstance(value, CppCSEVariable): + raise AssertionError(value) + if not isinstance(logical_index, (CppCSEVariable, type(None))): + raise AssertionError(logical_index) + + if not value.is_vec: + value = self.broadcast(value) + + if logical_index is not None: + logical_index_key = cast(CppCSEVariable, logical_index) + reduction_key = src_dtype, reduction_type, (value, logical_index_key) + else: + reduction_key = src_dtype, reduction_type, value + if reduction_key in self.reduction_cse.reduction_cache: + return self.reduction_cse.reduction_cache[reduction_key] + + vec_ns = "at::vec" + vec = f"{vec_ns}::Vectorized<{DTYPE_TO_CPP[dtype]}>" + acc_type = reduction_acc_type(reduction_type, init_dtype) + acc_type_vec = self.reduction_acc_type_vec(reduction_type, init_dtype) + + acc = self.reduction_cse.generate( + self.loads, f"reduction {reduction_key}", write=False + ) + if not isinstance(acc, CppCSEVariable): + raise AssertionError("expected isinstance(acc, CppCSEVariable)") + acc_vec = f"{acc}_vec" + masked_acc = f"masked_{acc}" + masked_acc_vec = f"masked_{acc_vec}" + self.reduction_var_names += [f"{acc}", acc_vec, masked_acc_vec] + self.is_reduction = True + self.reduction_prefix_generators.append( + self._gen_reduction_prefix( + acc, acc_type, reduction_type, init_dtype, reduction_init + ) + ) + self.reduction_prefix_generators.append( + self._gen_reduction_prefix( + acc_vec, + acc_type_vec, + reduction_type, + init_dtype, + self.reduction_init_vec, + ) + ) + + use_acc_helper = self.need_use_acc_helper(reduction_type, dtype, False) + if use_acc_helper: + if logical_index is not None: + raise AssertionError(logical_index) + # use masked acc_vec for tail vec kernel + self.reduction_prefix_generators.append( + self._gen_reduction_prefix( + masked_acc_vec, + acc_type_vec, + reduction_type, + dtype, + self.reduction_init_vec, + ) + ) + + # use welford_helper/cascade_helper for vec kernel + if self.reduction_depth is None: + raise AssertionError("expected self.reduction_depth is not None") + reduction_size = functools.reduce( + operator.mul, self.ranges[self.reduction_depth :] + ) + if reduction_type == "welford_reduce": + helper_val = self.welford_helper_cse.generate( + self.compute, f"reduction {reduction_key}", write=False + ) + else: + helper_val = self.cascade_helper_cse.generate( + self.compute, f"reduction {reduction_key}", write=False + ) + masked_helper_val = f"masked_{helper_val}" + helper_vec_range = ( + ( + FloorDiv(reduction_size, self.ranges[self.tiling_idx]) + * FloorDiv(self.ranges[self.tiling_idx], self.tiling_factor) + if self.tiling_idx >= self.reduction_depth + else reduction_size + ) + if FloorDiv(self.ranges[self.tiling_idx], self.tiling_factor) + else sympy.Integer(0) + ) + masked_helper_vec_range = ( + ( + FloorDiv(reduction_size, self.ranges[self.tiling_idx]) + if self.tiling_idx >= self.reduction_depth + else reduction_size + ) + if self.ranges[self.tiling_idx] % self.tiling_factor + else sympy.Integer(0) + ) + # scalar helper for scalar welford_reduce/sum is also needed when vec kernel is included + scalar_helper_val = f"scalar_{helper_val}" + self._use_acc_helper( + reduction_type, + acc, + scalar_helper_val, + reduction_size, + dtype, + use_scalar=True, + ) + self._use_acc_helper( + reduction_type, acc, helper_val, helper_vec_range, dtype + ) + self._use_acc_helper( + reduction_type, + masked_acc, + masked_helper_val, + masked_helper_vec_range, + dtype, + ) + + # use masked acc_vec for tail vec kernel + acc_vec_ = masked_acc_vec if self.tail_size else acc_vec + helper_val_ = masked_helper_val if self.tail_size else helper_val + if reduction_type == "sum": + self.stores.writeline( + f"{acc_vec_} = {self.reduction_combine_vec(reduction_type, acc_vec_, value, helper_val_)};" + ) + else: + self.stores.writeline( + f"{acc_vec_} = {self.reduction_combine_vec(reduction_type, acc_vec_, value, helper_val_)};" + ) + else: + if logical_index is not None: + index = logical_index + index_horizontal_reduction = False + else: + if self.reduction_depth is None: + raise AssertionError("expected self.reduction_depth is not None") + index = self.itervars[self.reduction_depth] + for i in range(self.reduction_depth + 1, len(self.itervars)): + index = index * self.ranges[i] + self.itervars[i] + index_horizontal_reduction = horizontal_reduction + kwargs = { + "next_value": value, + "index": index, + "horizontal_reduction": index_horizontal_reduction, + "src_dtype": src_dtype, + } + self.stores.writeline( + f"{acc_vec} = {self.reduction_combine_vec(reduction_type, acc_vec, **kwargs)};" + ) + self._gen_parallel_reduction_buffers( + acc_vec, + acc_type_vec, + reduction_type, + init_dtype, + reduction_combine_fn=self.reduction_combine_vec, + reduction_init_fn=self.reduction_init_vec, + ) + self._gen_parallel_reduction_buffers( + acc, + acc_type, + reduction_type, + init_dtype, + reduction_combine_fn=reduction_combine, + reduction_init_fn=reduction_init, + ) + if use_acc_helper: + # use masked acc_vec for tail vec kernel + self._gen_parallel_reduction_buffers( + masked_acc_vec, + acc_type_vec, + reduction_type, + dtype, + reduction_combine_fn=self.reduction_combine_vec, + reduction_init_fn=self.reduction_init_vec, + ) + tmpvar: str | CSEVariable + is_bool = dtype == torch.bool + if horizontal_reduction: + # Horizontal reduction + if is_welford_reduction(reduction_type): + if self._get_num_vectors(dtype) not in [ + 1, + 2, + ]: + raise AssertionError( + "Welford reduction does not support VectorizedN (N>2)" + ) + next_value = f"welford_vec_reduce_all({acc_vec})" + masked_next_value = f"welford_vec_reduce_all({masked_acc_vec})" + self.reduction_suffix.writeline( + f"{acc} = {reduction_combine(reduction_type, acc, masked_next_value)};" + ) + elif argmax_or_argmin: + next_value = f"{reduction_type}_vec_reduce_all({acc_vec})" + elif is_bool: + if reduction_type in ( + "any", + "sum", + "max", + ): + next_value = f"!{acc_vec}.all_zero()" + else: + if reduction_type != "min": + raise AssertionError('expected reduction_type == "min"') + next_value = f"{acc_vec}.all_masked()" + else: + reduce_all_body = ( + "{ return " + + self.reduction_combine_vec(reduction_type, "x", "y") + + "; }" + ) + is_bool = dtype == torch.bool + # we are using at::vec::VecMask for bool + vec_dtype = torch.float if is_bool else dtype + vec = f"at::vec::Vectorized<{DTYPE_TO_CPP[vec_dtype]}>" + vec_reduce_all_func = f"at::vec::vec_reduce_all<{DTYPE_TO_CPP[vec_dtype]}, {self._get_num_vectors(vec_dtype)}>" + result_vec = f"{acc_vec}" + if use_acc_helper: + if reduction_type != "sum": + raise AssertionError('expected reduction_type == "sum"') + result_vec = f"{acc_vec} + {masked_acc_vec}" + next_value = f"{vec_reduce_all_func}([]({vec}& x, {vec}& y) {reduce_all_body}, {result_vec})" + + self.reduction_suffix.writeline( + f"{acc} = {reduction_combine(reduction_type, acc, next_value, src_dtype=src_dtype)};" + ) + tmpvar = acc + else: + tmpvar = acc_vec + if is_welford_reduction(reduction_type): + masked_tmpvar = f"masked_{tmpvar}" + self.reduction_suffix.writeline( + f"{tmpvar} = {reduction_combine(reduction_type, tmpvar, masked_tmpvar)};" + ) + elif use_acc_helper: + if reduction_type != "sum": + raise AssertionError('expected reduction_type == "sum"') + masked_tmpvar = f"masked_{tmpvar}" + self.reduction_suffix.writeline( + f"{tmpvar} = {tmpvar} + {masked_tmpvar};" + ) + + result = reduction_project(reduction_type, tmpvar) + self.reduction_cse.reduction_cache[reduction_key] = result + return result + + def store_reduction(self, name, index, value): + index = self.rename_indexing(index) + var = self.args.output(name) + out_dtype = V.graph.get_dtype(name) + if out_dtype.is_floating_point and out_dtype != torch.double: + dtype = torch.float + else: + dtype = out_dtype + out_num_vectors = V.kernel._get_num_vectors(out_dtype) + src_num_vectors = V.kernel._get_num_vectors(dtype) + code = IndentedBuffer() + if self.tiling_idx >= self.reduction_depth: + # Horizontal reduction + code.writeline( + f"{var}[{cexpr_index(index)}] = static_cast<{DTYPE_TO_CPP[out_dtype]}>({value});" + ) + else: + # Vertical reduction + if out_dtype != dtype: + converted_value = ( + f"{DTYPE_TO_CPP[out_dtype].replace('::', '_')}_{value}" + ) + if out_dtype == torch.bool: + convert = f"{value}.template cast()" + else: + if src_num_vectors == out_num_vectors == 1: + convert = ( + f"at::vec::convert<{DTYPE_TO_CPP[out_dtype]}>({value})" + ) + else: + convert = ( + f"at::vec::convert<{DTYPE_TO_CPP[out_dtype]}," + f"{out_num_vectors},{DTYPE_TO_CPP[dtype]},{src_num_vectors}>({value})" + ) + code.writeline(f"auto {converted_value} = {convert};") + value = converted_value + code.splice(self._get_store_line(value, var, index, out_dtype)) + self.reduction_suffix.splice(code.map(lambda x: DeferredLine(name, x))) + + def broadcast(self, scalar_var: CppCSEVariable) -> CppCSEVariable: + if scalar_var.is_vec: + raise AssertionError("expected not scalar_var.is_vec") + if scalar_var.dtype == torch.bool: + vec_var = self.cse.generate( + self.compute, f"{self._get_mask_type()}::from({scalar_var.name})" + ) + else: + if scalar_var.dtype is None: + raise AssertionError("expected scalar_var.dtype is not None") + vec_var = self.cse.generate( + self.compute, + f"{self._get_vec_type(scalar_var.dtype)}({scalar_var.name})", + ) + if not isinstance(vec_var, CppCSEVariable): + raise AssertionError("expected isinstance(vec_var, CppCSEVariable)") + vec_var.dtype = scalar_var.dtype + vec_var.dependent_itervars = scalar_var.dependent_itervars + vec_var.is_vec = True + return vec_var + + def arange(self, index: CppCSEVariable, stride: sympy.Symbol) -> CppCSEVariable: + if index.is_vec: + raise AssertionError("expected not index.is_vec") + if index.dtype is None: + raise AssertionError("expected index.dtype is not None") + csevar = self.cse.generate( + self.compute, + f"{self._get_vec_type(index.dtype)}::arange({index}, {stride})", + ) + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + csevar.dtype = index.dtype + csevar.is_vec = True + return csevar + + def reduction_init_vec(self, reduction_type, dtype): + scalar_type = DTYPE_TO_COMPUTATION_DTYPE[dtype] + vec_type = self._get_vec_type(scalar_type) + + if is_welford_reduction(reduction_type): + return f"Welford<{vec_type}>()" + + if reduction_type in ("argmin", "argmax"): + # For bool argmin/argmax, we use float for computations + compute_dtype = torch.float if dtype == torch.bool else scalar_type + cdtype = DTYPE_TO_CPP[compute_dtype] + acc_type = self.reduction_acc_type_vec(reduction_type, dtype) + if reduction_type == "argmin": + val = ( + f"std::numeric_limits<{cdtype}>::infinity()" + if is_float_dtype(dtype) or dtype == torch.bool + else f"std::numeric_limits<{cdtype}>::max()" + ) + else: + val = ( + f"-std::numeric_limits<{cdtype}>::infinity()" + if is_float_dtype(dtype) or dtype == torch.bool + else f"std::numeric_limits<{cdtype}>::min()" + ) + return f"{acc_type}({val})" + + if reduction_type == "any": + return f"{self._get_mask_type()}::from(0)" + + scalar_init = reduction_init(reduction_type, dtype) + vec_init = f"{vec_type}({scalar_init})" + if dtype == torch.bool: + if reduction_type not in ("min", "max", "sum"): + raise AssertionError('expected reduction_type in ("min", "max", "sum")') + return f"{self._get_mask_type()}::from({scalar_init})" + return vec_init + + def reduction_acc_type_vec(self, reduction_type, dtype): + scalar_type = DTYPE_TO_COMPUTATION_DTYPE[dtype] + vec_type = self._get_vec_type(scalar_type) + if is_welford_reduction(reduction_type): + return f"Welford<{vec_type}>" + if reduction_type in ("argmin", "argmax"): + n_idx = self._get_num_vectors(torch.int64) + if dtype == torch.bool: + # For bool argmin/argmax, we use float for computations + # so n_src must be computed from float, not bool + n_src = self._get_num_vectors(torch.float) + return f"IndexValueVec<{DTYPE_TO_CPP[torch.float]}, {n_src}, {n_idx}>" + n_src = self._get_num_vectors(scalar_type) + return f"IndexValueVec<{DTYPE_TO_CPP[scalar_type]}, {n_src}, {n_idx}>" + if dtype == torch.bool: + if reduction_type not in ("min", "max", "any", "sum"): + raise AssertionError( + 'expected reduction_type in ("min", "max", "any", "sum")' + ) + return f"{self._get_mask_type()}" + return vec_type + + def reduction_combine_vec( + self, + reduction_type, + var, + next_value, + helper_val=None, + index: sympy.Expr | CppCSEVariable | None = None, + horizontal_reduction: bool | None = None, + src_dtype: torch.dtype | None = torch.float32, + ): + """Emit the C++ expression for combining vector reduction values.""" + is_bool = src_dtype == torch.bool + if reduction_type == "max": + if self.tail_size: + return f"max_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return ( + f"{var} | {next_value}" + if is_bool + else f"at::vec::maximum({var}, {next_value})" + ) + elif reduction_type == "min": + if self.tail_size: + return f"min_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return ( + f"{var} & {next_value}" + if is_bool + else f"at::vec::minimum({var}, {next_value})" + ) + elif reduction_type == "sum": + if helper_val: + if self.tail_size: + return f"cascade_sum_combine({next_value}, {cexpr_index(self.tail_size)}, &{helper_val})" + else: + return f"cascade_sum_combine({next_value}, &{helper_val})" + else: + if self.tail_size: + return f"sum_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + conjunction = "|" if is_bool else "+" + return f"{var} {conjunction} {next_value}" + elif reduction_type == "prod": + if self.tail_size: + return f"prod_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return f"{var} * {next_value}" + elif reduction_type == "xor_sum": + if self.tail_size: + return f"xor_sum_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return f"{var} ^ {next_value}" + elif reduction_type == "welford_reduce": + if helper_val: + if self.tail_size: + return f"welford_combine({var}, {next_value}, {cexpr_index(self.tail_size)}, &{helper_val})" + else: + return f"welford_combine({var}, {next_value}, &{helper_val})" + else: + if self.tail_size: + return f"welford_combine({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return f"welford_combine({var}, {next_value})" + elif reduction_type == "welford_combine": + if isinstance(next_value, tuple): + # When reading a value from Inductor IR we have a tuple of variable names + mean, m2, weight = next_value + else: + # When combining intermediate accumulators we have a Welford struct + mean, m2, weight = reduction_project(reduction_type, next_value) + if self.tail_size: + return f"welford_combine({var}, {{{mean}, {m2}, {weight}}}, {cexpr_index(self.tail_size)})" + else: + return f"welford_combine({var}, {{{mean}, {m2}, {weight}}})" + elif reduction_type in ("argmin", "argmax"): + if src_dtype is None: + raise AssertionError("expected src_dtype is not None") + cdtype = DTYPE_TO_CPP[src_dtype] + compute_dtype = src_dtype + if src_dtype == torch.bool: + # For bool argmin/argmax, we use float for computations + cdtype = DTYPE_TO_CPP[torch.float] + compute_dtype = torch.float + # Convert bool VecMask to float vector for argmax_combine_vec + if isinstance(next_value, CppCSEVariable) and next_value.is_vec: + (next_value,) = unify_mask_base_type(self.compute, (next_value,)) + n_src = self._get_num_vectors(compute_dtype) + n_idx = self._get_num_vectors(torch.int64) + t_extra = "" + arg_extra = "" + if index is not None: + if isinstance(index, CppCSEVariable): + if index.is_vec: + arg_extra = f", {index}" + else: + t_extra = ", false" + arg_extra = f", {index}" + else: + if horizontal_reduction is None: + raise AssertionError( + "expected horizontal_reduction is not None" + ) + t_extra = f", {str(horizontal_reduction).lower()}" + arg_extra = f", {self._adjust_argreduce_index(index)}" + if self.tail_size: + return ( + f"{reduction_type}_combine_vec<{cdtype}, {n_src}, {n_idx}{t_extra}>" + f"({var}, {next_value}{arg_extra}, {cexpr_index(self.tail_size)})" + ) + else: + return f"{reduction_type}_combine_vec<{cdtype}, {n_src}, {n_idx}{t_extra}>({var}, {next_value}{arg_extra})" + elif reduction_type == "any": + if isinstance(next_value, CppCSEVariable): + if next_value.dtype != torch.bool: + raise AssertionError("expected next_value.dtype == torch.bool") + (next_value,) = unify_mask_base_type(V.kernel.compute, (next_value,)) + if self.tail_size: + return f"any_masked_reduce({var}, {next_value}, {cexpr_index(self.tail_size)})" + else: + return f"{var} | {next_value}" + else: + raise NotImplementedError + + def indirect_assert(self, var, lower, upper, mask=None): + if not isinstance(var, CppCSEVariable): + raise AssertionError("expected isinstance(var, CppCSEVariable)") + if var.dtype is None: + raise AssertionError("expected var.dtype is not None") + if not var.is_vec: + if isinstance(mask, CppCSEVariable) and mask.is_vec: + mask = f"({mask}).all_masked()" + return super().indirect_assert(var, lower, upper, mask) + lower_scalar = lower + upper_scalar = upper + if lower: + lower = f"{self._get_vec_type(var.dtype)}({lower})" + if upper: + upper = f"{self._get_vec_type(var.dtype)}({upper})" + if lower and upper: + cond = f"({lower} <= {var}) & ({var} < {upper})" + cond_print = f"{lower_scalar} <= {var} < {upper_scalar}" + elif lower: + cond = f"{lower} <= {var}" + cond_print = f"{lower_scalar} <= {var}" + else: + if not upper: + raise AssertionError("expected upper") + cond = f"{var} < {upper}" + cond_print = f"{var} < {upper_scalar}" + cond = f"{self._get_mask_type(var.dtype)}({cond})" + if mask: + if not mask.is_vec: + mask = f"{self._get_mask_type(var.dtype)}::from({mask})" + # We need not check when the mask is False + cond = f"({cond}) | ~({mask})" + if self.tail_size: + cond = ( + f"{self._get_mask_type(var.dtype)}::set({self._get_mask_type(var.dtype)}::from(1)" + f", ({cond}), {cexpr_index(self.tail_size)})" + ) + cond = f"({cond}).all_masked()" + return f'{self.assert_function}({cond}, "index out of bounds: {cond_print}")' + + def get_to_dtype_expr(self, src, dtype, src_dtype, rounding=False): + if not isinstance(src, CppCSEVariable): + raise AssertionError("expected isinstance(src, CppCSEVariable)") + if not src.is_vec: + return super().get_to_dtype_expr(src, dtype, src_dtype, rounding) + src_cpp_type = DTYPE_TO_CPP[src_dtype] + src_num_vectors = self._get_num_vectors(src_dtype) + dst_cpp_type = DTYPE_TO_CPP[dtype] + dst_num_vectors = self._get_num_vectors(dtype) + expr = f"({src})" + if src_dtype != torch.bool and dtype == torch.bool: + expr = f"{self._get_mask_type(src_dtype)}::from<{src_cpp_type},{src_num_vectors}>({src})" + elif src_dtype == torch.bool and dtype != torch.bool: + expr = f"{src}.to<{dst_cpp_type},{dst_num_vectors}>()" + elif src_dtype != dtype: + expr = "" + if ( + rounding + and src_dtype in [torch.float, torch.double] + and dtype in [torch.int8, torch.uint8] + ): + expr = "at::vec::round_convert" + else: + expr = "at::vec::convert" + if src_num_vectors == dst_num_vectors == 1: + expr = expr + f"<{dst_cpp_type}>({src})" + else: + expr = ( + expr + + f"<{dst_cpp_type},{dst_num_vectors},{src_cpp_type},{src_num_vectors}>({src})" + ) + return expr + + +class CppTile2DKernel(CppVecKernel): + """ + A vector kernel that handles the 2d tiles with the tile size defined in `tiling_factor` on + the inner-most loop level and one of the outer loop level (`outer_tiling_idx`). When the data + tile is accessed in a contiguous way from the outer loop axis, a transposition is applied on the + tile to make the access contiguous from the inner-most loop axis. Then, the same vectorization + logic from its parent `CppVecKernel` is leveraged for load/store/compute. The transposed tile load + and store are generated into kernel.preloads and kernel.poststores buffers. + + The loop structure looks like below: + for ... + for i_outer ... + for ... + for inner_most ... + // generated by CppTile2DKernel + float tmp0[16*16]; at::vec::transpose_mxn<...>(tmp0, in_ptr0 + ..., ...); // into kernel.preloads + float tmp1[16*16]; // into kernel.preloads + for i_inner ... { // the kernel inner loop + vectorized loads/compute/stores (e.g., load tmp0, store tmp1) // into kernel.loads/compute/stores + } + at::vec::transpose_mxn(out_ptr0 + ..., tmp1, ...) // into kernel.poststores + for inner_most ... (tail) + // generated by CppVecKernel + ... + for i_outer ... (tail) + for ... + for ... + // generated by CppKernel + ... + """ + + overrides = CppTile2DOverrides # type: ignore[assignment] + + def __init__( + self, + args, + num_threads, + tiling_factor, + tiling_indices, + inner_tail_size=None, + outer_tail_size=None, + ): + super().__init__( + args, + num_threads, + tiling_factor, + tiling_indices[1], + inner_tail_size, + ) + self.tiling_indices = tiling_indices + self.inner_tail_size = inner_tail_size + self.outer_tail_size = outer_tail_size + self.inner_num_elems = inner_tail_size if inner_tail_size else tiling_factor + self.outer_num_elems = outer_tail_size if outer_tail_size else tiling_factor + self.inner_is_tiling_idx = True + + def inner_itervar(self): + return sympy_index_symbol(f"{self.itervars[self.outer_idx]}_inner") + + def need_vec_transpose(self, index): + outer_var = self.itervars[self.outer_idx] + inner_var = self.itervars[self.tiling_idx] + # Indirect indexing (SymT.TMP) variables are declared inside the inner + # loop, but transpose_mxn is emitted into preloads (before the loop). + if free_symbol_is_type(index, SymT.TMP): + return False + outer_stride = stride_at_vec_range(index, outer_var, self.tiling_factor) + inner_stride = stride_at_vec_range(index, inner_var, self.tiling_factor) + return ( + self._load_mask is None # TODO: support transposition with mask + and outer_stride == 1 + and index.has(inner_var) + and not inner_stride.has(inner_var) + and not inner_stride.has(outer_var) + ) + + def gen_transposed_tile_load_store( + self, name, var, index, is_store, store_mode=None + ): + # transposed tile load/store outside the kernel inner loop + dtype = V.graph.get_dtype(name) + factor = self.tiling_factor + src = f"{var} + {cexpr_index(index)}" + dst = "__place_holder__" + ld_src = f"{cexpr_index(stride_at_vec_range(index, self.itervars[self.tiling_idx], self.tiling_factor))}" + ld_dst = f"{cexpr_index(self.num_elems)}" + if is_store: + src, dst = dst, src + ld_src, ld_dst = ld_dst, ld_src + + need_define = True + if self.inner_is_tiling_idx ^ is_store: + M, N = self.inner_num_elems, self.outer_num_elems + else: + M, N = ( + self.outer_num_elems, + self.inner_num_elems, + ) + atomic_add = "true" if (is_store and (store_mode == "atomic_add")) else "false" + if (isinstance(M, sympy.Expr) and not M.is_number) or ( + isinstance(N, sympy.Expr) and not N.is_number + ): + load_or_store = ( + f"transpose_mxn<{DTYPE_TO_CPP[dtype]},{atomic_add}>" + f"({src}, {ld_src}, {dst}, {ld_dst}, {cexpr_index(M)}, {cexpr_index(N)});" + ) + else: + load_or_store = ( + f"transpose_mxn<{DTYPE_TO_CPP[dtype]},{cexpr_index(M)},{cexpr_index(N)},{atomic_add}>" + f"({src}, {ld_src}, {dst}, {ld_dst});" + ) + if is_store: + tile_var = self.cse.newvar() + elif not self.cse.contains(load_or_store): + tile_var = self.cse.generate(self.preloads, load_or_store, write=False) + else: + need_define = False + tile_var = self.cse.get(load_or_store) + + if need_define: + cpp_dtype = DTYPE_TO_CPP[dtype] + # tiling_factor might be smaller than the alignment of cpp_dtype, such as + # with a vector that only holds 4 elements due to NEON 128-bit vectors and + # cpp_dtype being a 64-bit integer. + alignas = f"alignas(std::max(std::size_t({factor}), alignof({cpp_dtype})))" + define_line = f"{alignas} {cpp_dtype} {tile_var}[{factor}*{factor}];" + self.preloads.writeline(define_line) + + load_or_store = load_or_store.replace("__place_holder__", str(tile_var)) + if is_store: + self.poststores.writeline(DeferredLine(name, load_or_store)) + else: + self.preloads.writeline(load_or_store) + + return tile_var + + def load(self, name: str, index: sympy.Expr): + var = self.args.input(name) + index = self.rename_indexing(index) + + inner = self.inner_itervar() + if self.need_vec_transpose(index): + tile_var = self.gen_transposed_tile_load_store( + name, var, index, is_store=False + ) + # vector load inside the kernel inner loop + loadbuf = f"{tile_var} + {cexpr_index(inner * self.num_elems)}" + dtype = V.graph.get_dtype(name) + line = self._get_vec_load_line(loadbuf, 0, dtype) # type: ignore[arg-type] + csevar = self.cse.generate(self.loads, line, dtype=dtype) + csevar.update_on_args("load", (self, name, index), {}) + if not isinstance(csevar, CppCSEVariable): + raise AssertionError("expected isinstance(csevar, CppCSEVariable)") + csevar.is_vec = True + return csevar + else: + new_index = self.transform_indexing(index) + return super().load(name, new_index) + + def store(self, name, index, value, mode=None): + if "buf" not in name: + raise AssertionError('expected "buf" in name') + if not isinstance(value, CppCSEVariable): + raise AssertionError(value) + if not value.is_vec: + # this happens when we store a scalar into a vectorized buffer like "fill" + value = self.broadcast(value) + + var = self.args.output(name) + + inner = self.inner_itervar() + index = self.rename_indexing(index) + if self.need_vec_transpose(index): + tile_var = self.gen_transposed_tile_load_store( + name, var, index, is_store=True, store_mode=mode + ) + # vector store inside the kernel inner loop + storebuf = f"{tile_var} + {cexpr_index(inner * self.num_elems)}" + if self.tail_size or V.graph.get_dtype(name) in DTYPE_LOWP_FP + [ + torch.uint8, + torch.int8, + torch.float8_e4m3fn, + torch.float8_e5m2, + ]: + line = f"{value}.store({storebuf}, {cexpr_index(self.num_elems)});" + else: + line = f"{value}.store({storebuf});" + self.stores.writeline(DeferredLine(name, line)) + else: + # the parallel atomic_add path re-applies transform_indexing via ops.index_expr + vec_atomic_add = mode == "atomic_add" and self._use_parallel_atomic_add() + new_index = index if vec_atomic_add else self.transform_indexing(index) + super().store(name, new_index, value, mode) + + def codegen_inner_loops(self, code): + inner = self.inner_itervar() + if self.inner_is_tiling_idx: + code.writeline( + f"for (long {inner} = 0; {inner} < {cexpr_index(self.outer_num_elems)}; {inner}++)" + ) + else: + code.writeline( + f"for (long {inner} = 0; {inner} < {cexpr_index(self.inner_num_elems)}; {inner}++)" + ) + + def set_ranges(self, group, reduction_group): + vars = super().set_ranges(group, reduction_group) + # do vertical reduction as the tail loop + self.outer_idx, self.tiling_idx = ( + self.tiling_indices + if self.tiling_indices[1] < self.reduction_depth + else reversed(self.tiling_indices) + ) + if self.tiling_idx == self.tiling_indices[0]: + self.tail_size = self.outer_tail_size + self.num_elems = self.outer_num_elems + self.inner_is_tiling_idx = False + else: + self.tail_size = self.inner_tail_size + self.num_elems = self.inner_num_elems + self.inner_is_tiling_idx = True + return vars + + def transform_indexing(self, index: sympy.Expr) -> sympy.Expr: + return self.scale_index_with_offset( + index, + itervar_idx=self.outer_idx, + offset=self.inner_itervar(), + ) + + def _adjust_argreduce_index(self, index: sympy.Expr) -> sympy.Expr: + return self.transform_indexing(index) + + +def get_loop_body_lowp_fp(_body: LoopBody) -> tuple[torch.dtype | None, bool]: + """ + Returns the low precision data type (torch.float16/torch.bfloat16) contained in the nodes + and if all the nodes can codegen with this data type without converting to float. + Otherwise returns None and True. + """ + sub_blocks = [_body.root_block] + list(_body.subblocks.values()) + + _lowp_fp_type: torch.dtype | None = None + _use_fp32 = False + for sub_block in sub_blocks: + for _node in sub_block.graph.nodes: + if _node.op == "placeholder" or _node.target in ( + "get_index", + "index_expr", + "value_expr", + ): + continue + + # Fast path if all operations can support bf16/fp16 without converting to fp32 + if _node.target not in [ + "load", + "store", + "abs", + "neg", + "output", + ]: + _use_fp32 = True + + if hasattr(_node, "meta") and _node.meta: + if OptimizationContext.key not in _node.meta: + raise AssertionError( + "expected OptimizationContext.key in _node.meta" + ) + opt_ctx: OptimizationContext = _node.meta[OptimizationContext.key] + if not opt_ctx.dtype or opt_ctx.dtype not in DTYPE_LOWP_FP: + _use_fp32 = True + elif _lowp_fp_type is not None: + if _lowp_fp_type != opt_ctx.dtype: + warnings.warn("bf16 and fp16 are mixed in the scheduler node.") + else: + _lowp_fp_type = opt_ctx.dtype + else: + _use_fp32 = True + + return _lowp_fp_type, _use_fp32 + + +@dataclasses.dataclass +class KernelOpStats: + """Op statistics collected during tiling selection.""" + + # Ratio of non-contiguous/mask ops to total ops above which vectorization + # is considered unprofitable (used both for disabling vectorization entirely + # and for deciding whether tail vectorization is worthwhile). + OVERHEAD_RATIO_THRESHOLD: ClassVar[float] = 0.12 + + op_counter: dict[str, int] = dataclasses.field(default_factory=dict) + non_contig_indexing_op_counter: dict[str, int] = dataclasses.field( + default_factory=dict + ) + mask_op_count: int = 0 + + +class TilingSelect: + """ + Implement the heuristic to select the tiling factors and tiling indices. + In the future, we can implement advanced heuristic in a subclass. + """ + + def select_tiling( + self, + fn_list, + var_sizes_list, + ) -> tuple[list[int], list[int], KernelOpStats]: + # TODO(jgong5): support alternative tiling factors and data types + loop_bodies = _get_loop_body(fn_list) + all_dtypes = _get_dtype_from_loopbodies(loop_bodies) + if not all_dtypes: + raise AssertionError("expected all_dtypes") + if any(dtype not in VECTORIZABLE_DTYPES for dtype in all_dtypes): + return [], [], KernelOpStats() + dtype = torch.float + _lowp_fp_dtype = get_loop_body_lowp_fp(loop_bodies[0])[0] + if _lowp_fp_dtype and all( + (get_loop_body_lowp_fp(loop_body)[0] == _lowp_fp_dtype) + for loop_body in loop_bodies[1:] + ): + dtype = _lowp_fp_dtype + + tiling_factor = cpu_vec_isa.pick_vec_isa().nelements(dtype=dtype) + tiling_indices = self._select_tiling_indices( + fn_list, var_sizes_list, tiling_factor + ) + + if tiling_indices: + group, reduction_group = max( + var_sizes_list, key=lambda sizes: len(sizes[1]) + ) + call_ranges = tuple(group) + tuple(reduction_group) + + stats = KernelOpStats() + if config.cpp.enable_tiling_heuristics: + + def _try_get_stride( + index, + itervars, + tiling_factor, + tiling_indices, + ): + itervar = itervars[tiling_indices[0]] + stride = stride_at_vec_range(index, itervar, tiling_factor) + return stride if stride.is_number else None + + def _update_negative_op_count( + node_name, non_contig_indexing_op_counter + ): + if node_name not in non_contig_indexing_op_counter: + non_contig_indexing_op_counter[node_name] = 1 + else: + non_contig_indexing_op_counter[node_name] += 1 + + def _is_valid_indices( + itervars, + tiling_indices, + ): + return ( + len(tiling_indices) == 1 + and len(itervars) > 0 + and ( + tiling_indices[0] + if tiling_indices[0] >= 0 + else tiling_indices[0] + len(itervars) + ) + < len(itervars) + ) + + itervars = [ + sympy_index_symbol_with_prefix(SymT.XBLOCK, n) + for n in range(len(call_ranges)) + ] + reduction_depth = len(group) + vars, reduction_vars = ( + itervars[:reduction_depth], + itervars[reduction_depth:], + ) + for _body in loop_bodies: + sub_blocks = [_body.root_block] + list(_body.subblocks.values()) + for sub_block in sub_blocks: + for _node in sub_block.graph.nodes: + if _node.target in [ + "index_expr", + "value_expr", + "load", + "store", + ]: + # get the index and replace prefix from z to x + arg_idx = ( + 1 + if _node.target in ("index_expr", "value_expr") + else 2 + ) + index = sub_block.body.indexing_from_args( + (vars, reduction_vars) + )[_node.args[arg_idx].args[0]] + if _is_valid_indices(itervars, tiling_indices): + stride = _try_get_stride( + index, itervars, tiling_factor, tiling_indices + ) + if ( + stride is None + if _node.target in ("index_expr", "value_expr") + else stride not in [0, 1] + ): + _update_negative_op_count( + _node.target, + stats.non_contig_indexing_op_counter, + ) + if isinstance(_node.target, str): + # Only count "where" and "masked" as mask ops — + # they generate actual mask/blend instructions. + if _node.target in ("where", "masked"): + stats.mask_op_count += 1 + if not ( + _node.target.startswith("masked_subblock") + or _node.target + in ["ops", "output", "constant", "get_index"] + ): + if _node.target not in stats.op_counter: + stats.op_counter[_node.target] = 1 + else: + stats.op_counter[_node.target] += 1 + + op_num = sum(stats.op_counter.values()) + non_contig_indexing_op_num = sum( + stats.non_contig_indexing_op_counter.values() + ) + quantity_threshold = 35 + if non_contig_indexing_op_num >= quantity_threshold or ( + op_num > 0 + and non_contig_indexing_op_num / op_num + >= stats.OVERHEAD_RATIO_THRESHOLD + ): + # Too many non-contiguous load/store/index/value_expr which hurts the + # vectorization performance. Disable vectorization when exceeding + # the thresholds. + return [], [], stats + + if ( + not reduction_group + and group + and len(tiling_indices) == 1 + and not has_free_symbols( + [ + group[tiling_indices[0]], + ] + ) + and group[tiling_indices[0]] < tiling_factor / 4 + and op_num < 10 + ): + # We found that when the number of elements in the inner loop range is + # relatively small(< tiling_factor / 4) and the number of operations is + # not large(< 10), vectorization is not efficient. + # And found that `#pragma GCC ivdep` has better performance than + # `#pragma omp simd simdlen(8)` for these cases. + return [], [], stats + + if dtype in DTYPE_LOWP_FP: + # For lower precision data type, if the call_range is not long enough, + # use tiling_factor // 2 for better performance + factor_lowp = cpu_vec_isa.pick_vec_isa().nelements(dtype=dtype) + for tiling_indice in tiling_indices: + if tiling_indice < 0: + tiling_indice = tiling_indice + len(call_ranges) + if tiling_indice < 0 or tiling_indice >= len(call_ranges): + continue + if has_free_symbols(call_ranges): + call_range = V.graph.sizevars.optimization_hint( + call_ranges[tiling_indice], fallback=0 + ) + if call_range < factor_lowp: + V.graph.sizevars.check_lt(call_range, factor_lowp) # type: ignore[arg-type] + tiling_factor = factor_lowp // 2 + break + elif call_ranges[tiling_indice] < factor_lowp: + tiling_factor = factor_lowp // 2 + break + + if len(tiling_indices) == 1: + return [tiling_factor], tiling_indices, stats + if len(tiling_indices) == 2: + return [tiling_factor, tiling_factor], tiling_indices, stats + return [], [], KernelOpStats() + + def _select_tiling_indices( + self, + fn_list, + var_sizes_list, + tiling_factor, + ): + all_index = [] + for fn, var_sizes in zip(fn_list, var_sizes_list): + rw = dependencies.extract_read_writes(fn, *var_sizes) + all_index += [dep.index for dep in itertools.chain(rw.reads, rw.writes)] + contig_vars = OrderedSet[int]() + contig_vars_list = [] + non_contig_stride_const = OrderedSet[int]() + non_contig_stride_other = OrderedSet[int]() + for index in all_index: + for var in index.free_symbols: + if not re.search(r"^d\d+$", var.name): + continue + stride = stride_at_vec_range(index, var, tiling_factor) + if stride == 0: + continue + elif stride == 1: + contig_vars.add(int(var.name[1:])) + contig_vars_list.append(int(var.name[1:])) + elif all(symbol_is_type(s, SymT.SIZE) for s in stride.free_symbols): + non_contig_stride_const.add(int(var.name[1:])) + else: + non_contig_stride_other.add(int(var.name[1:])) + contig_only = contig_vars - non_contig_stride_const - non_contig_stride_other + group, reduction_group = max(var_sizes_list, key=lambda sizes: len(sizes[1])) + num_itervars = len(group) + len(reduction_group) + if len(contig_vars) == 0: + # no contiguous vars + return [num_itervars - 1] + if contig_only: + return sorted(contig_only)[-1:] + contig_and_const_stride = ( + contig_vars & non_contig_stride_const + ) - non_contig_stride_other + contig_vars_sorted = sorted(contig_vars) + if ( + len(contig_vars_sorted) == 2 + and contig_vars_sorted[-1] in contig_and_const_stride + and contig_vars_sorted[-1] == num_itervars - 1 + ): + return contig_vars_sorted + return sorted(contig_vars_sorted, key=contig_vars_list.count)[-1:] + + +class CppKernelProxy(CppKernel): + # Subclass CppKernel, CppVecKernel, etc., to customize code generation. + # Override CppOverrides or CppVecOverrides to emit custom ops. + # Earlier, this meant copying codegen_functions() to use your subclasses. + # Now, use kernel_cls and vec_kernel_cls class attributes instead. + # This lets CppKernelProxy subclasses inject custom behavior cleanly. + # No need to duplicate codegen_functions() just to swap kernel classes. + kernel_cls: type[CppKernel] = CppKernel + vec_kernel_cls: type[CppVecKernel] = CppVecKernel + tile2d_kernel_cls: type[CppTile2DKernel] = CppTile2DKernel + + def __init__(self, kernel_group): + super().__init__(kernel_group.args, kernel_group.ws.num_threads) + self.kernel_group = kernel_group + self.loop_nest = None + self.call_ranges = None + self.picked_vec_isa: cpu_vec_isa.VecISA = cpu_vec_isa.pick_vec_isa() + self.kernels: list[CppKernel] = [] + + def data_type_propagation(self, nodes): + for _node in nodes: + if not isinstance(_node, SchedulerNode): + raise AssertionError("expected isinstance(_node, SchedulerNode)") + DataTypePropagation.propagate_scheduler_node(_node) + + # Check if all the nodes of a given fx graph can support BF16/FP16 + def is_lowp_fp_scheduler(self, scheduler_node: SchedulerNode): + if not isinstance(scheduler_node._body, LoopBody): + return True + # Propagate the dtype to check if all the fx node is bf16/fp16 + DataTypePropagation.propagate_scheduler_node(scheduler_node) + return ( + get_loop_body_lowp_fp(scheduler_node._body)[0] is not None + and not get_loop_body_lowp_fp(scheduler_node._body)[1] + ) + + def legalize_lowp_fp_dtype_loopbody(self, loop_body: LoopBody): + def add_to_dtype(sub_graph: torch.fx.Graph): + def get_input_dtype(node: torch.fx.Node) -> torch.dtype | None: + """Get input dtype for nodes that may consumes lowp fp dt""" + if node.target == "store": + return V.graph.get_dtype(node.args[1]) # type: ignore[arg-type] + elif node.target == "to_dtype_bitcast": + return node.args[-1] # type: ignore[return-value] + elif node.target == "to_dtype": + if len(node.args) > 3: + return node.args[3] # type: ignore[return-value] + else: + return node.kwargs.get("src_dtype", None) # type: ignore[return-value] + else: + return None + + def get_output_dtype(node: torch.fx.Node) -> torch.dtype | None: + """Get output dtype for nodes that may produce lowp fp dt""" + if node.target == "load": + if len(node.args) != 3: + raise AssertionError("expected len(node.args) == 3") + return V.graph.get_dtype(node.args[1]) # type: ignore[arg-type] + elif node.target in [ + "to_dtype", + "constant", + "index_expr", + "value_expr", + ]: + return node.args[-1] # type: ignore[return-value] + elif node.target == "to_dtype_bitcast": + return node.args[2] # type: ignore[return-value] + else: + return None + + def is_lowp_fp_source(node: torch.fx.Node, dt: torch.dtype): + """Check if the given node produces output with expected low precision floating point data type.""" + if dt not in DTYPE_LOWP_FP: + raise AssertionError("expected dt in DTYPE_LOWP_FP") + return get_output_dtype(node) == dt + + def is_lowp_fp_sink(node: torch.fx.Node, dt: torch.dtype): + """Check if the given node accept input with expected low precision floating point data type.""" + if dt not in DTYPE_LOWP_FP: + raise AssertionError("expected dt in DTYPE_LOWP_FP") + if input_dtype := get_input_dtype(node): + return input_dtype == dt + elif node.target == "to_dtype": + # The `src_dtype` of a `to_dtype` node might miss, in which case the node accept any input dtype. + return True + else: + return False + + def is_lowp_fp_source_no_promote(node: torch.fx.Node, dt: torch.dtype): + """Check if the node is a lowp fp sources which are all directly fed to ops that accepts lowp fp input + thus no need to promote to float + """ + return is_lowp_fp_source(node, dt) and all( + is_lowp_fp_sink(user, dt) for user in node.users + ) + + sub_graph_nodes = list(sub_graph.nodes) + to_lowp_fp_legalized_nodes = [] + for _node in sub_graph_nodes: + if ( + _node.target in ["load", "index_expr", "value_expr"] + and (dt := get_output_dtype(_node)) in DTYPE_LOWP_FP + ): + # No need to promote to float if all users are ops that accepts lowp fp input + # pyrefly: ignore [bad-argument-type] + if all(is_lowp_fp_sink(user, dt) for user in _node.users): + continue + ops = _node.args[0] + with sub_graph.inserting_after(_node): + to_type_node = sub_graph.call_method( + "to_dtype", args=(ops, _node, torch.float) + ) + _node.replace_all_uses_with( + to_type_node, lambda n: n is not to_type_node + ) + # pyrefly: ignore [bad-assignment] + metrics.cpp_to_dtype_count += 1 + elif ( + _node.target == "store" + and (dt := get_input_dtype(_node)) in DTYPE_LOWP_FP + ): + ops, name, _, value_var, _ = _node.args + # pyrefly: ignore [bad-argument-type] + if is_lowp_fp_source_no_promote(value_var, dt): + continue + dtype = V.graph.get_dtype(name) + with sub_graph.inserting_before(_node): + to_type_node = sub_graph.call_method( + "to_dtype", args=(ops, value_var, dtype) + ) + _node.replace_input_with(value_var, to_type_node) + # pyrefly: ignore [bad-assignment] + metrics.cpp_to_dtype_count += 1 + elif _node.target == "reduction": + ( + ops, + dtype, + src_dtype, + reduction_type, + value, + ) = _node.args + if src_dtype in DTYPE_LOWP_FP: + # Since we always convert the load/store value to float if the tensor is bfloat16/float16. + # Therefore, the reduction should never work with bfloat16/float16 value. Hence, we update + # the bfloat16/float16 reduction by + # 1) updating the src_dtype to float + # and 2) updating the dtype to float if it is bfloat16/float16. + if dtype not in [ + torch.float, + torch.bfloat16, + torch.float16, + torch.int64, + ]: + raise AssertionError( + "expected dtype in [ torch.float, torch.bfloat16, torch.float16, to..." + ) + _node.args = ( + ops, + torch.float if dtype in DTYPE_LOWP_FP else dtype, + torch.float, + reduction_type, + value, + ) + elif _node.target == "constant" and _node.args[-1] in DTYPE_LOWP_FP: + # No need to promote to float if all users are ops that accepts lowp fp input + (ops, value, dt) = _node.args + if all(is_lowp_fp_sink(user, dt) for user in _node.users): # type: ignore[arg-type] + continue + _node.args = (ops, value, torch.float) + elif _node.target == "to_dtype" and _node.args[-1] in DTYPE_LOWP_FP: + # No need to promote to float if all users are ops that accepts lowp fp input + (ops, x, dt) = _node.args + if all(is_lowp_fp_sink(user, dt) for user in _node.users): # type: ignore[arg-type] + continue + # The legalization always loads the BF16/FP16 tensor as FP32 for computation + # and converts back to BF16/FP16 after the computation. + # Hence, there should be no computation w/ BF16/FP16. + # Therefore, we update the to_dtype by replacing the bf16/fp16 dtype with fp32. + # Save the legalized to_dtype node for the elimination(eliminate_to_dtype step): + # 1) Eliminate the redundant to_dtype node if we have a pattern as follows: + # graph(): + # %lowp_fp_legalized = call_method[target=to_dtype](args = (%ops, %input, torch.float)) + # %to_dtype2 = call_method[target=to_dtype](args = (%ops, %lowp_fp_legalized, torch.bfloat16/float16)) + # Regarding the first to_dtype, it is redundant because + # the second to_type also converts to the torch.bfloat16/torch.float16. + # Hence, we remove the first to_type. + to_lowp_fp_legalized_nodes.append(_node) + _node.args = (ops, x, torch.float) + elif _node.target == "to_dtype_bitcast": + (ops, value_var, dtype, src_dtype) = _node.args + + # to_dtype_bitcast act as a lowp fp sink: + # c10::bit_cast requires the source and target have the same bitwidth. Because the input tensor's + # dtype could be promoted, e.g. from float16 to float, we have to cast the tensor to its original + # source dtype before invoking bit_cast. + if src_dtype in DTYPE_LOWP_FP: + # No need to promote to float if it is a user of a lowp fp sources + # which are all directly fed to ops that accepts lowp fp input + if not is_lowp_fp_source_no_promote(value_var, src_dtype): + with sub_graph.inserting_before(_node): + to_type_node = sub_graph.call_method( + "to_dtype", args=(ops, value_var, src_dtype) + ) + _node.replace_input_with(value_var, to_type_node) + # pyrefly: ignore [bad-assignment] + metrics.cpp_to_dtype_count += 1 + + # to_dtype_bitcast act as a lowp fp source: + # We also need to convert the bit-casted tensor back to float to make sure we keep using higher + # precision values for the rest of the computation. + if dtype in DTYPE_LOWP_FP: + # No need to promote to float if all users are ops that accepts lowp fp input + if not ( + all(is_lowp_fp_sink(user, dtype) for user in _node.users) + ): + ops = _node.args[0] + with sub_graph.inserting_after(_node): + to_type_node = sub_graph.call_method( + "to_dtype", args=(ops, _node, torch.float) + ) + _node.replace_all_uses_with( + to_type_node, lambda n: n is not to_type_node + ) + # pyrefly: ignore [bad-assignment] + metrics.cpp_to_dtype_count += 1 + + def eliminate_to_dtype(sub_graph: torch.fx.Graph): + def _eliminate_duplicate_to_node(sub_graph: torch.fx.Graph): + # Eliminate the redundant to_dtype node. Let's consider a pattern as follows: + # graph(): + # %to_dtype1 = call_method[target=to_dtype](args = (%ops, %input, torch.float), kwargs = {}) + # %to_dtype2 = call_method[target=to_dtype](args = (%ops, %to_dtype1, torch.float), kwargs = {}) + # Regarding the first to_dtype, it is redundant because the second to_type also converts to the + # torch.float. Hence, we remove the first to_type + def _used_by_to(to_node: torch.fx.Node): + return all(usr.target == "to_dtype" for usr in to_node.users) + + all_to_nodes = [ + node for node in sub_graph.nodes if node.target == "to_dtype" + ] + all_to_nodes_and_users = [ + {node: node.users} for node in all_to_nodes if _used_by_to(node) + ] + for node_users in all_to_nodes_and_users: + for node, users in node_users.items(): + if node in sub_graph.nodes and ( + all(usr.args[-1] == node.args[-1] for usr in users) + or ( + node in to_lowp_fp_legalized_nodes + and all( + usr.args[-1] in DTYPE_LOWP_FP for usr in users + ) + ) + ): + val_node = node.all_input_nodes[-1] + node.replace_all_uses_with(val_node) + sub_graph.erase_node(node) + + # For debug mode, the graph of LoopBody will attach a new GraphModule as + # owning_module for debugging while the release mode will not. The lint will + # check whether the graph has owning_module to decide if it needs to check + # call_module. LoopBody might contain get_index as a module call. But it + # is just a function. Hence, it cannot pass the lint check for debug mode. + # We bypass the check if the owning_module is None. Eventually, we should call + # get_index via call_function but not call_module. + if sub_graph.owning_module is None: + sub_graph.lint() + + _eliminate_duplicate_to_node(sub_graph) + + eliminate_to_dtype(sub_graph) + + sub_blocks = [loop_body.root_block] + list(loop_body.subblocks.values()) + for sub_block in sub_blocks: + add_to_dtype(sub_block.graph) + + def legalize_lowp_fp_dtype(self, nodes): + if all( + isinstance(_node, SchedulerNode) and self.is_lowp_fp_scheduler(_node) + for _node in nodes + ): + # Mark the load node to load bf16/fp16 + for _node in nodes: + sub_blocks = [_node._body.root_block] + list( + _node._body.subblocks.values() + ) + for sub_block in sub_blocks: + for fx_node in sub_block.graph.nodes: + if fx_node.target in ["load", "store"]: + if not fx_node.meta: + raise AssertionError("expected fx_node.meta") + if OptimizationContext.key not in fx_node.meta: + raise AssertionError( + "expected OptimizationContext.key in fx_node.meta" + ) + opt_ctx: OptimizationContext = fx_node.meta[ + OptimizationContext.key + ] + if opt_ctx.dtype not in DTYPE_LOWP_FP: + raise AssertionError( + "expected opt_ctx.dtype in DTYPE_LOWP_FP" + ) + + # Bypass the legalization as the kernel can run with bf16/fp16 directly + return + + for _node in nodes: + if not isinstance(_node, SchedulerNode): + raise AssertionError("expected isinstance(_node, SchedulerNode)") + if not isinstance(_node._body, LoopBody): + raise AssertionError("expected isinstance(_node._body, LoopBody)") + body: LoopBody = _node._body + if not body.is_memory_copy(): + self.legalize_lowp_fp_dtype_loopbody(body) + + def codegen_functions(self, fn_list, var_sizes_list): + """Generate scalar and vectorized C++ kernels with tiling for the given functions.""" + if len(fn_list) != len(var_sizes_list): + raise AssertionError("expected len(fn_list) == len(var_sizes_list)") + kernel_group = self.kernel_group + group, reduction_group = max(var_sizes_list, key=lambda sizes: len(sizes[1])) + + self.set_ranges(group, reduction_group) + + def codegen_kernel(cls, *args): + with kernel_group.new_kernel(cls, *args) as kernel: + # Ugly hack to maintain the metrics kernel count since + # we only count in CppKernelProxy, not those contained in it + # pyrefly: ignore [bad-assignment] + metrics.generated_kernel_count -= 1 + + run(kernel) + return kernel + + def run(kernel): + vars, reduction_vars = kernel.set_ranges(group, reduction_group) + in_suffix = False + for fn, var_sizes in zip(fn_list, var_sizes_list): + if var_sizes in [ + (group, reduction_group), + (tuple(itertools.chain(group, reduction_group)), ()), + ]: + if in_suffix: + raise AssertionError("expected not in_suffix") + fn(vars, reduction_vars) + else: + in_suffix = True + if not ( + var_sizes + == ( + group, + (), + ) + ): + raise AssertionError( + f"unexpected group: {var_sizes} != {group}, {reduction_group}" + ) + # we can fuse in some extra pointwise into the suffix + with kernel.write_to_suffix(): + fn(vars, ()) + + scalar_kernel = codegen_kernel(self.kernel_cls) + V.graph.removed_buffers |= scalar_kernel.removed_buffers + V.graph.inplaced_to_remove |= scalar_kernel.inplaced_to_remove + self.loop_nest = LoopNest.build(scalar_kernel) + + if not self.picked_vec_isa or not self.itervars: + self.kernels = [scalar_kernel] + self.aggregate_reduction_buffers(False, None) + self.loop_nest.set_kernel(self) + return + + # Kernels share the same global contexts like V.graph.wrapper_code, V.kernel.args. + # But the generated scalar kernel has updated these global contexts. Hence, the other kernels + # should not do this again to avoid context conflict. By now, we only control the + # config.inplace_buffers. In the future, we could maintain more contexts. + with torch._inductor.config.patch(inplace_buffers=False): + tiling_select = TilingSelect() + tiling_factors, tiling_indices, tiling_stats = tiling_select.select_tiling( + fn_list, var_sizes_list + ) + + def _tail_vec_worthwhile(tail_size, tiling_factor) -> bool: + # Tail vectorization has non-trivial mask/cast/blend overhead. + # Only vectorize tail when it is large enough to amortize overhead. + op_num = sum(tiling_stats.op_counter.values()) + if ( + op_num > 0 + and ( + tiling_stats.mask_op_count + + sum(tiling_stats.non_contig_indexing_op_counter.values()) + ) + / op_num + > tiling_stats.OVERHEAD_RATIO_THRESHOLD + ): + hint_tail_size = V.graph.sizevars.optimization_hint(tail_size) + return 2 * hint_tail_size > tiling_factor + return True + + if len(tiling_factors) != len(tiling_indices): + raise AssertionError( + "expected len(tiling_factors) == len(tiling_indices)" + ) + _inner_loop_reduction_outer_not = False + _tiled_loop_reduction_descendant = False + _outer_loop = None + if tiling_indices: + inner_loop_reduction = False + outer_loop_level = tiling_indices[0] + inner_loop_level = outer_loop_level + 1 + if len(self.loop_nest.loops) > inner_loop_level: + inner_loop_reduction = self.loop_nest.loops[ + inner_loop_level + ].is_reduction + outer_loop_reduction = self.loop_nest.loops[ + outer_loop_level + ].is_reduction + _inner_loop_reduction_outer_not = ( + inner_loop_reduction and not outer_loop_reduction + ) + _tiled_loop_reduction_descendant = not outer_loop_reduction and any( + loop.is_reduction + for loop in self.loop_nest.loops[inner_loop_level:] + ) + + if len(tiling_indices) == 1: + # pyrefly: ignore [bad-assignment] + metrics.generated_cpp_vec_kernel_count += 1 + loop = self.loop_nest.tile(tiling_indices[0], factor=tiling_factors[0]) + vec_kernel = codegen_kernel( + self.vec_kernel_cls, tiling_factors[0], tiling_indices[0] + ) + tail_size = loop.size - loop.tiled_size + vec_kernel.active_ranges = {loop.var: (0, loop.tiled_size)} + if config.cpp.enable_loop_tail_vec and _tail_vec_worthwhile( + tail_size, tiling_factors[0] + ): + tail_kernel = codegen_kernel( + self.vec_kernel_cls, + tiling_factors[0], + tiling_indices[0], + tail_size, + ) + else: + tail_kernel = scalar_kernel + scalar_kernel.inner_itervars = [loop.var] + tail_kernel.active_ranges = {loop.var: (loop.tiled_size, loop.size)} + self.kernels = [vec_kernel, tail_kernel] + _outer_loop = loop + elif len(tiling_indices) == 2: + if not ( + tiling_indices[1] == len(self.itervars) - 1 + and tiling_factors[0] == tiling_factors[1] + ): + raise AssertionError( + "expected tiling_indices[1] == len(self.itervars) - 1 and tiling_fa..." + ) + + # pyrefly: ignore [bad-assignment] + metrics.generated_cpp_vec_kernel_count += 2 + outer_loop = self.loop_nest.tile( + tiling_indices[0], factor=tiling_factors[0] + ) + outer_ranges = { + "main": (0, outer_loop.tiled_size), + "tail": (outer_loop.tiled_size, outer_loop.size), + } + outer_tail_size = outer_loop.size - outer_loop.tiled_size + inner_loop = self.loop_nest.tile( + tiling_indices[1], factor=tiling_factors[0] + ) + inner_ranges = { + "main": (0, inner_loop.tiled_size), + "tail": (inner_loop.tiled_size, inner_loop.size), + } + inner_tail_size = inner_loop.size - inner_loop.tiled_size + tile2d_kernel = codegen_kernel( + self.tile2d_kernel_cls, + tiling_factors[0], + tiling_indices, + ) + tile2d_kernel.active_ranges = { + outer_loop.var: outer_ranges["main"], + inner_loop.var: inner_ranges["main"], + } + tail_kernel = [] + if config.cpp.enable_loop_tail_vec and _tail_vec_worthwhile( + inner_tail_size, tiling_factors[0] + ): + for outer_r, inner_r in ( + ("main", "tail"), + ("tail", "main"), + ("tail", "tail"), + ): + _inner_tail_size = ( + inner_tail_size if inner_r == "tail" else None + ) + _outer_tail_size = ( + outer_tail_size if outer_r == "tail" else None + ) + kernel = codegen_kernel( + self.tile2d_kernel_cls, + tiling_factors[0], + tiling_indices, + _inner_tail_size, + _outer_tail_size, + ) + kernel.active_ranges = { + outer_loop.var: outer_ranges[outer_r], + inner_loop.var: inner_ranges[inner_r], + } + tail_kernel.append(kernel) + else: + vec_kernel = codegen_kernel( + self.vec_kernel_cls, tiling_factors[0], tiling_indices[0] + ) + vec_kernel.active_ranges = { + outer_loop.var: outer_ranges["main"], + inner_loop.var: inner_ranges["tail"], + } + vec_kernel.inner_itervars = [inner_loop.var] + tail_kernel.append(vec_kernel) + scalar_kernel.active_ranges = { + outer_loop.var: outer_ranges["tail"], + inner_loop.var: (0, inner_loop.size), + } + scalar_kernel.inner_itervars = [inner_loop.var, outer_loop.var] + tail_kernel.append(scalar_kernel) + self.kernels = [tile2d_kernel] + tail_kernel + _outer_loop = outer_loop + else: + self.kernels = [scalar_kernel] + # A non-reduction tiled loop with a nested reduction needs its + # reduction suffix selected by the same main/tail active range. + self.aggregate_reduction_buffers( + _inner_loop_reduction_outer_not + or (len(tiling_indices) == 1 and _tiled_loop_reduction_descendant), + _outer_loop, + ) + self.loop_nest.set_kernel(self) + + def codegen_loop_bodies(self, loop_bodies, var_sizes_list): + for body in loop_bodies: + self.legalize_lowp_fp_dtype_loopbody(body) + DataTypePropagation.propagate_loopbody(body) + self.codegen_functions(loop_bodies, var_sizes_list) + + def codegen_nodes(self, nodes: list[SchedulerNode]): + # Legalize BF16 node by adding to_dtype explicitly + self.legalize_lowp_fp_dtype(nodes) + self.data_type_propagation(nodes) + if len(nodes) < 1: + raise AssertionError("expected len(nodes) >= 1") + + def fn(node, *index_vars): + node.decide_inplace_update() + node.mark_run() + if isinstance(V.kernel, NullKernelHandler): + return node._body(*index_vars) + else: + return node.codegen(index_vars) + + fn_list = [functools.partial(fn, node) for node in nodes] + + if ( + isinstance(V.local_buffer_context, LocalBufferContext) + and V.local_buffer_context.local_buffers + ): + + def wrap_fn(fn): + wrapped_fn = V.local_buffer_context.localize_function( + fn, + ) + wrapped_fn.original_fn = fn + return wrapped_fn + + fn_list = [wrap_fn(fn) for fn in fn_list] + + var_sizes_list = [node.group[1] for node in nodes] + self.codegen_functions(fn_list, var_sizes_list) + + def codegen_loops(self, code, worksharing): + self.codegen_loops_impl(self.loop_nest, code, worksharing) + + def update_stores_with_parallel_reduction(self): + for kernel in self.kernels: + kernel.update_stores_with_parallel_reduction() + + def gen_body(self, code: BracesBuffer | None = None): + if code is None: + raise AssertionError("expected code is not None") + if_prefix = "C10_LIKELY" + for kernel in self.kernels: + with contextlib.ExitStack() as stack: + if kernel.codegen_conditions(code, if_prefix): + if_prefix = "C10_UNLIKELY" + stack.enter_context(code.indent()) + code.splice(kernel.gen_body()) + + def aggregate_reduction_buffers( + self, inner_loop_reduction_outer_not: bool, outer_loop: Optional["LoopLevel"] + ): + """ + CppKernel/CppVecKernel/CppTile2dKernel have reduction buffers themselves. + Here, we decide how to aggregate them together and place new reduction buffers + under CppKernelProxy. + """ + + def aggregate_reduction_prefix_suffix(outer_loop: "LoopLevel"): + if len(self.kernels) < 2: + raise AssertionError("expected len(self.kernels) >= 2") + main_loop_kernel = self.kernels[0] + tail_loop_kernel = self.kernels[-1] + if not isinstance(main_loop_kernel, self.vec_kernel_cls): + raise AssertionError( + "expected isinstance(main_loop_kernel, self.vec_kernel_cls)" + ) + + # Prefix + if type(tail_loop_kernel) is self.kernel_cls: + # if tail loop kernel is a scalar kernel, we need to extend tmp_acc -> tmp_acc_arr[] to + # hold the temporary inner loop acc result for outer tail loop + tail_loop_kernel.finalize_reduction_prefix( + main_loop_kernel.tiling_factor + ) + main_loop_kernel.finalize_reduction_prefix() + self.reduction_prefix.splice( + tail_loop_kernel.reduction_prefix + + main_loop_kernel.reduction_prefix + ) + else: + main_loop_kernel.finalize_reduction_prefix() + self.reduction_prefix.splice(main_loop_kernel.reduction_prefix) + + # Suffix + suffix_buf = BracesBuffer() + with contextlib.ExitStack() as stack: + if main_loop_kernel.codegen_conditions( + suffix_buf, "C10_LIKELY", outer_loop.var + ): + stack.enter_context(suffix_buf.indent()) + suffix_buf.splice(main_loop_kernel.reduction_suffix) + with contextlib.ExitStack() as stack: + if tail_loop_kernel.codegen_conditions( + suffix_buf, "C10_UNLIKELY", outer_loop.var + ): + stack.enter_context(suffix_buf.indent()) + if type(tail_loop_kernel) is self.kernel_cls: + reduction_vars = tail_loop_kernel.reduction_var_names + for name in reduction_vars: + new_name = f"{name}_arr[{outer_loop.var}_tail - {cexpr_index(outer_loop.tiled_size)}]" + replace_acc_name(tail_loop_kernel.stores, name, new_name) + replace_acc_name( + tail_loop_kernel.reduction_suffix, name, new_name + ) + # If tail loop kernel is a scalar kernel, use direct sum instead of cascade_sum_combine + # as the reduction vars are extended: tmp_acc -> tmp_acc_arr[]. + replace_cascade_sum_with_add(tail_loop_kernel.stores) + suffix_buf.splice( + move_code_under_inner_loop( + tail_loop_kernel.reduction_suffix, + outer_loop.var, + f"{outer_loop.var}_tail", + outer_loop.tiled_size, + outer_loop.size, + ) + ) + else: + suffix_buf.splice(tail_loop_kernel.reduction_suffix) + self.reduction_suffix = suffix_buf + + main_kernel = self.kernels[0] + if inner_loop_reduction_outer_not: + if not outer_loop: + raise AssertionError("expected outer_loop") + aggregate_reduction_prefix_suffix(outer_loop) + else: + main_kernel.finalize_reduction_prefix() + self.reduction_prefix.splice(main_kernel.reduction_prefix) + self.reduction_suffix.splice(main_kernel.reduction_suffix) + self.parallel_reduction_prefix.splice(main_kernel.parallel_reduction_prefix) + self.parallel_reduction_suffix.splice(main_kernel.parallel_reduction_suffix) + self.local_reduction_init.splice(main_kernel.local_reduction_init) + self.local_reduction_stores.splice(main_kernel.local_reduction_stores) + self.non_parallel_reduction_prefix.splice( + main_kernel.non_parallel_reduction_prefix + ) + self.non_parallel_reduction_suffix.splice( + main_kernel.non_parallel_reduction_suffix + ) + + +class OuterLoopFusedKernel(CppKernel): + def __init__(self, kernel_group): + super().__init__(kernel_group.args, kernel_group.ws.num_threads) + self.inner: list[LoopNest] = [] + + def decide_parallel_depth(self, max_parallel_depth, threads): + kernels_parallel_depth = [] + nested_kernels: list[CppKernel] = [ + loop_nest.get_kernel() for loop_nest in self.inner + ] + # TODO(leslie-fang-intel): only enable parallel within all outer loop levels. + for kernel in nested_kernels: + # For any ScalarKernel, VecKernel, or Tile2DKernel, + # they should all have the same call_ranges + call_ranges = kernel.call_ranges + if call_ranges is None: + raise AssertionError("expected call_ranges is not None") + kernels_parallel_depth.append( + kernel.decide_parallel_depth( + ParallelDepth( + parallel_depth=( + len(call_ranges) - max_parallel_depth.start_depth + ), + start_depth=max_parallel_depth.start_depth, + ), + threads, + ).parallel_depth + ) + return ParallelDepth( + parallel_depth=min( + max_parallel_depth.parallel_depth, max(kernels_parallel_depth) + ), + start_depth=max_parallel_depth.start_depth, + ) + + +class ReasonFusedNodes(Enum): + SAME_VARS_REDUCE = "same_vars_reduce" + COMPATIBLE_REDUCTION = "compatible_reduction" + COMPATIBLE_RANGES_NO_REDUCTION = "compatible_ranges_no_reduction" + + +class CppScheduling(BaseScheduling): + # Subclass CppKernelProxy to customize codegen without copying codegen_node(). + # Use kernel_proxy_cls to inject custom proxies in CppScheduling subclasses. + # Avoid duplicating codegen_node() just to swap in a custom kernel proxy class. + kernel_proxy_cls: type[CppKernelProxy] = CppKernelProxy + # ctypes limits the number of args to 1024, refer to: + # https://github.com/python/cpython/commit/a285af7e626d1b81cf09f8b2bf7656f100bc1237 + # We set a conservative threshold here. + MAX_FUSED_KERNEL_ARGS_NUM = 500 + backend_features = OrderedSet( + [ + BackendFeature.INPLACE_BUFFERS, + BackendFeature.REDUCE_TO_SINGLE_ELEMENT, + ] + ) + + @classmethod + def get_backend_features(cls, device: torch.device) -> OrderedSet[BackendFeature]: + return cls.backend_features + + def __init__(self, scheduler): + super().__init__(scheduler) + if scheduler: + self.reset_kernel_group() + self._ready_to_flush = False + + def _set_flush_status(self, status: bool): + self._ready_to_flush = status + + def group_fn(self, sizes): + return tuple(tuple(map(V.graph.sizevars.simplify, s)) for s in sizes) + + def reset_kernel_group(self): + self.kernel_group = KernelGroup() + + def _get_indexing_ranges_exprs(self, node) -> ir.ExtraIndexingConstraints: + if isinstance(node, FusedSchedulerNode): + if len(node.snodes) <= 0: + raise AssertionError(node.snodes) + var_ranges = None + indexing_exprs = OrderedSet[Any]() + for snode in node.snodes: + constraints = self._get_indexing_ranges_exprs(snode) + if var_ranges is None: + var_ranges = constraints.ranges + if var_ranges != constraints.ranges: + raise AssertionError((var_ranges, constraints.ranges, node.snodes)) + indexing_exprs.update(constraints.exprs) + if var_ranges is None: + raise AssertionError("expected at least one snode to set var_ranges") + return ir.ExtraIndexingConstraints(var_ranges, list(indexing_exprs)) + + if not isinstance(node, SchedulerNode): + raise AssertionError("expected isinstance(node, SchedulerNode)") + comp_buffer = node.node + if not isinstance(comp_buffer, ir.ComputedBuffer): + raise AssertionError("expected isinstance(comp_buffer, ir.ComputedBuffer)") + _, body, _ = comp_buffer.get_default_sizes_body() + return ir.ExtraIndexingConstraints( + body.var_ranges, list(body.indexing_exprs.values()) + ) + + def _snapshot_node_loop_states(self, node): + if isinstance(node, SchedulerNode): + return [(node, node.snapshot_loop_state())] + + if not isinstance(node, FusedSchedulerNode): + raise AssertionError("expected isinstance(node, FusedSchedulerNode)") + snapshots = [] + for snode in node.snodes: + if not isinstance(snode, SchedulerNode): + raise AssertionError("expected isinstance(snode, SchedulerNode)") + snapshots.append((snode, snode.snapshot_loop_state())) + return snapshots + + def _align_compatible_range_nodes(self, node1, node2): + if not isinstance(node1, (SchedulerNode, FusedSchedulerNode)): + raise AssertionError( + "expected isinstance(node1, (SchedulerNode, FusedSchedulerNode))" + ) + if not isinstance(node2, (SchedulerNode, FusedSchedulerNode)): + raise AssertionError( + "expected isinstance(node2, (SchedulerNode, FusedSchedulerNode))" + ) + + _, (vars1, reduce1) = node1.group + _, (vars2, reduce2) = node2.group + if not (reduce1 == () and reduce2 == ()): + raise AssertionError((reduce1, reduce2)) + + node_to_recomp = node1 if len(vars1) < len(vars2) else node2 + ref_node = node2 if len(vars1) < len(vars2) else node1 + if not isinstance(node_to_recomp, SchedulerNode): + raise AssertionError("expected isinstance(node_to_recomp, SchedulerNode)") + + ref_indexing_constraints = self._get_indexing_ranges_exprs(ref_node) + node_to_recomp.recompute_size_and_body( + extra_indexing_constraints=ref_indexing_constraints + ) + + _, (vars1, _) = node1.group + _, (vars2, _) = node2.group + if vars1 == vars2: + return True + + node_to_recomp_indexing_constraints = self._get_indexing_ranges_exprs( + node_to_recomp + ) + if isinstance(ref_node, SchedulerNode): + ref_node.recompute_size_and_body( + extra_indexing_constraints=node_to_recomp_indexing_constraints + ) + else: + if not isinstance(ref_node, FusedSchedulerNode): + raise AssertionError( + "expected isinstance(ref_node, FusedSchedulerNode)" + ) + for snode in ref_node.snodes: + if not isinstance(snode, SchedulerNode): + raise AssertionError("expected isinstance(snode, SchedulerNode)") + snode.recompute_size_and_body( + extra_indexing_constraints=node_to_recomp_indexing_constraints + ) + + _, (vars1, _) = node1.group + _, (vars2, _) = node2.group + return vars1 == vars2 + + def fuse(self, node1, node2): + if node1.is_foreach() or node2.is_foreach(): + return ForeachKernelSchedulerNode.fuse(node1, node2) + elif node1.is_template(): + if node2.is_template(): + raise AssertionError("expected not node2.is_template()") + return FusedSchedulerNode.fuse(node1, node2) + else: + if ( + self._why_fuse_nodes(node1, node2) + == ReasonFusedNodes.COMPATIBLE_RANGES_NO_REDUCTION + ): + if not (self._align_compatible_range_nodes(node1, node2)): + raise AssertionError( + ( + node1.group, + node2.group, + ) + ) + return FusedSchedulerNode.fuse(node1, node2) + elif self.can_fuse_vertical_outer_loop(node1, node2): + return OuterLoopFusedSchedulerNode.fuse( + node1, node2, self._get_outer_loop_fusion_depth(node1, node2) + ) + else: + return FusedSchedulerNode.fuse(node1, node2) + + def _why_fuse_nodes(self, node1, node2) -> ReasonFusedNodes | None: + _, (vars1, reduce1) = node1.group + _, (vars2, reduce2) = node2.group + + if vars1 == vars2 and reduce1 == reduce2: + return ReasonFusedNodes.SAME_VARS_REDUCE + if reduce1 == () and vars1 == vars2 + reduce2: + return ReasonFusedNodes.COMPATIBLE_REDUCTION + if self._can_fuse_nodes_with_compatible_ranges(node1, node2): + return ReasonFusedNodes.COMPATIBLE_RANGES_NO_REDUCTION + # TODO(jansel): allow fusion pointwise (vars1, ()) suffix? + return None + + def _can_fuse_nodes_with_compatible_ranges(self, node1, node2): + # Here we try to fuse SchedulerNode/FusedSchedulerNode with compatible ranges + # e.g. (s0, s1, s2) and (s0 * s1 * s2) + _, (vars1, reduce1) = node1.group + _, (vars2, reduce2) = node2.group + + c1 = reduce1 == () and reduce2 == () + c2 = math.prod(vars1) == math.prod(vars2) + c3 = len(vars1) == 1 or len(vars2) == 1 + if not (c1 and c2 and c3): + return False + + node_to_recomp = node1 if len(vars1) < len(vars2) else node2 + ref_node = node2 if len(vars1) < len(vars2) else node1 + + # We can not recompute sizes and body for nodes other than SchedulerNode + # TODO: we can extend fusion support with compatible ranges for FusedSchedulerNode + if isinstance(node_to_recomp, FusedSchedulerNode): + return False + + # It may happen that node1 and node2 compatible number of elements + # but different original ranges, for example: + # {d0: s0, d1: s1, d2: s2} vs {d0: s0*s1*s2} + # See https://github.com/pytorch/pytorch/pull/120077/files#r1500427848 for more details + # TODO: we can fix if it allows us to CSE at least one of the variables + + if not isinstance(node_to_recomp, SchedulerNode): + raise AssertionError("expected isinstance(node_to_recomp, SchedulerNode)") + if isinstance(node_to_recomp.node, ir.TemplateBuffer): + return False + if not isinstance(node_to_recomp.node, ir.ComputedBuffer): + raise AssertionError( + "expected isinstance(node_to_recomp.node, ir.ComputedBuffer)" + ) + # node.data.get_size() is a cheaper version of node.get_read_writes().var_ranges + # but without variable name + ranges2 = node_to_recomp.node.data.get_size() + ranges1 = None + if isinstance(ref_node, FusedSchedulerNode): + ranges_set = OrderedSet[tuple[Any, ...]]() + for snode in ref_node.snodes: + if not isinstance(snode, SchedulerNode): + raise AssertionError("expected isinstance(snode, SchedulerNode)") + if isinstance(snode.node, ir.TemplateBuffer): + break + if not isinstance(snode.node, ir.ComputedBuffer): + raise AssertionError( + "expected isinstance(snode.node, ir.ComputedBuffer)" + ) + ranges_set.add(tuple(snode.node.data.get_size())) + + if len(ranges_set) != 1: + return False + + ranges1 = list(next(iter(ranges_set))) + else: + if not isinstance(ref_node, SchedulerNode): + raise AssertionError("expected isinstance(ref_node, SchedulerNode)") + if not isinstance(ref_node.node, ir.ComputedBuffer): + raise AssertionError( + "expected isinstance(ref_node.node, ir.ComputedBuffer)" + ) + ranges1 = ref_node.node.data.get_size() # type: ignore[assignment] + + if ranges1 != ranges2: + return False + + snapshots = self._snapshot_node_loop_states(node_to_recomp) + snapshots.extend(self._snapshot_node_loop_states(ref_node)) + try: + return self._align_compatible_range_nodes(node1, node2) + finally: + for node, state in reversed(snapshots): + node.restore_loop_state(state) + + def _can_fuse_horizontal_impl(self, node1, node2): + if not ( + isinstance( + node1, (FusedSchedulerNode, SchedulerNode, ExternKernelSchedulerNode) + ) + ): + raise AssertionError( + "expected isinstance( node1, (FusedSchedulerNode, SchedulerNode, Ex..." + ) + if not isinstance(node2, (FusedSchedulerNode, SchedulerNode)): + raise AssertionError( + "expected isinstance(node2, (FusedSchedulerNode, SchedulerNode))" + ) + if any( + isinstance(node, (OuterLoopFusedSchedulerNode, ExternKernelSchedulerNode)) + for node in (node1, node2) + ): + return False + return self._why_fuse_nodes(node1, node2) is not None + + def can_fuse_horizontal(self, node1, node2): + if node1.is_template() or node2.is_template(): + return False + if ( + len(node1.get_nodes()) + len(node2.get_nodes()) + > config.cpp.max_horizontal_fusion_size + ): + return False + + return self._can_fuse_horizontal_impl(node1, node2) + + def can_fuse_multi_outputs_template( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + if template_buf := node1.get_template_node(): + return ( + isinstance(template_buf.layout, ir.MultiOutputLayout) + and isinstance(node2.node, ir.MultiOutput) + and len(node2.node.inputs) == 1 + and node2.node.inputs[0].get_name() == template_buf.name # type: ignore[union-attr] + ) + return False + + def _get_outer_loop_fusion_depth(self, node1, node2): + DISABLE_OUTER_LOOP_FUSION = 0 + if not all( + type(node) + in (OuterLoopFusedSchedulerNode, FusedSchedulerNode, SchedulerNode) + for node in (node1, node2) + ): + return DISABLE_OUTER_LOOP_FUSION + + _node1 = ( + node1.get_outer_nodes()[-1] + if isinstance(node1, OuterLoopFusedSchedulerNode) + else node1 + ) + if not isinstance(_node1, (FusedSchedulerNode, SchedulerNode)): + raise AssertionError( + "expected isinstance(_node1, (FusedSchedulerNode, SchedulerNode))" + ) + _node2 = ( + node2.get_outer_nodes()[0] + if isinstance(node2, OuterLoopFusedSchedulerNode) + else node2 + ) + if not isinstance(_node2, (FusedSchedulerNode, SchedulerNode)): + raise AssertionError( + "expected isinstance(_node2, (FusedSchedulerNode, SchedulerNode))" + ) + + _, (vars1, reduce1) = _node1.group + _, (vars2, reduce2) = _node2.group + if vars1 == () and vars2 == () and reduce1 != () and reduce2 != (): + # Reduction only + return DISABLE_OUTER_LOOP_FUSION + if all(type(node) is OuterLoopFusedSchedulerNode for node in (node1, node2)): + return ( + node1.outer_loop_fusion_depth + if node1.outer_loop_fusion_depth == node2.outer_loop_fusion_depth + else DISABLE_OUTER_LOOP_FUSION + ) + outer_loop_fusion_depth = min(len(vars1), len(vars2)) + if ( + outer_loop_fusion_depth >= 1 + and vars1[:outer_loop_fusion_depth] == vars2[:outer_loop_fusion_depth] + ): + if any( + type(node) is OuterLoopFusedSchedulerNode for node in (node1, node2) + ): + _compare_node = ( + node1 if type(node1) is OuterLoopFusedSchedulerNode else node2 + ) + if _compare_node.outer_loop_fusion_depth == outer_loop_fusion_depth: + # Same outer loop fusion depth as prev nodes in OuterLoopFusedSchedulerNode + return outer_loop_fusion_depth + else: + return DISABLE_OUTER_LOOP_FUSION + else: + # First 2 nodes to generate OuterLoopFusedSchedulerNode + return outer_loop_fusion_depth + return DISABLE_OUTER_LOOP_FUSION + + def can_fuse_vertical_outer_loop(self, node1, node2): + return ( + not node1.is_template() + and not node2.is_template() + and node1.get_operation_names() & node2.ancestors + and not ( + self._can_fuse_horizontal_impl(node1, node2) + and not node1.is_reduction() + ) + and self._get_outer_loop_fusion_depth(node1, node2) >= 1 + ) + + def get_fusion_pair_priority(self, node1, node2): + if self.can_fuse_vertical_outer_loop(node1, node2): + # Outer loop fusion with lower priority + return 1 + else: + return 0 + + def can_fuse_vertical(self, node1, node2): + if node2.is_template(): + # TODO(jgong5): support pre-op fusion with template + return False + if node1.is_template(): + template_fusion_supported, _ = template_fusion_with_epilogues_supported( + node1, [node2] + ) + return not node2.is_reduction() and template_fusion_supported + return ( + self._can_fuse_horizontal_impl(node1, node2) and not node1.is_reduction() + ) or self.can_fuse_vertical_outer_loop(node1, node2) + + def try_loop_split(self, nodes: list[SchedulerNode]): + """ + Apply loop split optimization. + When one of the indexing_exprs contains a division, we eliminate the division by splitting the loop + to avoid non-contiguous loads, subject to the following conditions: + 1. No reduction and no mudular index for all nodes. + 2. The indexing_exprs of all nodes contain only one (or more, but all the same) division, + where the divisor is an integer and not too small (the divisor > 8), the dividend is + one of the iter_vars, and this var, i.e. the dimension that needs to be split, is + contiguous in all other indexing_exprs. + + For example, if the node's var_ranges: {z0: 2, z1: 9216, z2: 960} and indexing_exprs: + {'index0': 8847360*z0 + 960*z1 + z2, 'index1': 32*z0 + (z2//30), 'index2': z2}, + we will split z2 -> 30*z2 + z3, then the node's var_ranges will be changed to + {z0: 2, z1: 9216, z2: 32, z3: 30} and indexing_exprs will be changed to + {'index0': 8847360*z0 + 960*z1 + 30*z2 + z3, 'index1': 32*z0 + z2, 'index2': 30*z2 + z3}. + """ + + # No reduction and no mudular + if any( + len(node.group[1][1]) != 0 + or any( + expr.has(ModularIndexing) for expr in node._body.indexing_exprs.values() + ) + for node in nodes + ): + return nodes + + split_var = None + split_number = None + num_div = 0 + div_expr_ = None + match_div = False + matched_index_size = None + + # Collect node info for later compatibility check + node_bodies: list[tuple[Any, Any]] = [] + + for node in nodes: + if not isinstance(node.node, ir.ComputedBuffer): + raise AssertionError( + "expected isinstance(node.node, ir.ComputedBuffer)" + ) + sizes_body = node.node.get_default_sizes_body() + node_bodies.append((node, sizes_body)) + (index_size, _), original_body, _ = sizes_body + for name, expr in original_body.indexing_exprs.items(): + if not isinstance(expr, sympy.Expr): + continue + for div_expr in expr.find(FloorDiv): + if ( + any(div_expr.has(var) for var in original_body.iter_vars) + and div_expr != div_expr_ + ): + div_expr_ = div_expr + num_div += 1 + if num_div > 1: + return nodes + if ( + isinstance(div_expr.args[1], sympy.core.numbers.Integer) + and div_expr.args[0] in original_body.iter_vars + and name is not None + and all( + stride_at_vec_range(expr_, div_expr.args[0]) in (0, 1) + for name_, expr_ in original_body.indexing_exprs.items() + if name_ != name + ) + and div_expr.args[1] > 8 + ): + split_var = div_expr.args[0] + split_number = div_expr.args[1] + match_div = True + matched_index_size = index_size + + # Only one node contains a division, and the split dimension is contiguous in all other indexing_exprs. + if not match_div: + return nodes + + # Check if all nodes have split_var in their iter_vars and have compatible sizes + # (same number of index dimensions). If not, bail out to avoid incompatible + # var_ranges after loop split which would cause assertion failures in + # simplify_and_reorder or codegen_functions. + if matched_index_size is None: + raise AssertionError("expected matched_index_size is not None") + matched_num_dims = len(matched_index_size) + + for node, ((index_size, _), original_body, _) in node_bodies: + if split_var not in original_body.iter_vars: + return nodes + if len(index_size) != matched_num_dims: + return nodes + + def loop_split(sizes, body, vars): + index_size, reduce_size = sizes + index_vars, reduce_vars = vars + split_idx = index_vars.index(split_var) + new_index_size = index_size.copy() + new_index_size[split_idx] = index_size[split_idx] // split_number + new_index_size.insert(split_idx + 1, split_number) + (new_index_vars, _), var_ranges = dependencies.index_vars_no_squeeze( + new_index_size, reduce_size, prefix="y" + ) + iter_vars = new_index_vars.copy() + divisor_var = iter_vars.pop(split_idx + 1) + iter_vars[split_idx] = split_number * iter_vars[split_idx] + divisor_var + body = ir.LoopBody( + body, [iter_vars, reduce_vars], var_ranges, new_index_vars, reduce_vars + ) + return ( + (new_index_size, reduce_size), + body, + (new_index_vars, reduce_vars), + ) + + extra_indexing_ranges = None + extra_indexing_exprs = OrderedSet[Any]() + for _, sizes_body in node_bodies: + _, split_body, _ = loop_split(*sizes_body) + if extra_indexing_ranges is None: + extra_indexing_ranges = split_body.var_ranges + if extra_indexing_ranges != split_body.var_ranges: + raise AssertionError( + ( + extra_indexing_ranges, + split_body.var_ranges, + ) + ) + extra_indexing_exprs.update(split_body.indexing_exprs.values()) + + if extra_indexing_ranges is None: + raise AssertionError("extra_indexing_ranges is None") + extra_indexing_constraints = ir.ExtraIndexingConstraints( + extra_indexing_ranges, + list(extra_indexing_exprs), + ) + + snapshots = [(node, node.snapshot_loop_state()) for node in nodes] + for node in nodes: + node.recompute_size_and_body( + extra_indexing_constraints=extra_indexing_constraints, + recompute_sizes_body_func=loop_split, + ) + + # Keep the post-split leaves compatible with CppKernelProxy.codegen_functions. + # If simplification still picks different loop factorizations, skip this + # optional optimization and codegen the original fused pointwise group. + group = nodes[0].group[1] + if any(node.group[1] != group for node in nodes[1:]): + for node, state in reversed(snapshots): + node.restore_loop_state(state) + + return nodes + + def codegen_outer_loop_node( + self, + node: OuterLoopFusedSchedulerNode, + ): + """ + Generate the code for the outer loop fused scheduler node. + 1. Codegen with fused outer loop: depends on the analysis of + the outer loop fused scheduler node, with or without the local buffer. + 2. If failed, fallback to standard codegen. + """ + kernel_group = self.kernel_group + generated_cpp_vec_kernel_count = metrics.generated_cpp_vec_kernel_count + cpp_kernel_proxy_list: list[self.kernel_proxy_cls] = [] # type: ignore[name-defined] + nodes_list: list[list[SchedulerNode]] = [] + if not isinstance(node, OuterLoopFusedSchedulerNode): + raise AssertionError( + "expected isinstance(node, OuterLoopFusedSchedulerNode)" + ) + + def try_outer_loop_fusion_with_local_buf(node: OuterLoopFusedSchedulerNode): + """ + Codegen code with fused outer loop and local Buffer. + """ + if not isinstance(node, OuterLoopFusedSchedulerNode): + raise AssertionError( + "expected isinstance(node, OuterLoopFusedSchedulerNode)" + ) + cpp_kernel_proxy_list.clear() + nodes_list.clear() + + def get_call_ranges(node: BaseSchedulerNode): + if not isinstance(node, (SchedulerNode, FusedSchedulerNode)): + raise AssertionError( + "expected isinstance(node, (SchedulerNode, FusedSchedulerNode))" + ) + nodes: list[SchedulerNode] = node.get_nodes() # type: ignore[assignment] + _, (group, reduction_group) = max( + nodes, key=lambda x: int(x.is_reduction()) + ).group + call_ranges = tuple(group) + tuple(reduction_group) + return call_ranges + + local_buffers: list[ir.Buffer] = [] + # Map local buffer name to a list of global buffers + local_to_global_buffers: dict[str, list[ir.Buffer]] = {} + if all( + len(get_call_ranges(_node)) == node.outer_loop_fusion_depth + 1 + for _node in node.get_outer_nodes() + ): + # Ref to the typical case of local buffer in + # https://github.com/pytorch/pytorch/blob/1115a25c36340554442f28f9570abd42f0aface2/aten/src/ATen/native/cpu/SoftMaxKernel.cpp#L159 + # where the buffer is with size of last dim and contiguous. + # Only support this typical case at first. + visited_scheduler_nodes: OrderedSet[str] = OrderedSet() + for scheduler_node in node.get_nodes(): + # all users inside same OuterLoopFusedSchedulerNode + if not isinstance(scheduler_node, SchedulerNode): + raise AssertionError( + "expected isinstance(scheduler_node, SchedulerNode)" + ) + visited_scheduler_nodes.add(scheduler_node.get_name()) + if ( + scheduler_node.is_reduction() + or len(scheduler_node.get_outputs()) != 1 + ): + continue + + scheduler_buffer = scheduler_node.get_outputs()[0] + if all( + user.node in node.get_nodes() for user in scheduler_buffer.users + ): + global_buffer = scheduler_buffer.node + if not isinstance(global_buffer, ir.ComputedBuffer): + raise AssertionError( + "expected isinstance(global_buffer, ir.ComputedBuffer)" + ) + global_buffer_layout = global_buffer.get_layout() + size_offset = node.outer_loop_fusion_depth - len( + get_call_ranges(scheduler_node) + ) + + def is_all_write_read_contiguous(): + contiguous_index_expr = 0 + stride = 1 + for var, range in reversed( + # pyrefly: ignore [missing-attribute] + scheduler_node._body.var_ranges.items() + ): + contiguous_index_expr += stride * var + stride *= range + # pyrefly: ignore [missing-attribute] + write_index_expr = scheduler_node._body.get_write_expr( + scheduler_buffer.get_name() + ) + + def is_contiguous_index(x): + return x == contiguous_index_expr + + return is_contiguous_index(write_index_expr) and all( + isinstance(user.node, SchedulerNode) + and is_contiguous_index( + user.node._body.get_read_expr( + scheduler_buffer.get_name() + ), + ) + for user in scheduler_buffer.users + ) + + if not ( + global_buffer_layout.is_contiguous() + and is_all_write_read_contiguous() + ): + continue + # Local Buffer is a view of global buffer + local_buffer_stride: list[int] = [] + stride = global_buffer_layout.stride[-1] + local_buffer_size = get_call_ranges(scheduler_node)[ + size_offset: + ] + for sz in reversed(local_buffer_size): + local_buffer_stride.insert(0, stride) + stride *= sz + local_buffer_layout = ir.FixedLayout( + global_buffer_layout.device, + global_buffer_layout.dtype, + local_buffer_size, + local_buffer_stride, + ) + + def try_share_local_buffer(local_buffer_layout, local_buffers): + for local_buf in local_buffers: + if local_buffer_layout == local_buf.layout and all( + all( + user.node.get_name() in visited_scheduler_nodes + for user in V.graph.scheduler.name_to_buf[ + global_buffer.name + ].users + ) + for global_buffer in local_to_global_buffers[ + local_buf.name + ] + if global_buffer.name is not None + ): + return local_buf + return None + + local_buf_prefix = "local_buffer_data" + # Share existing local buffer + local_buffer_used = try_share_local_buffer( + local_buffer_layout, local_buffers + ) + if not local_buffer_used: + # Create new local buffer + local_buffer_used = ir.Buffer( + name=f"{local_buf_prefix}_{len(local_buffers)}", + layout=local_buffer_layout, + ) + local_buffers.append(local_buffer_used) + local_to_global_buffers[local_buffer_used.name] = [] # type: ignore[index] + + local_to_global_buffers[local_buffer_used.name].append( + global_buffer, + ) + + with LocalBufferContext(kernel_group.args) as scope: + if len(local_buffers) > 0: + for local_buffer in local_buffers: + if local_buffer.name is None: + raise AssertionError( + "expected local_buffer.name is not None" + ) + scope.add_local_buffer( + local_buffer, local_to_global_buffers[local_buffer.name] + ) + for _node in node.get_outer_nodes(): + if not isinstance(_node, (FusedSchedulerNode, SchedulerNode)): + raise AssertionError( + "expected isinstance(_node, (FusedSchedulerNode, SchedulerNode))" + ) + cpp_kernel_proxy = self.kernel_proxy_cls(kernel_group) + cpp_kernel_proxy.codegen_nodes(_node.get_nodes()) # type: ignore[arg-type] + cpp_kernel_proxy_list.append(cpp_kernel_proxy) + nodes_list.append(_node.get_nodes()) # type: ignore[arg-type] + + def fallback_without_local_buffers() -> Literal[False]: + for removed_buffer in scope.removed_buffers: + # Restore the removed buffers by this context before + # fallback to codegen without using Local Buffer. + V.graph.removed_buffers.remove(removed_buffer) + return False + + # Local buffers omit fused outer dimensions. If an omitted + # outer loop is tiled, one local buffer slot would be reused for + # multiple outer elements in the same loop iteration. + def has_tiled_fused_outer_loop() -> bool: + for cpp_kernel_proxy in cpp_kernel_proxy_list: + loop_nest = cpp_kernel_proxy.loop_nest + if loop_nest is None: + raise AssertionError("expected loop_nest is not None") + loops = loop_nest.loops + if loops is None: + raise AssertionError("expected loops is not None") + for loop in loops[: node.outer_loop_fusion_depth]: + if loop.steps != sympy.S.One: + return True + return False + + if len(local_buffers) > 0 and has_tiled_fused_outer_loop(): + return fallback_without_local_buffers() + + if not node.check_outer_fusion_loop_level_attr( + cpp_kernel_proxy_list, node.outer_loop_fusion_depth + ): + return fallback_without_local_buffers() + metrics.cpp_outer_loop_fused_inner_counts.append( + metrics.CppOuterLoopFusedCount( + len(cpp_kernel_proxy_list), + local_buffer_number=len(scope.local_buffers), + ) + ) + outer_fusion_cpp_kernel_proxy = node.merge_outer_fusion_kernels( + cpp_kernel_proxy_list, + ) + kernel_group.finalize_kernel( + outer_fusion_cpp_kernel_proxy, + [*itertools.chain.from_iterable(nodes_list)], + ) + + return True + + if not try_outer_loop_fusion_with_local_buf(node): + # Reset generated_cpp_vec_kernel_count to codegen again + metrics.generated_cpp_vec_kernel_count = generated_cpp_vec_kernel_count + cpp_kernel_proxy_list.clear() + nodes_list.clear() + # Similar as comment in + # https://github.com/pytorch/pytorch/blob/469383755fe416eb1c41fa724762ad3eaecdff07/torch/_inductor/codegen/cpp.py#L3269-L3272 + # Kernels share the same global contexts like V.graph.wrapper_code, V.kernel.args. + with torch._inductor.config.patch(inplace_buffers=False): + for _node in node.get_outer_nodes(): + if not isinstance(_node, (FusedSchedulerNode, SchedulerNode)): + raise AssertionError( + "expected isinstance(_node, (FusedSchedulerNode, SchedulerNode))" + ) + _nodes: list[SchedulerNode] = _node.get_nodes() # type: ignore[assignment] + cpp_kernel_proxy = self.kernel_proxy_cls(kernel_group) + cpp_kernel_proxy.codegen_nodes(_nodes) + kernel_group.finalize_kernel(cpp_kernel_proxy, _nodes) + + def codegen_node( + self, + node: OuterLoopFusedSchedulerNode | FusedSchedulerNode | SchedulerNode, + ): + """ + Turn a set of pre-fused nodes into a C++ kernel. + """ + kernel_group = self.kernel_group + + if isinstance(node, OuterLoopFusedSchedulerNode): + self.codegen_outer_loop_node(node) + else: + nodes: list[SchedulerNode] = node.get_nodes() # type: ignore[assignment] + nodes = self.try_loop_split(nodes) + cpp_kernel_proxy = self.kernel_proxy_cls(kernel_group) + cpp_kernel_proxy.codegen_nodes(nodes) + kernel_group.finalize_kernel(cpp_kernel_proxy, nodes) + + args_num = self._get_scheduled_num_args() + if args_num > CppScheduling.MAX_FUSED_KERNEL_ARGS_NUM: + self._set_flush_status(True) + + def is_cpp_template(self, node: BaseSchedulerNode) -> bool: + return isinstance(node, SchedulerNode) and isinstance( + node.node, ir.CppTemplateBuffer + ) + + def codegen_template( + self, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + prologue_nodes: Sequence[BaseSchedulerNode], + ): + """ + Codegen a CPP template, possibly with fused epilogues + """ + if prologue_nodes: + raise AssertionError("expected not prologue_nodes") + + # remove MultiOutput from epilogue_nodes + epilogue_nodes = [ + epilogue_node + for epilogue_node in epilogue_nodes + if isinstance(epilogue_node, (SchedulerNode, FusedSchedulerNode)) + ] + # The counter cpp_templated_kernel_counter is used for verifying if a + # a templated kernel was successfully compiled in a UT + counters["inductor"]["cpp_templated_kernel_counter"] += 1 + counters["inductor"]["cpp_epilogue_fusion_counter"] += len(epilogue_nodes) + if not (self.is_cpp_template(template_node)): + raise AssertionError( + "Template node passed to CppScheduler.codegen_template must be a SchedulerNode that wraps a CppTemplateBuffer" + ) + template_node = cast(SchedulerNode, template_node) + _, (_, rnumel) = template_node.group + if rnumel != (): + raise AssertionError("expected rnumel == ()") + ctb: ir.CppTemplateBuffer = cast(ir.CppTemplateBuffer, template_node.node) + epilogue_ir_nodes: list[ir.Operation | None] = [n.node for n in epilogue_nodes] + if not (all(isinstance(n, ir.ComputedBuffer) for n in epilogue_ir_nodes)): + raise AssertionError( + "Epilogue nodes must all be instances of ir.ComputedBuffer" + ) + + def template_buffer_has_other_users( + template_buffer, outputs_by_name, epilogue_nodes + ): + if not epilogue_nodes: + return False + + if template_buffer.get_name() not in outputs_by_name: + raise AssertionError( + "expected template_buffer.get_name() in outputs_by_name" + ) + users = outputs_by_name[template_buffer.get_name()].users + return not all( + isinstance(user.node, BaseSchedulerNode) + and user.node.node in epilogue_nodes + for user in users + ) + + flag_template_buffer_has_other_users = template_buffer_has_other_users( + ctb, template_node.outputs_by_name, epilogue_ir_nodes + ) + kernel, render = ctb.make_kernel_render( # type: ignore[misc] + ctb, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_ir_nodes, + ) + with kernel: + if not is_multi_outputs_template(template_node.node): + template_node.mark_run() # type: ignore[attr-defined] + for node in epilogue_nodes: + node.mark_run() # type: ignore[attr-defined] + src_code = render() + + with V.set_kernel_handler(kernel): + node_schedule = [template_node, *epilogue_nodes] + kernel_name = self.define_kernel(src_code, node_schedule, kernel.args) + + if is_multi_outputs_template(template_node.node): + # For multi outputs template, allocate buffers for each output after the epilogue + # codegen to which determines if the buffer has been removed. + if len(template_node.outputs) != 1: + raise AssertionError( + "Multi outputs template should be with 1 output template buffer of MultiOutputLayout" + ) + for user in template_node.outputs[0].users: + if not isinstance(user.node, ExternKernelSchedulerNode): + raise AssertionError( + "Multi outputs template should be with ExternKernelSchedulerNode" + ) + if not isinstance(user.node.node, ir.MultiOutput): + raise AssertionError( + "Multi outputs template has multi users with MultiOutput" + ) + user.node.mark_run() + + 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() + + def _get_scheduled_num_args(self): + return self.kernel_group.get_num_args() + + def ready_to_flush(self): + return self._ready_to_flush + + def codegen_sync(self): + pass + + def define_kernel(self, src_code, nodes, kernel_args=None): + 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(nodes, config.cpp.descriptive_names) + if config.cpp.descriptive_names + else "" + ) + kernel_name = "_".join(["cpp", fused_name, wrapper.next_kernel_suffix()]) + wrapper.src_to_kernel[src_code] = kernel_name + kernel_decl_name = kernel_name if V.graph.cpp_wrapper else "kernel" + src_code = src_code.replace(str(Placeholder.KERNEL_NAME), kernel_decl_name) + src_code = src_code.replace(str(Placeholder.DESCRIPTIVE_NAME), kernel_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", "//") + + # Get the lines in the source code representing the function definition, + # excluding the first line including cpp_prefix.h. + first_char = src_code.rfind('extern "C"') + last_char = src_code.find(")", first_char) + if _IS_WINDOWS: + # get_export_declaration introduced one more ')' in Windows + last_char = src_code.find(")", last_char + 1) + kernel_definition = f"{src_code[first_char : last_char + 1]};\n" + + compile_wrapper = IndentedBuffer() + args = self.kernel_group.args if kernel_args is None else kernel_args + _, _, arg_types = args.cpp_argdefs() + if not V.graph.cpp_wrapper: + compile_wrapper.writeline( + f"async_compile.cpp_pybinding({arg_types!r}, r'''" + ) + compile_wrapper.splice(src_code, strip=True) + if not V.graph.cpp_wrapper: + compile_wrapper.writeline("''')") + wrapper.define_kernel( + kernel_name, + compile_wrapper.getvalue(), + gpu=False, + cpp_definition=kernel_definition, + ) + return kernel_name + + def flush(self): + src_code = self.kernel_group.codegen_group() + if src_code: + kernel_name = self.define_kernel( + src_code, self.kernel_group.scheduled_nodes + ) + self.codegen_comment(self.kernel_group.scheduled_nodes, 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_name, + self.kernel_group.scheduled_nodes, # type: ignore[arg-type] + ) + self.kernel_group.call_kernel(V.graph.wrapper_code, kernel_name) + if config.cpp.enable_kernel_profile: + V.graph.wrapper_code.write_kernel_context_guard_end() + + self.reset_kernel_group() + self._set_flush_status(False) + + def codegen_comment(self, node_schedule, kernel_name=None): + # below add provenance tracing info for cpu CppKernel types + wrapper = V.graph.wrapper_code + debug_handle = set_kernel_post_grad_provenance_tracing( + node_schedule, # type: ignore[arg-type] + # pyrefly: ignore [bad-argument-type] + kernel_name, + ) + wrapper.write_provenance_debug_handle(kernel_name, debug_handle) + + +class KernelGroup: + def __init__(self): + super().__init__() + self.args = KernelArgs() + self.loops_code = BracesBuffer() + self.ws = WorkSharing(self.loops_code) + self.stack = contextlib.ExitStack() + self.stack.enter_context(self.ws) + self.scheduled_nodes = [] + + def new_kernel(self, cls, *args): + return cls(self.args, parallel_num_threads(), *args) + + def finalize_kernel(self, new_kernel, nodes): + self.scheduled_nodes += nodes + code = self.loops_code + ws = self.ws + new_kernel.codegen_loops(code, ws) + + def get_num_args(self): + arg_defs, _call_args, _arg_types = self.args.cpp_argdefs() + args_num = len(arg_defs) + return args_num + + def codegen_group(self, name=None) -> str: + self.stack.close() + if not self.scheduled_nodes: + return "" + code = BracesBuffer() + # 1. Include header files + # TODO: support kernel profile on other platforms + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + if enable_kernel_profile: + code.writelines(["#include "]) + code.writeline("#include ") + + # 2. Function definition + kernel_decl_name = str(Placeholder.KERNEL_NAME) if name is None else name + kernel_name = str(Placeholder.DESCRIPTIVE_NAME) if name is None else name + arg_defs, _, _ = self.args.cpp_argdefs() + arg_defs = ",\n".ljust(25).join(arg_defs) + func_export_decl = get_export_declaration() + inline_attr = ( + "C10_ALWAYS_INLINE_ATTRIBUTE" if config.cpp.force_inline_kernel else "" + ) + code.writeline( + f'extern "C" {func_export_decl} void {inline_attr} {kernel_decl_name}({arg_defs})' + ) + + # 3. Function body + with code.indent(): + code.writeline("std::atomic inductor_cpu_integer_div_error{0};") + code.writeline( + "inductor_cpu_integer_div_error_flag = &inductor_cpu_integer_div_error;" + ) + if enable_kernel_profile: + graph_id = V.graph.graph_id + prefix = "graph_" + str(graph_id) + "_" if graph_id is not None else "" + code.writelines( + [ + ( + "torch::aot_inductor::RAIIAtenRecordFunctionHandle " + f'record_{prefix + kernel_name}_("{prefix + kernel_name}", nullptr);' + ) + ] + ) + for old, new in self.args.aliases(): + code.writeline(f"auto {old} = {new};") + code.splice(self.loops_code) + code.writeline("inductor_cpu_integer_div_error_flag = nullptr;") + code.writeline( + "inductor_cpu_throw_if_integer_div_error(inductor_cpu_integer_div_error);" + ) + return code.getvalue() + + def call_kernel(self, wrapper, kernel_name): + _, call_args, arg_types = self.args.cpp_argdefs() + wrapper.generate_kernel_call( + kernel_name, + call_args, + triton=False, + arg_types=arg_types, + ) + + +class WorkSharing: + def __init__(self, code): + self.code = code + self.in_parallel = False + self.num_threads = None + self.stack = contextlib.ExitStack() + + def parallel(self, threads): + if self.in_parallel and threads != self.num_threads: + # wrong number of threads + self.close() + if not self.in_parallel: + self.num_threads = threads + self.in_parallel = True + # Decide whether to use dynamic threading + use_dynamic = False + if config.cpp.threads >= 1: + # User explicitly set config.cpp.threads (hardcode it) + use_dynamic = False + elif threads == os.cpu_count(): + # Thread count matches system CPU count (most likely default, use dynamic) + use_dynamic = True + else: + # Thread count differs from system (user probably set it so hardcode) + use_dynamic = False + + if use_dynamic or config.cpp.dynamic_threads: + self.code.writeline("#pragma omp parallel") + else: + self.code.writeline(f"#pragma omp parallel num_threads({threads})") + self.stack.enter_context(self.code.indent()) + self.code.writeline( + "int tid = omp_get_thread_num();", + ) + + def single(self): + if self.in_parallel: + self.code.writeline("#pragma omp single") + return self.in_parallel + + def close(self): + self.stack.close() + self.in_parallel = False + + def __enter__(self): + self.stack.__enter__() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.stack.__exit__(exc_type, exc_val, exc_tb) + + +@dataclasses.dataclass +class LoopLevel: + var: sympy.Expr | None = None + size: sympy.Expr | None = None + offset: sympy.Expr = sympy.S.Zero + # Note [tiled_size] + # We may do loop-tiling at this loop level. + # When var is in [offset, tiled_size), we will perform the vectorization kernel. + # When var is in [tiled_size, size), we will perform the scalar or masked vectorization kernel. + # for (var = offset; var < size; var += steps) { + # if (var >= offset && var < tiled_size) vec_loop_body(); + # if (var >= tiled_size && var < size) scalar_or_maskvec_loop_body(); + # } + tiled_size: sympy.Expr = sympy.S.Zero + steps: sympy.Expr = sympy.S.One + parallel: int = 0 + simd_omp: bool = False + simd_vec: bool = False + collapsed: bool = False + is_reduction: bool = False + + def __post_init__(self): + # Regarding the C++/OpenMP backend, `cpu_vec_isa.pick_vec_isa()` to check + # vectorization ISA is a time-consuming and one-shot operation. It leads + # to taking a longer time to import `codegen.cpp` package because the + # `LoopLevel` of the package is decorated by `@dataclasses.dataclass` while + # the decorator will invoke `cpu_vec_isa.pick_vec_isa()` to initialize the + # `simd_nelements` of the `LoopLevel`. It might introduce additional compilation + # overhead to the Triton backend. Therefore, we moved the `simd_nelements` to + # `__post_init__` + picked_vec_isa: cpu_vec_isa.VecISA = cpu_vec_isa.pick_vec_isa() + self.simd_nelements: int = picked_vec_isa.nelements() if picked_vec_isa else 0 + + def tile(self, factor): + sympy_factor = sympy.Integer(factor) + loop = LoopLevel(self.var, self.size) + loop.steps = sympy_factor + loop.simd_vec = True + loop.tiled_size = FloorDiv(loop.size, sympy_factor) * sympy_factor + loop.parallel = self.parallel + loop.collapsed = False + loop.is_reduction = self.is_reduction + return loop + + def lines(self): + offset_expr = cexpr_index(self.offset) + size_expr = cexpr_index(self.size) + if config.cpp.no_redundant_loops and offset_expr == size_expr: + return None + simd = ( + f"simd simdlen({self.simd_nelements}) " + if self.simd_omp and self.simd_nelements > 1 + else "" + ) + if self.parallel: + # TODO(jansel): look into chunk size and other schedules + line1 = "#pragma omp for" + if self.parallel > 1: + line1 += f" collapse({self.parallel})" + if self.simd_omp: + line1 = line1.replace(" for ", f" for {simd}") + elif self.simd_vec: + line1 = "" + elif self.simd_omp: + line1 = f"#pragma omp {simd}" + elif not self.is_reduction and cpp_builder.is_gcc(): + line1 = "#pragma GCC ivdep" + else: + line1 = "" + offset_str = f"{INDEX_TYPE} {self.var}={offset_expr}" + size_str = f"{self.var}<{size_expr}" + if self.steps.is_number: + steps_str = f"{self.var}+={cexpr_index(self.steps)}" + else: + # If the step size is 0, change it to 1 because a step size of 0 + # will cause floating point exception (core dump) during parallelization. + steps_str = ( + f"{self.var}+=({cexpr_index(self.steps)} == 0 ? " + f"1 : {cexpr_index(self.steps)})" + ) + line2 = f"for({offset_str}; {size_str}; {steps_str})" + if self.collapsed or not line1: + return [line2] + return [line1, line2] + + +@dataclasses.dataclass +class LoopNest: + """ + A loop-nest-like structure. It is built with the `build` method + as a loop nest and then will perform loop-tiling at some depth. + + A typical case is for vectorization, where we typically do loop-tiling + at the innermost loop level. A more complicated case is when we do + 2D tiling at both the innermost and outer levels. + """ + + loops: list[LoopLevel] | None = None + kernel: CppKernel | None = None + + @staticmethod + def build(kernel: CppKernel): + """Build a LoopNest with the given `kernel` as the leaf""" + itervars = kernel.itervars + ranges = kernel.ranges + reduction_depth = kernel.reduction_depth + if reduction_depth is None: + raise AssertionError("expected reduction_depth is not None") + + loops: list[LoopLevel] | None = None + for loop_idx, (var, size) in enumerate(zip(itervars, ranges)): + loop = LoopLevel(var, size) + if not loops: + loops = [loop] + else: + loops.append(loop) + if loop_idx >= reduction_depth: + loop.is_reduction = kernel.is_reduction + + loop_nest = LoopNest(loops) + return loop_nest + + def __bool__(self): + return bool(self.loops) + + @cache_on_self + def max_parallel_depth(self): + """ + Maximal allowed depth for parallelism: All reduction or non-reduction levels. + When the range of the first inner loop beyond the maximum parallel depth is much + larger than the range of all outer loops within the maximum parallel depth, + change the starting depth of parallelism to the first inner loop and recalculate + the maximum parallel depth. + """ + if self.loops is None: + return ParallelDepth(parallel_depth=0, start_depth=0) + + start_depth = 0 + max_depth = 0 + is_reduction = self.loops[0].is_reduction + num_steps = sympy.Integer(1) + for loop in self.loops: + if loop.is_reduction != is_reduction: + break + num_steps = num_steps * FloorDiv(loop.size, loop.steps) + max_depth += 1 + + def get_simd_vec_depth(loops): + # Return the first loop level which is simd_vec + for i, loop in enumerate(loops): + if loop.simd_vec: + return i + return None + + simd_vec_depth = get_simd_vec_depth(self.loops) + + def has_scalar_kernel(loop_nest: LoopNest): + if not isinstance(loop_nest.kernel, CppKernelProxy): + raise AssertionError( + "expected isinstance(loop_nest.kernel, CppKernelProxy)" + ) + return any( + not isinstance(kernel, CppVecKernel) + for kernel in loop_nest.kernel.kernels + ) + + # When the number of steps of the first inner loop is much larger than the number of steps of + # all outer loops, change `start_depth` to the first inner loop and recalculate `max_depth`. + if ( + max_depth < len(self.loops) + and isinstance(num_steps, sympy.Integer) + and isinstance(self.loops[max_depth].size, sympy.Integer) + and num_steps * 300 + < FloorDiv(self.loops[max_depth].size, self.loops[max_depth].steps) + and not ( + # Disable parallel reduction under the vec loop + simd_vec_depth is not None + and max_depth > simd_vec_depth + and self.loops[max_depth].is_reduction + and has_scalar_kernel(self) + ) + ): + start_depth = max_depth + max_depth = 0 + is_reduction = self.loops[start_depth].is_reduction + for i in range(start_depth, len(self.loops)): + if self.loops[i].is_reduction != is_reduction: + break + max_depth += 1 + return ParallelDepth(parallel_depth=max_depth, start_depth=start_depth) + + def mark_parallel(self, par_depth): + if par_depth.parallel_depth > self.max_parallel_depth().parallel_depth: + raise AssertionError( + "Parallel depth cannot exceed the maximal allowed parallel depth" + ) + if self.loops is None: + raise AssertionError("expected self.loops is not None") + if len(self.loops) < par_depth.parallel_depth: + raise AssertionError("expected len(self.loops) >= par_depth.parallel_depth") + loop = self.loops[par_depth.start_depth] + loop.parallel = par_depth.parallel_depth + if loop.is_reduction: + # pyrefly: ignore [bad-assignment] + metrics.parallel_reduction_count += 1 + for i in range(par_depth.start_depth + 1, par_depth.parallel_depth): + self.loops[i].collapsed = True + + def tile(self, depth, factor): + """ + Do loop-tiling at the `depth` level with `factor`. + for (x0 = 0; x0 < x0_end; x0++) + -> + for (x0 = 0; x0 < x0_end; x0 += factor) + See details in Note [tiled_size]. + """ + if not self.loops: + raise AssertionError("expected self.loops") + self.loops[depth] = self.loops[depth].tile(factor) + return self.loops[depth] + + def get_kernel(self) -> CppKernel: + if not self.kernel: + raise AssertionError("expected self.kernel") + return self.kernel + + def set_kernel(self, kernel): + self.kernel = kernel + + def from_loop_level(self, level: int): + if not self.loops: + raise AssertionError("expected self.loops") + if len(self.loops) < level: + raise AssertionError("expected len(self.loops) >= level") + loops = None if level == len(self.loops) else self.loops[level:] + return LoopNest(loops, self.kernel) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_bmm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_bmm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..1c8d324a13dee32dd1a0168e6374d8880d568511 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_bmm_template.py @@ -0,0 +1,270 @@ +# mypy: allow-untyped-defs +import contextlib +import itertools +from collections.abc import Callable +from typing import Any +from unittest.mock import patch + +import sympy + +from .. import ir +from ..select_algorithm import PartialRender +from ..virtualized import V +from .common import ArgName +from .cpp_gemm_template import CppGemmTemplate, GEMM_TEMPLATE +from .cpp_micro_gemm import LayoutType +from .cpp_template_kernel import CppTemplateKernel +from .cpp_utils import DTYPE_TO_CPP, GemmBlocking + + +# We pass all sizevars present in BY to the GEMM templates so variables are not renamed in the BMM definition +GEMM_SINGLE_THREAD_MM_STUB = r""" +{{kernel.def_kernel( + inputs={"X": X, "W": W}, + outputs={"Y": Y_2d}, + aliases=aliases, + function_name=kernel_name+"_single_thread_mm", + extra_sizevars=BY_sizevars + [b_index], + placeholder="")}}""" + +GEMM_THREADED_MM_STUB = r""" +{{kernel.def_kernel( + inputs={"X": X, "W": W}, + outputs={"Y": Y_2d}, + aliases=aliases, + function_name=kernel_name+"_threaded_mm", + extra_sizevars=BY_sizevars + [b_index], + placeholder="")}}""" + +BMM_TEMPLATE = r""" +{{ template.codegen_microkernel_def() }} +{{ template.codegen_single_thread_gemm() }} +{{ template.codegen_multi_thread_gemm() }} + +extern "C" +{{kernel.def_kernel(inputs={"X": BX, "W": BW}, outputs={"Y": BY}, aliases=aliases)}} +{ + const int64_t B = {{kernel.size(BY_2d, 0)}}; + {%- if num_threads > 1 %} + constexpr int64_t num_threads = {{num_threads}}; + int64_t B_single_thread_block = (B / num_threads) * num_threads; + + {%- set use_dynamic_threads = ((config.cpp.threads < 1) and (num_threads == cpu_count)) or config.cpp.dynamic_threads %} + {%- if use_dynamic_threads %} + #pragma omp parallel for + {%- else %} + #pragma omp parallel for num_threads({{num_threads}}) + {%- endif %} + {%- else %} + int64_t B_single_thread_block = B; + {%- endif %} + for (int64_t b_start = 0; b_start < B_single_thread_block; ++b_start) { + {{template.get_gemm_function_call( + kernel, + kernel_name+"_single_thread_mm", + "", + b_index="b_start", + )}} + } + for (int64_t b_start = B_single_thread_block; b_start < B; ++b_start) { + {{template.get_gemm_function_call( + kernel, + kernel_name+"_threaded_mm", + "", + b_index="b_start", + )}} + } +} +""" + + +class CppBmmTemplate(CppGemmTemplate): + def __init__( + self, + input_nodes, + layout: ir.Layout, + num_threads: int, + register_blocking: GemmBlocking, + beta=1, + alpha=1, + has_bias=False, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + should_block_weights: bool = False, + name="bmm", + ): + """ + In order to simplify the implementation and increase code reuse, the BMM template implements + two versions of the GEMM kernel: a single-threaded version and a multi-threaded version. + GEMM kernels are called in a loop over the batch dimension, with single-threaded GEMM calls + for all but the last (B % num_threads), which are handled by the multi-threaded GEMM kernel. + + We use an extra sizevar `b_index` to index the batch dimension, which we pass into the GEMM + template as a sympy.Symbol. This allows us to slice the 3D batch tensors in the GEMM template + without any changes to the GEMM template itself. + """ + super().__init__( + input_nodes, + layout, + num_threads, + register_blocking, + beta=beta, + alpha=alpha, + has_bias=has_bias, + epilogue_creator=epilogue_creator, + should_block_weights=should_block_weights, + name=name, + ) + self.b_index = sympy.Symbol("s_b_index", integer=True, nonnegative=True) + + @staticmethod + def get_padded_size(n, block_n, k, should_block_weight): + if should_block_weight: + # Tensor is constant or not contiguous, so we will pad and block + new_size, padded_n = CppGemmTemplate.get_padded_size( + n, block_n, k, should_block_weight + ) + # Add the new batch dimension + new_size.insert(0, -1) + return new_size, padded_n + else: + new_size = [-1, k, n] + return new_size, n + + @staticmethod + def check_if_block_weight(W, micro_gemm): + if not isinstance(W, ir.IRNode): + raise AssertionError(f"expected W to be an ir.IRNode, got {type(W)}") + _, n = W.get_size()[-2:] + result = ( + not W.get_layout().is_contiguous() + or W.get_name() in V.graph.constants + or ( + n % micro_gemm.register_blocking.block_n != 0 + and micro_gemm.get_b_layout != LayoutType.NORMAL + ) + ) + return result + + def get_gemm_function_call( + self, + kernel: CppTemplateKernel, + function_name: str, + placeholder: str, + b_index: str, + ) -> str: + """ + Similar to 'def_kernel' in cpp_template_kernel, but instead of generating a function definition, + generate a function call for the GEMM kernel. + Args: + placeholder: The string to replace the function call with + b_index: The index for slicing the 3D batch tensors + """ + + def hook(): + arg_defs, call_args, _, _ = kernel.args.python_argdefs() + for i, buf in enumerate(call_args): + if buf == self.b_index: + arg_defs[i] = ArgName(b_index) + call = f"{function_name}({', '.join(x.full_name() for x in arg_defs)});" + return call + + if placeholder in kernel.render_hooks: + raise AssertionError(f"render hook already registered for {placeholder}") + kernel.render_hooks[placeholder] = hook + return placeholder + + def get_default_reindexers(self, epilogues): + def reindexer(args): + # if epilogue nodes exist, they have 3D ranges but args are 2D, so add 0 index + return [self.b_index] + args + + return [reindexer] * len(epilogues) + + def get_options( + self, + kernel: CppTemplateKernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + flag_template_buffer_has_other_users: bool | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + **kwargs, + ) -> dict[str, Any]: + options = super().get_options( + kernel=kernel, + template_buffer_node=template_buffer_node, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_nodes, + **kwargs, + ) + + BX, BW, BY = options["X"], options["W"], options["Y"] + options["BX"], options["BW"], options["BY"] = BX, BW, BY + options["BY_2d"] = options["Y_2d"] + for kword in ["X", "W", "GemmOut", "Y_2d"]: + options[kword] = kernel.select(options[kword], 0, self.b_index) + for kword in ["X", "W", "Y_2d"]: + options[kword + "_dtype"] = DTYPE_TO_CPP[options[kword].dtype] + options["b_index"] = self.b_index + options["BY_sizevars"] = [ + s + for sym in itertools.chain(BY.get_size(), BY.get_stride()) + if isinstance(sym, sympy.Expr) + for s in sym.free_symbols + ] + options["kernel_name"] = kernel.kernel_name + + return options + + def render( # type: ignore[override, return] + self, + kernel: CppTemplateKernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + flag_template_buffer_has_other_users: bool | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + **kwargs, + ) -> str: + options = self.get_options( + kernel=kernel, + template_buffer_node=template_buffer_node, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_nodes, + **kwargs, + ) + self.render_options = options + + with contextlib.ExitStack() as stack: + for buf in options["fake_buffers"]: + stack.enter_context( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf)) + ) + result = self._template_from_string(BMM_TEMPLATE).render(**options) + + # Finalize the function definitions for the gemm routines + sub_mm_hooks = { + name: hook + for name, hook in kernel.render_hooks.items() + if "FOR_BMM" in name + } + result = PartialRender(result, sub_mm_hooks).finalize_all() + for name in sub_mm_hooks: + del kernel.render_hooks[name] + del kernel.args.sizevars[options["b_index"]] + return result + + def codegen_single_thread_gemm(self): + stub = self._template_from_string(GEMM_SINGLE_THREAD_MM_STUB).render( + self.render_options + ) + return stub + self._template_from_string(GEMM_TEMPLATE).render( + {**self.render_options, "num_threads": 1} + ) + + def codegen_multi_thread_gemm(self): + stub = self._template_from_string(GEMM_THREADED_MM_STUB).render( + self.render_options + ) + return stub + self._template_from_string(GEMM_TEMPLATE).render( + self.render_options + ) + + def codegen_gemm_stub_def(self): + return "" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_flex_attention_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_flex_attention_template.py new file mode 100644 index 0000000000000000000000000000000000000000..87bedb35d0716dbd2ca384ecd92c101bb75f3cb7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_flex_attention_template.py @@ -0,0 +1,1515 @@ +# mypy: allow-untyped-defs +import contextlib +import logging +import re +from unittest.mock import patch + +import sympy + +import torch +import torch.utils + +from ...utils._ordered_set import OrderedSet +from .. import ir +from ..ir import TensorBox +from ..select_algorithm import DataProcessorTemplateWrapper +from ..utils import parallel_num_threads +from ..virtualized import V +from .cpp_template import CppTemplate +from .cpp_utils import GemmBlocking + + +log = logging.getLogger(__name__) + +# TODO: reuse cpp codegen to generate below pointwise/reduction kernels +SOFTMAX_FUSIONS = r""" +// 1) out = exp(a - val) +// 2) val = sum(out) +template +inline void {{kernel_name}}_exp_reduce_sum_fusion_kernel( + T1* a, + const int& size, + T2* out, + T1& val) { + auto vec_size = at::vec::Vectorized::size(); + auto vec_max = at::vec::Vectorized(val); + T1 tmp_sum = 0; + auto vec_tmp_sum = at::vec::Vectorized(tmp_sum); + for (long i = 0; i < vec_size * (size / vec_size); i += vec_size) { + auto tmp0 = at::vec::Vectorized::loadu(a + i); + auto tmp1 = tmp0 - vec_max; + auto tmp2 = tmp1.exp_u20(); + vec_tmp_sum += tmp2; + at::native::_store(out + i, tmp2); + } + tmp_sum = at::vec::vec_reduce_all( + [](at::vec::Vectorized& x, at::vec::Vectorized& y) { + return x + y; + }, + vec_tmp_sum); + for (long i = vec_size * (size / vec_size); i < size; i++) { + auto tmp0 = a[i]; + auto tmp1 = tmp0 - val; + auto tmp2 = exp(tmp1); + tmp_sum += tmp2; + out[i] = tmp2; + } + val = tmp_sum; +} + +// 1) out = a * scale +// 2) max = max(out) +template +inline void {{kernel_name}}_mul_reduce_max_fusion_kernel( + const scalar_t* a, + const scalar_t& scale, + const int& size, + scalar_t* out, + scalar_t& max) { + auto vec_size = at::vec::Vectorized::size(); + auto vec_scale = at::vec::Vectorized(scale); + scalar_t tmp_max = -std::numeric_limits::infinity(); + auto vec_tmp_max = at::vec::Vectorized(tmp_max); + for (long i = 0; i < vec_size * (size / vec_size); i += vec_size) { + auto tmp0 = at::vec::Vectorized::loadu(a + i); + auto tmp1 = tmp0 * vec_scale; + vec_tmp_max = at::vec::maximum(vec_tmp_max, tmp1); + at::native::_store(out + i, tmp1); + } + for (long i = vec_size * (size / vec_size); i < size; i++) { + auto tmp0 = a[i]; + auto tmp1 = tmp0 * scale; + tmp_max = std::max(tmp_max, tmp1); + out[i] = tmp1; + } + max = std::max( + tmp_max, + at::vec::vec_reduce_all( + [](at::vec::Vectorized& x, at::vec::Vectorized& y) { + return at::vec::maximum(x, y); + }, + vec_tmp_max)); +} + +template +static inline scalar_t* {{kernel_name}}_conditional_data_ptr(scalar_t* ptr, scalar_t* ptr2) { + TORCH_CHECK(ptr2 == nullptr); + return ptr; +} + +template , int> = 0> +static inline scalar_t* {{kernel_name}}_conditional_data_ptr(float* ptr, scalar_t* ptr2) { + return ptr2; +} + +template +inline void {{kernel_name}}_fill_stub(scalar_t* data, scalar_t val, int64_t size) { + using Vec = at::vec::Vectorized; + Vec data_vec = Vec(val); + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + data_vec.store(data + d); + } + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (; d < size; d++) { + data[d] = val; + } +} + +// out = a * scale +template +inline void {{kernel_name}}_mul_scale_kernel( + scalar_t* a, + scalar_t scale, + int64_t size) { + auto vec_size = at::vec::Vectorized::size(); + auto vec_scale = at::vec::Vectorized(scale); + for (int64_t i = 0; i < vec_size * (size / vec_size); i += vec_size) { + auto tmp0 = at::vec::Vectorized::loadu(a + i); + auto tmp1 = tmp0 * vec_scale; + at::native::_store(a + i, tmp1); + } + for (int64_t i = vec_size * (size / vec_size); i < size; i++) { + auto tmp0 = a[i]; + auto tmp1 = tmp0 * scale; + a[i] = tmp1; + } +} + +""" + +BRGEMM_PACK_FUNCTIONS = r""" +template +inline void {{kernel_name}}_copy_value_with_pad( + const scalar_t* value_ptr, + scalar_t* dst_ptr, + int64_t rows, + int64_t cols, + int64_t prows, + int64_t pcols, + int64_t ldi) { + auto vec_size = at::vec::Vectorized::size(); + int64_t i = 0; + for (; i < rows; i++) { + int64_t j = 0; + for (; j < cols - (cols % vec_size); j += vec_size) { + auto vec_v = + at::vec::Vectorized::loadu(value_ptr + i * ldi + j); + vec_v.store(dst_ptr + i * pcols + j); + } + + if (j < cols) { + auto vec_v = at::vec::Vectorized::loadu( + value_ptr + i * ldi + j, cols - j); + vec_v.store(dst_ptr + i * pcols + j, cols - j); + } + + // col padding + auto psize = pcols - cols; + if (psize > 0) { + auto zero_vec = at::vec::Vectorized(0); + int64_t pj = 0; + for (; pj < psize - (psize % vec_size); pj += vec_size) { + zero_vec.store(dst_ptr + i * pcols + cols + pj); + } + if (pj < psize) { + zero_vec.store(dst_ptr + i * pcols + cols + pj, psize - pj); + } + } + } + // row padding + for (; i < prows; i++) { + auto zero_vec = at::vec::Vectorized(0); + int64_t j = 0; + for (; j < pcols - (pcols % vec_size); j += vec_size) { + zero_vec.store(dst_ptr + i * pcols + j); + } + if (j < pcols) { + zero_vec.store(dst_ptr + i * pcols + j, pcols - j); + } + + } +} +""" + +MICRO_GEMM_TEMPLATE = r""" +GEMM_DEFINE +""" + +ALLOCATE_BUFFER = r""" + int64_t {{buffer_name}}_dtype_itemsize = c10::is_reduced_floating_point_v<{{buffer_dtype}}> ? 2 : 4; + auto& {{buffer_name}}_allocator = *at::getCPUAllocator(); + auto {{buffer_name}}_work_data = {{buffer_name}}_allocator.allocate({{buffer_size}}*{{buffer_name}}_dtype_itemsize); + void* {{buffer_name}}_data_ptr = {{buffer_name}}_work_data.get(); + {{buffer_dtype}}* {{buffer_name}} = ({{buffer_dtype}}*){{buffer_name}}_data_ptr; +""" + +INIT_PARAMS = r""" +{{template.header().getvalue()}} +#include +#include +#include +{{template.codegen_micro_gemm(kernel.kernel_name)}} +{{template.codegen_softmax_fusion(kernel.kernel_name)}} +{{template.codegen_brgemm_pack_function(kernel.kernel_name)}} +{%- set kernel_args = {"query": query, "key": key, "value": value, + "kv_num_blocks": kv_num_blocks, "kv_indices": kv_indices, + "full_kv_num_blocks": full_kv_num_blocks, "full_kv_indices": full_kv_indices } %} +{%- set kernel_args = template.update_kernel_args(kernel_args) %} + +extern "C" +{{kernel.def_kernel(inputs=kernel_args, outputs={"output": output}, extra_sizevars=template.extra_sizevars)}} +{ + {{ kernel.maybe_codegen_profile() }} + + // dtypes + using scalar_t = {{kernel.dtype(query)}}; + constexpr bool is_reduced_type = c10::is_reduced_floating_point_v; + using accum_t = at::opmath_type<{{kernel.dtype(query)}}>; + using Vec = at::vec::Vectorized; + accum_t scaling_factor = {{scale}}; + + // sizes + int64_t qBlockSize = {{qBlockSize}}; + int64_t kvBlockSize = {{kvBlockSize}}; + int64_t num_thread = {{num_thread}}; + int64_t batchSize = {{kernel.size(query, 0)}}; + int64_t qSize = {{kernel.size(query, 1)}}; + int64_t num_head = {{kernel.size(query, 2)}}; + int64_t headSize = {{kernel.size(query, 3)}}; + int64_t batchSize_k = {{kernel.size(key, 0)}}; + int64_t num_head_k = {{kernel.size(key, 2)}}; + int64_t headSize_v = {{kernel.size(value, 3)}}; + bool is_broadcast_bs_kv = batchSize != batchSize_k; + bool is_broadcast_head_kv = num_head != num_head_k; + int64_t gqa_shards = num_head / num_head_k; + int64_t bs_shards = batchSize / batchSize_k; + + int64_t batchSize_kvi = {{kernel.size(kv_indices, 0)}}; + int64_t num_head_kvi = {{kernel.size(kv_indices, 1)}}; + int64_t block_num_kvi = {{kernel.size(kv_indices, 3)}}; + bool is_broadcast_bs_kvi = batchSize != batchSize_kvi; + bool is_broadcast_head_kvi = num_head != num_head_kvi; + int64_t gqa_shards_kvi = num_head / num_head_kvi; + int64_t bs_shards_kvi = batchSize / batchSize_kvi; + + int64_t kvSize = {{kernel.size(key, 1)}}; + + int64_t qSplitSize = qBlockSize; + int64_t kvSplitSize = kvBlockSize; + + qSplitSize = qSplitSize > qSize ? qSize : qSplitSize; + kvSplitSize = kvSplitSize > kvSize ? kvSize : kvSplitSize; + int64_t qSlice = (qSize + qSplitSize - 1) / qSplitSize; + int64_t kvSlice = (kvSize + kvSplitSize - 1) / kvSplitSize; + int64_t kvTail = (kvSize - 1) % kvSplitSize + 1; + + // Strides + int64_t kviStrideB = {{kernel.stride(kv_indices, 0)}}; + int64_t kviStrideH = {{kernel.stride(kv_indices, 1)}}; + int64_t kviStrideQ = {{kernel.stride(kv_indices, 2)}}; + + int64_t num_kviStrideB = {{kernel.stride(kv_num_blocks, 0)}}; + int64_t num_kviStrideH = {{kernel.stride(kv_num_blocks, 1)}}; + +{%- if has_full_kv_block %} + int64_t full_kviStrideB = {{kernel.stride(full_kv_indices, 0)}}; + int64_t full_kviStrideH = {{kernel.stride(full_kv_indices, 1)}}; + int64_t full_kviStrideQ = {{kernel.stride(full_kv_indices, 2)}}; + + int64_t full_num_kviStrideB = {{kernel.stride(full_kv_num_blocks, 0)}}; + int64_t full_num_kviStrideH = {{kernel.stride(full_kv_num_blocks, 1)}}; + auto full_kv_indices_data = full_kv_indices; + auto full_kv_num_blocks_data = full_kv_num_blocks; +{%- endif %} + + auto kv_num_blocks_data = kv_num_blocks; + auto kv_indices_data = kv_indices; + + int64_t qStrideB = {{kernel.stride(query, 0)}}; + int64_t qStrideM = {{kernel.stride(query, 1)}}; + int64_t qStrideH = {{kernel.stride(query, 2)}}; + int64_t kStrideB = {{kernel.stride(key, 0)}}; + int64_t kStrideN = {{kernel.stride(key, 1)}}; + int64_t kStrideH = {{kernel.stride(key, 2)}}; + int64_t vStrideB = {{kernel.stride(value, 0)}}; + int64_t vStrideN = {{kernel.stride(value, 1)}}; + int64_t vStrideH = {{kernel.stride(value, 2)}}; + int64_t oStrideB = {{kernel.stride(output, 0)}}; + int64_t oStrideM = {{kernel.stride(output, 2)}}; + int64_t oStrideH = {{kernel.stride(output, 1)}}; + + // Inputs/outputs buffers + const scalar_t* q_data = query; + const scalar_t* k_data = key; + const scalar_t* v_data = value; + scalar_t* out_data = output; + +""" + +FLEX_ATTENTION_TEMPLATE = r""" + bool need_pack = false; + // Whether pack is needed for BFloat16/Half + if (is_reduced_type) { + // check platform ability + need_pack = std::is_same_v ? at::native::cpublas::could_pack(at::kBFloat16) + : at::native::cpublas::could_pack(at::kHalf); + } + if (need_pack) { + // When the number of gemm is greater than the number of pack, + // the pack overhead can be overlapped. + int64_t thresh_size = 64; + need_pack = kvSize >= thresh_size && qSize >= thresh_size; + if (need_pack) { + double pack_size = batchSize * num_head * kvSize * headSize; + double qs_per_thread = (batchSize * num_head * qSlice + num_thread - 1) / num_thread; + double gemm_size_per_thread = qs_per_thread * qSplitSize * kvSize * headSize; + need_pack = gemm_size_per_thread / pack_size >= 4; + } + } + // Pad is needed for packing when K is not even + bool headSize_even = headSize % 2 == 0; + int64_t eheadSize = need_pack && !headSize_even ? headSize + 1: headSize; + int64_t ekvSplitSize = need_pack && (kvSplitSize % 2 != 0) ? kvSplitSize + 1 : kvSplitSize; + int64_t ekvTail = need_pack && (kvTail % 2 != 0) ? kvTail + 1 : kvTail; + int64_t kv_padding_size = (kvSize - 1) / kvSplitSize * ekvSplitSize + ekvTail; + + // Allocate per thread temp buf (accumulate type) + int64_t _size_per_thread = + /* qk */ qSplitSize * kvSplitSize + + /* qk_max */ qSplitSize + + /* qk_sum */ qSplitSize + + /* dst */ qSplitSize * headSize_v; + + // Buffers to store accum results, padding query and transpose/packing key/value + {{template.codegen_allocate_buffer("buf_data", "accum_t", "num_thread*_size_per_thread")}} + {{template.codegen_allocate_buffer("buf_reduced_data", "scalar_t", "num_thread*qSplitSize*ekvSplitSize")}} + {{template.codegen_allocate_buffer("key_reorder_ptr", "scalar_t", "batchSize_k*num_head_k*eheadSize*kvSize")}} + {{template.codegen_allocate_buffer("value_reorder_ptr", "scalar_t", "batchSize_k*num_head_k*kv_padding_size*headSize_v")}} + {{template.codegen_allocate_buffer("transpose_buffer_ptr", "scalar_t", "num_thread*kvSplitSize*headSize")}} + {{template.codegen_allocate_buffer("query_padding_ptr", "scalar_t", "num_thread*qSplitSize*eheadSize")}} + if (need_pack) { + // Pack K, V + at::parallel_for(0, batchSize_k * num_head_k * kvSlice, 1, [&](int64_t begin, int64_t end) { + int ompIdx = at::get_thread_num(); + int64_t i = 0, j = 0, l = 0, n = 0; + scalar_t* transpose_ptr = need_pack? transpose_buffer_ptr + ompIdx * kvSplitSize * headSize : nullptr; + at::native::data_index_init(begin, i, batchSize_k, j, num_head_k, l, kvSlice); + for ([[maybe_unused]] auto z : c10::irange(begin, end)) { + n = l * kvSplitSize; + int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n); + auto k_addr = + k_data + i * kStrideB + j * kStrideH + n * kStrideN; + auto v_addr = + v_data + i * vStrideB + j * vStrideH + n * vStrideN; + // transpose [cur_kvSplitSize, headSize] -> [headSize, cur_kvSplitSize] + at::native::utils::transpose( + cur_kvSplitSize, + headSize, + /* src_ptr */ + reinterpret_cast(k_addr), + /* ld_src */ kStrideN, + /* dst */ reinterpret_cast(transpose_ptr), + /* ld_dst */ cur_kvSplitSize); + + // Pack [headSize, cur_kvSplitSize] + at::vec::pack_vnni2( + /* src */ reinterpret_cast(transpose_ptr), + /* dst */ reinterpret_cast(key_reorder_ptr + i * num_head_k * eheadSize * kvSize + + j * eheadSize * kvSize + n * eheadSize), + /* ld_src */ cur_kvSplitSize, + /* K */ headSize, + /* N */ cur_kvSplitSize); + + // Pack [cur_kvSplitSize, headSize_v] + at::vec::pack_vnni2( + /* src */ reinterpret_cast(v_addr), + /* dst */ reinterpret_cast(value_reorder_ptr + + i * num_head_k * kv_padding_size * headSize_v + + j * kv_padding_size * headSize_v + n * headSize_v), + /* ld_src */ vStrideN, + /* K */ cur_kvSplitSize, + /* N */ headSize_v); + // Move to the next query + at::native::data_index_step(i, batchSize_k, j, num_head_k, l, kvSlice); + } + }); + } + // Attention loop below + at::parallel_for(0, batchSize * num_head * qSlice, 1, [&](int64_t begin, int64_t end) { + int64_t i = 0, j = 0, k = 0; + at::native::data_index_init(begin, i, batchSize, j, num_head, k, qSlice); + int ompIdx = at::get_thread_num(); + accum_t* buf_ptr = buf_data + ompIdx * _size_per_thread; + accum_t* qk_data = buf_ptr; + accum_t* qk_max_data = qk_data + qSplitSize * kvSplitSize; + accum_t* qk_sum_data = qk_max_data + qSplitSize; + accum_t* dst_data = qk_sum_data + qSplitSize; + scalar_t *qk_reduced_data = + is_reduced_type + ? buf_reduced_data + ompIdx * qSplitSize * ekvSplitSize + : nullptr; + scalar_t* query_t_padding_ptr = (!headSize_even && need_pack) + ? query_padding_ptr + ompIdx * qSplitSize * eheadSize + : nullptr; + + for ([[maybe_unused]] auto z : c10::irange(begin, end)) { + auto i_kvi = is_broadcast_bs_kvi ? i/bs_shards_kvi : i; + auto j_kvi = is_broadcast_head_kvi ? j/gqa_shards_kvi : j; + auto kv_logical_num_data = kv_num_blocks_data + i_kvi * num_kviStrideB + + j_kvi * num_kviStrideH + k; + int kv_indice_num = *kv_logical_num_data; + std::vector kv_indice_list(kv_indice_num); + for(int kv_i = 0; kv_i < kv_indice_num; kv_i++){ + auto kv_logical_data = kv_indices_data + i_kvi * kviStrideB + + j_kvi * kviStrideH + k*kviStrideQ + kv_i; + kv_indice_list[kv_i] = *kv_logical_data; + } + bool is_skip_kv = kv_indice_num > 0 ? false : true; +{%- if has_full_kv_block %} + auto full_kv_logical_num_data = full_kv_num_blocks_data + i_kvi * num_kviStrideB + + j_kvi * num_kviStrideH + k; + int full_kv_indice_num = *full_kv_logical_num_data; + std::vector full_kv_indice_list(full_kv_indice_num); + for(int kv_i = 0; kv_i < full_kv_indice_num; kv_i++){ + auto full_kv_logical_data = full_kv_indices_data + i_kvi * full_kviStrideB + + j_kvi * full_kviStrideH + k*full_kviStrideQ + kv_i; + full_kv_indice_list[kv_i] = *full_kv_logical_data; + } + is_skip_kv = kv_indice_num + full_kv_indice_num > 0 ? false : true; +{%- endif %} + int64_t m = k * qSplitSize; + int64_t cur_qSplitSize = std::min(qSplitSize, qSize - m); + if (!is_skip_kv){ + // Initialize max and sum + {{kernel.kernel_name}}_fill_stub(qk_max_data, + -std::numeric_limits::infinity(), cur_qSplitSize); + {{kernel.kernel_name}}_fill_stub(qk_sum_data, + static_cast(0), cur_qSplitSize); + + if (!headSize_even && need_pack) { + // Pad query if headSize is not even + {{kernel.kernel_name}}_copy_value_with_pad( + q_data + i * qStrideB + j * qStrideH + m * qStrideM, + query_t_padding_ptr, + cur_qSplitSize, + headSize, + cur_qSplitSize, + eheadSize, + qStrideM + ); + } + } + +{%- if has_full_kv_block %} + for (int64_t n_idx = 0; n_idx < kv_indice_num + full_kv_indice_num ; n_idx += 1) { + auto n = n_idx < kv_indice_num ? kv_indice_list[n_idx]*kvSplitSize : full_kv_indice_list[n_idx - kv_indice_num]*kvSplitSize; +{%- else %} + for (int64_t n_idx = 0; n_idx < kv_indice_num ; n_idx += 1) { + auto n = kv_indice_list[n_idx]*kvSplitSize; +{%- endif %} + + auto cur_n = n/kvSplitSize; + int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n); + int64_t cur_ekvSplitSize = (need_pack && cur_kvSplitSize % 2 != 0) ? cur_kvSplitSize + 1 : cur_kvSplitSize; + + // Calculate scale * q @ k.T + auto i_kv = is_broadcast_bs_kv ? i/bs_shards : i; + auto j_kv = is_broadcast_head_kv ? j/gqa_shards : j; + + if (!need_pack) { + auto k_addr = + k_data + i_kv * kStrideB + j_kv * kStrideH + n * kStrideN; + + {{kernel.kernel_name}}_kernel_micro_gemm_transpose_b(false)>( + q_data + i * qStrideB + j * qStrideH + + m * qStrideM, + k_addr, + qk_data, + cur_qSplitSize, + cur_kvSplitSize, + headSize, + qStrideM, + kStrideN, + cur_kvSplitSize); + + } else { + at::native::cpublas::brgemm( + cur_qSplitSize, + cur_kvSplitSize, + eheadSize, + headSize_even ? qStrideM : eheadSize, + cur_kvSplitSize, + cur_kvSplitSize, + false, + !headSize_even + ? query_t_padding_ptr + : q_data + i * qStrideB + j * qStrideH + m * qStrideM, + key_reorder_ptr + i_kv * num_head_k * eheadSize * kvSize + + j_kv * eheadSize * kvSize + n * eheadSize, + qk_data, + need_pack); + } + + {{kernel.kernel_name}}_mul_scale_kernel(qk_data, scaling_factor, cur_qSplitSize*cur_kvSplitSize); + +{%- if score_mod and mask_mod %} + // TODO: reduce the number of calls of q_idx and kv_idx initialization + std::vector q_idx(cur_qSplitSize); + for (int64_t i = 0; i < cur_qSplitSize; ++i) { + q_idx[i] = m + i; + } + + std::vector kv_idx(cur_kvSplitSize); + for (int64_t i = 0; i < cur_kvSplitSize; ++i) { + kv_idx[i] = n + i; + } + + std::vector b_idx = {i}; + std::vector h_idx = {j}; + + accum_t* in_ptr0 = qk_data; + + auto in_ptr1 = b_idx.data(); + auto in_ptr2 = h_idx.data(); + auto in_ptr3 = q_idx.data(); + auto in_ptr4 = kv_idx.data(); + + // apply score mod function + { + {{ template.generate_other_buffer("score_others", 0, "len_score_other", kernel.args) }} + accum_t* out_ptr{{score_buf_idx}} = in_ptr0; + {{ template.modification(score_mod, score_buf_name, score_buf_idx)|indent(12, false) }} + } + + if ((std::find(kv_indice_list.begin(), kv_indice_list.end(), cur_n) != kv_indice_list.end()) ){ + // Apply block mask, fill unused with -inf + { + {{ template.generate_other_buffer("mask_others", -1, "len_mask_other", kernel.args) }} + accum_t* out_ptr{{mask_buf_idx}} = in_ptr0; + {{ template.modification(mask_mod, mask_buf_name, mask_buf_idx)|indent(12, false) }} + } + } + +{%- endif %} + // Update coefficients with Softmax + accum_t tmp_max = 0, tmp_sum = 0, exp_tmp = 0; + for (int64_t row = 0; row < cur_qSplitSize; ++row) { + // apply scaling factor and max per row in fusion + {{kernel.kernel_name}}_mul_reduce_max_fusion_kernel( + qk_data + row * cur_kvSplitSize, + static_cast(1), + cur_kvSplitSize, + qk_data + row * cur_kvSplitSize, + tmp_max); + tmp_max = qk_max_data[row] > tmp_max ? qk_max_data[row] : tmp_max; + if (tmp_max == -std::numeric_limits::infinity()) { + // to avoid `nan = exp2f(-inf - (-inf))` + {{kernel.kernel_name}}_fill_stub( + {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data) + row * cur_ekvSplitSize, + static_cast(0), cur_kvSplitSize); + } else { + tmp_sum = tmp_max; + // qk <- exp(qk - max) and sum per row + {{kernel.kernel_name}}_exp_reduce_sum_fusion_kernel( + qk_data + row * cur_kvSplitSize, cur_kvSplitSize, + {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data) + row * cur_ekvSplitSize, + tmp_sum); + // exp_tmp <- exp(max[row] - max) + exp_tmp = std::exp(qk_max_data[row] - tmp_max); + // sum[row] <- sum + exp_tmp * sum[row] + qk_sum_data[row] = tmp_sum + exp_tmp * qk_sum_data[row]; + // max[row] <- max + qk_max_data[row] = tmp_max; + // dst <- dst * exp_tmp + if (n_idx > 0) { + at::vec::map( + [exp_tmp](Vec x) { return x * Vec(exp_tmp); }, + dst_data + row * headSize_v, + dst_data + row * headSize_v, + headSize_v); + } + } + if (need_pack && cur_kvSplitSize % 2 != 0) { + // Pad: [qSplitSize, cur_kvSplitSize] -> [qSplitSize, cur_kvSplitSize + 1] + *(qk_reduced_data + row * (1 + cur_kvSplitSize) + cur_kvSplitSize) = scalar_t(0); + } + } + // Calculate Softmax(q @ k.T) @ v + if (!need_pack) { + auto v_addr = + v_data + i_kv * vStrideB + j_kv * vStrideH + n * vStrideN; + // Fallback Half brgemm is slower than micro gemm + if (!std::is_same_v) { + at::native::cpublas::brgemm( + cur_qSplitSize, + headSize_v, + cur_ekvSplitSize, + cur_ekvSplitSize, + vStrideN, + headSize_v, + n_idx > 0, + {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data), + v_addr, + dst_data, + need_pack); + } else { + if (n_idx > 0) { + {{kernel.kernel_name}}_kernel_micro_gemm(true)>( + {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data), + v_addr, + dst_data, + cur_qSplitSize, + headSize_v, + cur_ekvSplitSize, + cur_ekvSplitSize, + vStrideN, + headSize_v); + } else { + {{kernel.kernel_name}}_kernel_micro_gemm(false)>( + {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data), + v_addr, + dst_data, + cur_qSplitSize, + headSize_v, + cur_ekvSplitSize, + cur_ekvSplitSize, + vStrideN, + headSize_v); + } + } + } else { + int64_t psize = n / kvSplitSize * ekvSplitSize; + at::native::cpublas::brgemm( + cur_qSplitSize, + headSize_v, + cur_ekvSplitSize, + cur_ekvSplitSize, + headSize_v, + headSize_v, + n_idx > 0, + qk_reduced_data, + value_reorder_ptr + + i_kv * num_head_k * kv_padding_size * headSize_v + + j_kv * kv_padding_size * headSize_v + psize * headSize_v, + dst_data, + need_pack); + } + } + + // dst <- dst / sum[row] + // reorder MHA output with strides + for (int64_t row = 0; row < cur_qSplitSize; ++row) { + // Row sums for full masked out rows are 0, we set them to 1 + // in order to avoid NaNs in the output and instead set fully + // masked out rows to 0 + qk_max_data[row] = qk_max_data[row] == -std::numeric_limits::infinity() ? 0 : qk_max_data[row]; + qk_sum_data[row] = qk_sum_data[row] == 0 ? 1 : qk_sum_data[row]; + accum_t sum_reciprocal = 1 / qk_sum_data[row]; + at::vec::map( + [sum_reciprocal, is_skip_kv](Vec x) { return is_skip_kv ? Vec(0.0) : x * Vec(sum_reciprocal); }, + out_data + i * oStrideB + j * oStrideH + m * oStrideM + row * oStrideM, + dst_data + row * headSize_v, + headSize_v); + } + + // Move to the next query + at::native::data_index_step(i, batchSize, j, num_head, k, qSlice); + } + + at::native::cpublas::brgemm_release(need_pack); + + }); +} +""" + +FLEX_DECODING_TEMPLATE = r""" + int64_t PARTITION_SIZE = {{partition_size}}; + + // Check if score / mask mod dependent on batch_size / num_head + // Go into a fast path if independent + bool bs_head_independent_mod = true; + int64_t first_num_kvblocks = kv_num_blocks[0]; + int64_t first_full_num_kvblocks = full_kv_num_blocks[0]; + for (const auto& b : c10::irange(batchSize_kvi)) { + for (const auto& h : c10::irange(num_head_kvi)) { + if (*(kv_num_blocks + b * num_kviStrideB + h * num_kviStrideH) != first_num_kvblocks + || *(full_kv_num_blocks + b * full_num_kviStrideB + h * full_num_kviStrideH) != first_full_num_kvblocks) { + bs_head_independent_mod = false; + break; + } + } + } + + int64_t num_kvblocks_per_seq = kv_num_blocks[0] + full_kv_num_blocks[0]; + int64_t num_kvblocks_per_partition = PARTITION_SIZE / kvBlockSize; + int64_t num_partitions = (num_kvblocks_per_seq + num_kvblocks_per_partition - 1) / num_kvblocks_per_partition; + if (!bs_head_independent_mod) { + num_partitions = + (kvSize + PARTITION_SIZE - 1) / PARTITION_SIZE; + } + + // Allocate temp buf (accumulate type) + int64_t _accum_buff_size = + /* max_logits_ptr */ batchSize * num_head * num_partitions + + /* exp_sum_ptr */ batchSize * num_head * num_partitions + + /* tmp_out_ptr */ batchSize * num_head * num_partitions * headSize_v + + /* logits_ptrs */ num_thread * PARTITION_SIZE; + + {{template.codegen_allocate_buffer("buf_data", "accum_t", "_accum_buff_size")}} + accum_t* max_logits_ptr = buf_data; + accum_t* exp_sum_ptr = max_logits_ptr + batchSize * num_head * num_partitions; + accum_t* tmp_out_ptr = exp_sum_ptr + batchSize * num_head * num_partitions; + accum_t* logits_ptrs = tmp_out_ptr + batchSize * num_head * num_partitions * headSize_v; + {{template.codegen_allocate_buffer("logits_reduced_ptrs", "scalar_t", "num_thread * PARTITION_SIZE")}} + + auto max_logits_strideN = num_head * num_partitions; + auto max_logits_strideH = num_partitions; + auto exp_sum_strideN = num_head * num_partitions; + auto exp_sum_strideH = num_partitions; + auto tmp_out_strideN = num_head * num_partitions * headSize_v; + auto tmp_out_strideH = num_partitions * headSize_v; + auto tmp_out_strideS = headSize_v; + + // Attention loop + at::parallel_for(0, batchSize * num_head * num_partitions, 1, [&](int64_t begin, int64_t end) { + int64_t i = 0, j = 0, partition_id = 0; + at::native::data_index_init(begin, i, batchSize, j, num_head, partition_id, num_partitions); + int ompIdx = at::get_thread_num(); + accum_t* logits = logits_ptrs + ompIdx * PARTITION_SIZE; + scalar_t* logits_reduced = + is_reduced_type + ? logits_reduced_ptrs + ompIdx * PARTITION_SIZE + : nullptr; + + for ([[maybe_unused]] auto z : c10::irange(begin, end)) { + auto kvblock_offset = num_kvblocks_per_partition * partition_id; + auto i_kvi = is_broadcast_bs_kvi ? i/bs_shards_kvi : i; + auto j_kvi = is_broadcast_head_kvi ? j/gqa_shards_kvi : j; + auto kv_logical_num_data = kv_num_blocks_data + i_kvi * num_kviStrideB + + j_kvi * num_kviStrideH; + int64_t kv_indice_num = *kv_logical_num_data; + std::vector kv_indice_list(kv_indice_num); + for(int64_t kv_i = 0; kv_i < kv_indice_num; kv_i++){ + auto kv_logical_data = kv_indices_data + i_kvi * kviStrideB + + j_kvi * kviStrideH + kv_i; + kv_indice_list[kv_i] = *kv_logical_data; + } +{%- if has_full_kv_block %} + auto full_kv_logical_num_data = full_kv_num_blocks_data + i_kvi * num_kviStrideB + + j_kvi * num_kviStrideH; + int64_t full_kv_indice_num = *full_kv_logical_num_data; + std::vector full_kv_indice_list(full_kv_indice_num); + for(int64_t kv_i = 0; kv_i < full_kv_indice_num; kv_i++){ + auto full_kv_logical_data = full_kv_indices_data + i_kvi * full_kviStrideB + + j_kvi * full_kviStrideH + kv_i; + full_kv_indice_list[kv_i] = *full_kv_logical_data; + } +{%- endif %} + int64_t cur_qSplitSize = 1; + auto i_kv = is_broadcast_bs_kv ? i/bs_shards : i; + auto j_kv = is_broadcast_head_kv ? j/gqa_shards : j; + accum_t* tmp_out = tmp_out_ptr + i * tmp_out_strideN + + j * tmp_out_strideH + partition_id * tmp_out_strideS; + + // Initialize logits + {{kernel.kernel_name}}_fill_stub(logits, + static_cast(0), PARTITION_SIZE); + if (is_reduced_type) { + {{kernel.kernel_name}}_fill_stub(logits_reduced, + static_cast(0), PARTITION_SIZE); + } + + + // 1) calculate the matmul(query, key) for this partition + int64_t token_num = 0; +{%- if has_full_kv_block %} + int64_t n_idx_start = kvblock_offset; + int64_t n_idx_end = std::min(kvblock_offset + num_kvblocks_per_partition, kv_indice_num + full_kv_indice_num); + if (!bs_head_independent_mod) { + n_idx_start = 0; + n_idx_end = kv_indice_num + full_kv_indice_num; + } + for (int64_t n_idx : c10::irange(n_idx_start, n_idx_end)) { + auto n = n_idx < kv_indice_num ? kv_indice_list[n_idx]*kvSplitSize : full_kv_indice_list[n_idx - kv_indice_num]*kvSplitSize; +{%- else %} + int64_t n_idx_start = kvblock_offset; + int64_t n_idx_end = std::min(kvblock_offset + num_kvblocks_per_partition, kv_indice_num); + if (!bs_head_independent_mod) { + n_idx_start = 0; + n_idx_end = kv_indice_num; + } + for (int64_t n_idx : c10::irange(n_idx_start, n_idx_end)) { + auto n = kv_indice_list[n_idx]*kvSplitSize; +{%- endif %} + if (!bs_head_independent_mod + && (n < partition_id * PARTITION_SIZE + || n >= std::min(partition_id * PARTITION_SIZE + PARTITION_SIZE, kvSize))) { + continue; + } + auto cur_n = n/kvSplitSize; + int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n); + + auto k_addr = + k_data + i_kv * kStrideB + j_kv * kStrideH + n * kStrideN; + + {{kernel.kernel_name}}_kernel_micro_gemm_transpose_b( + q_data + i * qStrideB + j * qStrideH, + k_addr, + logits + token_num, + cur_qSplitSize, + cur_kvSplitSize, + headSize, + qStrideM, + kStrideN, + cur_kvSplitSize); + + {{kernel.kernel_name}}_mul_scale_kernel(logits + token_num, scaling_factor, cur_qSplitSize*cur_kvSplitSize); + +{%- if score_mod and mask_mod %} + // TODO: reduce the number of calls of q_idx and kv_idx initialization + std::vector q_idx(cur_qSplitSize); + for (int64_t i = 0; i < cur_qSplitSize; ++i) { + q_idx[i] = i; + } + + std::vector kv_idx(cur_kvSplitSize); + for (int64_t i = 0; i < cur_kvSplitSize; ++i) { + kv_idx[i] = n + i; + } + + std::vector b_idx = {i}; + std::vector h_idx = {j}; + + accum_t* in_ptr0 = logits + token_num; + + const auto in_ptr1 = b_idx.data(); + const auto in_ptr2 = h_idx.data(); + const auto in_ptr3 = q_idx.data(); + const auto in_ptr4 = kv_idx.data(); + + // apply score mod function + { + {{ template.generate_other_buffer("score_others", 0, "len_score_other", kernel.args) }} + accum_t* out_ptr{{score_buf_idx}} = in_ptr0; + {{ template.modification(score_mod, score_buf_name, score_buf_idx)|indent(12, false) }} + } + + if ((std::find(kv_indice_list.begin(), kv_indice_list.end(), cur_n) != kv_indice_list.end()) ){ + // Apply block mask, fill unused with -inf + { + {{ template.generate_other_buffer("mask_others", -1, "len_mask_other", kernel.args) }} + accum_t* out_ptr{{mask_buf_idx}} = in_ptr0; + {{ template.modification(mask_mod, mask_buf_name, mask_buf_idx)|indent(12, false) }} + } + } +{%- endif %} + token_num += cur_kvSplitSize; + } + + + // 2) calculate the max and exp_sum for this partition + auto partition_max = -std::numeric_limits::infinity(); + {{kernel.kernel_name}}_mul_reduce_max_fusion_kernel( + logits, + static_cast(1), + token_num, + logits, + partition_max); + if (partition_max == -std::numeric_limits::infinity()) { + partition_max = 0; + } + max_logits_ptr[i * max_logits_strideN + + j * max_logits_strideH + partition_id] = + partition_max; + {{kernel.kernel_name}}_exp_reduce_sum_fusion_kernel( + logits, + token_num, + {{kernel.kernel_name}}_conditional_data_ptr(logits, logits_reduced), + partition_max); + exp_sum_ptr[i * exp_sum_strideN + + j * exp_sum_strideH + partition_id] = partition_max; + + + // 3) calculate the matmul(exp(logits-partition_max), value) for this + // partition, need to divide the global exp_sum in the final result. + token_num = 0; + bool skipped_partition = true; +{%- if has_full_kv_block %} + n_idx_start = kvblock_offset; + n_idx_end = std::min(kvblock_offset + num_kvblocks_per_partition, kv_indice_num + full_kv_indice_num); + if (!bs_head_independent_mod) { + n_idx_start = 0; + n_idx_end = kv_indice_num + full_kv_indice_num; + } + for (int64_t n_idx : c10::irange(n_idx_start, n_idx_end)) { + auto n = n_idx < kv_indice_num ? kv_indice_list[n_idx]*kvSplitSize : full_kv_indice_list[n_idx - kv_indice_num]*kvSplitSize; +{%- else %} + n_idx_start = kvblock_offset; + n_idx_end = std::min(kvblock_offset + num_kvblocks_per_partition, kv_indice_num); + if (!bs_head_independent_mod) { + n_idx_start = 0; + n_idx_end = kv_indice_num; + } + for (int64_t n_idx : c10::irange(n_idx_start, n_idx_end)) { + auto n = kv_indice_list[n_idx]*kvSplitSize; +{%- endif %} + if (!bs_head_independent_mod + && (n < partition_id * PARTITION_SIZE + || n >= std::min(partition_id * PARTITION_SIZE + PARTITION_SIZE, kvSize))) { + continue; + } + skipped_partition = false; + int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n); + + auto v_addr = + v_data + i_kv * vStrideB + j_kv * vStrideH + n * vStrideN; + // Fallback Half brgemm is slower than micro gemm + + if constexpr (!std::is_same_v) { + at::native::cpublas::brgemm( + cur_qSplitSize, + headSize_v, + cur_kvSplitSize, + cur_kvSplitSize, + vStrideN, + headSize_v, + token_num > 0, + {{kernel.kernel_name}}_conditional_data_ptr(logits, logits_reduced) + token_num, + v_addr, + tmp_out, + false); + } else { + if (token_num > 0) { + {{kernel.kernel_name}}_kernel_micro_gemm(true)>( + {{kernel.kernel_name}}_conditional_data_ptr(logits, logits_reduced) + token_num, + v_addr, + tmp_out, + cur_qSplitSize, + headSize_v, + cur_kvSplitSize, + cur_kvSplitSize, + vStrideN, + headSize_v); + } else { + {{kernel.kernel_name}}_kernel_micro_gemm(false)>( + {{kernel.kernel_name}}_conditional_data_ptr(logits, logits_reduced) + token_num, + v_addr, + tmp_out, + cur_qSplitSize, + headSize_v, + cur_kvSplitSize, + cur_kvSplitSize, + vStrideN, + headSize_v); + } + } + token_num += cur_kvSplitSize; + } + if (skipped_partition) { + {{kernel.kernel_name}}_fill_stub(tmp_out, + static_cast(0), headSize_v); + } + + // Move to the next query + at::native::data_index_step(i, batchSize, j, num_head, partition_id, num_partitions); + } + + if constexpr (!std::is_same_v) { + at::native::cpublas::brgemm_release(); + } + }); + + + // Calculate the final output + at::parallel_for(0, batchSize * num_head, 1, [&](int64_t begin, int64_t end) { + int64_t i = 0, j = 0; + at::native::data_index_init(begin, i, batchSize, j, num_head); + + for ([[maybe_unused]] auto z : c10::irange(begin, end)) { + auto global_max = -std::numeric_limits::infinity(); + auto global_exp_sum = 0.0; + + // Calculate the global max and exp_sum for this head + global_max = at::vec::reduce_all( + [](Vec& x, Vec& y) { return at::vec::maximum(x, y); }, + max_logits_ptr + i * max_logits_strideN + + j * max_logits_strideH, + num_partitions); + + // Update the partition 0 result with the global max + auto partition0_out_start = + tmp_out_ptr + i * tmp_out_strideN + j * tmp_out_strideH; + auto max_logit0 = max_logits_ptr + [i * max_logits_strideN + j * max_logits_strideH]; + float exp_val = std::exp(max_logit0 - global_max); + global_exp_sum = + exp_sum_ptr[i * exp_sum_strideN + j * exp_sum_strideH] * + exp_val; + at::vec::map( + [exp_val](Vec x) { return x * Vec(exp_val); }, + partition0_out_start, + partition0_out_start, + headSize_v); + + // Accumulate the partition 1 to partition n result into partition 0 + if (num_partitions > 1) { + for (auto partition_id = 1; partition_id < num_partitions; + partition_id++) { + auto tmp_out_start = partition0_out_start + partition_id * tmp_out_strideS; + auto max_logit = max_logits_ptr + [i * max_logits_strideN + j * max_logits_strideH + + partition_id]; + auto exp_sum = exp_sum_ptr + [i * exp_sum_strideN + j * exp_sum_strideH + + partition_id]; + exp_val = std::exp(max_logit - global_max); + global_exp_sum += exp_sum * exp_val; + at::vec::map2( + [exp_val](Vec a, Vec b) { return a + Vec(exp_val) * b; }, + partition0_out_start, + partition0_out_start, + tmp_out_start, + headSize_v); + } + } + + // Rescale the partition 0 result with global exp_sum + // Sum for full masked out rows are 0, we set them to 1 + // in order to avoid NaNs in the output and instead set fully + // masked out rows to 0 + global_exp_sum = global_exp_sum == 0 ? 1 : global_exp_sum; + float sum_reciprocal = 1.0 / global_exp_sum; + // copy the partition 0 result into output + at::vec::map( + [sum_reciprocal](Vec x) { return x * Vec(sum_reciprocal); }, + out_data + i * oStrideB + j * oStrideH, + partition0_out_start, + headSize_v); + + // Move to the next query + at::native::data_index_step(i, batchSize, j, num_head); + } + + }); +} +""" + + +class CppFlexAttentionTemplate(CppTemplate): + """ + CPP template based FlexAttention CPP Template. + + This class supports generation of C++ code for broad attention variants, + with applying Flash Attention and Flash Decoding. It enables template-based + code synthesis according to user-defined score and mask modifications + and configuration settings. + """ + + def __init__( + self, + input_nodes, + layout: ir.Layout, + scale, + score_mod, + mask_mod, + kv_block_size, + q_block_size, + partition_size, + has_other_buffer, + no_full_kv_block, + fake_buffers, + len_score_other, + len_mask_other, + kernel_input_name_to_buffer, + block_vars, + ) -> None: + if layout.dtype not in [torch.float, torch.bfloat16, torch.float16]: + raise AssertionError(f"unsupported layout dtype: {layout.dtype}") + super().__init__("flex_attention", input_nodes, layout, parallel_num_threads()) + self.scale = scale + self.score_mod = score_mod + self.mask_mod = mask_mod + self.score_buf_name = ( + V.graph.register_buffer(self.score_mod) if self.score_mod else None + ) + self.mask_buf_name = ( + V.graph.register_buffer(self.mask_mod) if self.mask_mod else None + ) + + def get_idx(buf_name): + match = re.search(r"\d+", buf_name) + if not match: + raise AssertionError(f"incorrect score buf name: {buf_name}") + return match.group() + + self.score_buf_idx = ( + get_idx(self.score_buf_name) if self.score_buf_name else None + ) + self.mask_buf_idx = get_idx(self.mask_buf_name) if self.mask_buf_name else None + self.kv_block_size = kv_block_size + self.q_block_size = q_block_size + self.partition_size = partition_size + self.has_other_buffer = has_other_buffer + self.no_full_kv_block = no_full_kv_block + self.other_buffer_input_offset = 2 + if self.no_full_kv_block: + self.other_buffer_input_offset = 0 + self.fake_buffers = fake_buffers + self.len_score_other = len_score_other + self.len_mask_other = len_mask_other + self.kernel_input_name_to_buffer = kernel_input_name_to_buffer + self.block_vars = block_vars + self.extra_sizevars = list( + OrderedSet( + val + for val in self.kernel_input_name_to_buffer.values() + if isinstance(val, sympy.Symbol) + ) + ) + self.other_buf_start_idx = 5 + self.score_mod_other_buffers = ( + self.input_nodes[ + self.other_buf_start_idx + + self.other_buffer_input_offset : self.other_buf_start_idx + + self.other_buffer_input_offset + + self.len_score_other + ] + if self.has_other_buffer + else None + ) + self.mask_mod_other_buffers = ( + self.input_nodes[ + self.other_buf_start_idx + + self.other_buffer_input_offset + + self.len_score_other : + ] + if self.has_other_buffer + else None + ) + self.other_ptr_data = {} # type: ignore[var-annotated] + + def update_kernel_args(self, kernel_args): + kernel_args.update( + { + key: value + for key, value in self.kernel_input_name_to_buffer.items() + if not isinstance(value, sympy.Symbol) + } + ) + return kernel_args + + def generate_other_buffer(self, buf_list, start_offset, len_attr, kernel_args): + kernel_input_name_to_buffer_name = { + key: value if isinstance(value, sympy.Symbol) else value.get_name() + for key, value in self.kernel_input_name_to_buffer.items() + } + + def get_arg(name): + return kernel_input_name_to_buffer_name.get(name) + + def get_arg_name(name): + if isinstance(get_arg(name), sympy.Symbol): + return kernel_args.sizevars.get(get_arg(name)) + return kernel_args.input_buffers.get(get_arg(name)) + + if not self.has_other_buffer: + return "" + + if start_offset == -1: + start_offset = self.len_score_other + + length = getattr(self, len_attr) + for i in range(length): + pointer = f"in_ptr{self.other_buf_start_idx + start_offset + i}" + buffer_key = f"{buf_list}_{i}" + if pointer not in self.other_ptr_data: + self.other_ptr_data[pointer] = ( + get_arg_name(buffer_key), + get_arg(buffer_key), + ) + + return "\n".join( + f"auto {ptr} = {name};" for ptr, (name, _) in self.other_ptr_data.items() + ) + + def modification(self, subgraph_buffer, output_name, output_idx): + if not isinstance(subgraph_buffer, ir.ComputedBuffer): + raise AssertionError( + f"expected ir.ComputedBuffer, got {type(subgraph_buffer)}" + ) + subgraph_buffer_data = subgraph_buffer.data + from ..loop_body import LoopBody + from ..utils import sympy_index_symbol_with_prefix, SymT + from ..virtualized import V + from .cpp import CppKernelProxy, KernelGroup, ParallelDepth + + kernel_group = KernelGroup() + kernel_input_args = { + "score": "in_ptr0", + "b": "in_ptr1", + "h": "in_ptr2", + "q_idx": "in_ptr3", + "kv_idx": "in_ptr4", + } + if self.has_other_buffer: + kernel_input_args.update( + {arg: ptr for ptr, (_, arg) in self.other_ptr_data.items()} + ) + + kernel_output_args = {output_name: f"out_ptr{output_idx}"} + + args = kernel_group.args + for name, inp in kernel_input_args.items(): + args.input_buffers[name] = inp + + for name, inp in kernel_output_args.items(): + args.output_buffers[name] = inp + + for name in self.extra_sizevars: + args.sizevars[name] = f"k{name}" + + kernel_group.args = args + + cpp_kernel_proxy = CppKernelProxy(kernel_group) + bodies = [] + var_sizes_list = [] + var_sizes = tuple(subgraph_buffer.get_size()) + var_ranges = { + sympy_index_symbol_with_prefix(SymT.INDEX, i): sz + for i, sz in enumerate(var_sizes) + } + + dst_layout = subgraph_buffer.get_layout() + output_index = dst_layout.make_indexer()([*var_ranges.keys()]) + + def fn(*args): + V.ops.store( + output_name, + output_index, + subgraph_buffer_data.make_loader()(args).value, + ) + + body = LoopBody( + fn, + (list(var_ranges.keys())), + var_ranges, + list(var_ranges.keys()), + tuple(), + ) + + from ..loop_body import MemoryUsageType + + if not all( + mem.buffer_name in kernel_group.args.input_buffers + for mem in body.memory_usage[MemoryUsageType.LOAD] + ): + raise AssertionError( + "All the buffers in the score and mask subgraph should be in kernel_group.args.input_buffers" + ) + + bodies.append(body) + var_sizes_list.append((var_sizes, ())) + + cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list) + + def max_parallel_depth(): + return ParallelDepth(parallel_depth=0, start_depth=0) + + # This loop is not parallelized since it is not the outermost loop. + with patch.object( + cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth + ): + kernel_group.finalize_kernel(cpp_kernel_proxy, []) + output_code = kernel_group.loops_code.getvalue() + + var_q_symbol, var_kv_symbol = self.block_vars + # See [Note] Handle the case where the split sizes are not statically known. + # We don't know the value of qBlockSize and rkvBlockSize during compilation time + # thus we've represented them by symbols. + # We change the symbol strings back to "cur_qSplitSize" and "cur_kvSplitSize" + # in the generated code thus they'll be filled with the real value during runtime. + if var_q_symbol in kernel_group.args.sizevars: + output_code = output_code.replace( + kernel_group.args.sizevars[var_q_symbol], "cur_qSplitSize" + ) + if var_kv_symbol in kernel_group.args.sizevars: + output_code = output_code.replace( + kernel_group.args.sizevars[var_kv_symbol], "cur_kvSplitSize" + ) + + return output_code + + @staticmethod + def add_choices( + choices, + input_nodes, + layout, + scale, + score_mod, + mask_mod, + kv_block_size, + q_block_size, + partition_size, + has_other_buffer, + no_full_kv_block, + fake_buffers, + len_score_other, + len_mask_other, + kernel_input_name_to_buffer, + block_vars, + ): + def preprocessor(input_nodes, layout): + return input_nodes, layout + + def postprocessor(output): + return output + + template = DataProcessorTemplateWrapper( + CppFlexAttentionTemplate, + preprocessor, + postprocessor, + input_nodes=input_nodes, + layout=layout, + scale=scale, + score_mod=score_mod, + mask_mod=mask_mod, + kv_block_size=kv_block_size, + q_block_size=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_other, + len_mask_other=len_mask_other, + kernel_input_name_to_buffer=kernel_input_name_to_buffer, + block_vars=block_vars, + ) + template.maybe_append_choice(choices) + return template + + def apply_score_mod(self, score, b, h, q_idx, kv_idx): + return self.score_mod.graph_module(score, b, h, q_idx, kv_idx).item() + + def choose_flex_template( + self, + query: ir.Buffer, + key: ir.Buffer, + num_threads, + ): + # choose from FLEX_ATTENTION or FLEX_DECODING + FLEX_TEMPLATE = FLEX_ATTENTION_TEMPLATE + q_batch_size, q_num_heads, q_seq_len, _ = query.data.data.layout.size # type: ignore[attr-defined] + k_seq_len = key.data.data.layout.size[2] # type: ignore[attr-defined] + if all( + sympy.sympify(val).is_number + for val in [q_batch_size, q_num_heads, q_seq_len, k_seq_len, num_threads] + ): + # if static shape, FLEX_DECODING will be chosen with these conditions: + # 1) partition size is multiple of kv block size, so each partition has several blocks + # 2) decoding scenario: q seq length is 1 + # 3) The actual k seq length (k_seq_len / q_batch_size) is large enough + if ( + self.partition_size % self.kv_block_size == 0 + and q_seq_len == 1 + and k_seq_len / q_batch_size >= max(self.partition_size * 2, 512) + ): + FLEX_TEMPLATE = FLEX_DECODING_TEMPLATE + return FLEX_TEMPLATE + + def render( # type: ignore[override,return] + self, + kernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + **kwargs, + ) -> str: + if epilogue_nodes is not None and epilogue_nodes != []: + raise NotImplementedError( + "Unsupported for `epilogue_nodes` in CppFlexAttentionTemplate." + ) + # Query (Batch x Num_heads x Q_seq_len x Dim_per_head) + # -> (Batch x Q_seq_len x Num_heads x Dim_per_head) + # Key (Batch x Num_heads x KV_seq_len x Dim_per_head) + # -> (Batch x KV_seq_len x Num_heads x Dim_per_head) + # Value (Batch x Num_heads x KV_seq_len x Dim_per_head) + # -> (Batch x KV_seq_len x Num_heads x Dim_per_head) + + query = kernel.permute(self.input_nodes[0], [0, 2, 1, 3]) + key = kernel.permute(self.input_nodes[1], [0, 2, 1, 3]) + value = kernel.permute(self.input_nodes[2], [0, 2, 1, 3]) + self.accumulate_dtype = torch.float + self.input_dtype = query.layout.dtype + + num_threads = parallel_num_threads() + if not isinstance(self.output_node, ir.IRNode): + raise AssertionError(f"expected ir.IRNode, got {type(self.output_node)}") + buf_out = TensorBox.create(self.output_node) + if template_buffer_node is not None: + buf_out = template_buffer_node + options = dict( + query=query, + key=key, + value=value, + kv_num_blocks=self.input_nodes[3], + kv_indices=self.input_nodes[4], + full_kv_num_blocks=( + self.input_nodes[5] if not self.no_full_kv_block else None + ), + full_kv_indices=self.input_nodes[6] if not self.no_full_kv_block else None, + score_mod_other_buffers=self.score_mod_other_buffers, + mask_mod_other_buffers=self.mask_mod_other_buffers, + scale=self.scale, + has_full_kv_block=not self.no_full_kv_block, + accumulate_dtype=self.accumulate_dtype, + query_dtype=self.input_dtype, + kvBlockSize=self.kv_block_size, + qBlockSize=self.q_block_size, + template=self, + output=buf_out, + kernel=kernel, + num_thread=num_threads, + score_mod=self.score_mod, + mask_mod=self.mask_mod, + score_buf_name=self.score_buf_name, + mask_buf_name=self.mask_buf_name, + score_buf_idx=self.score_buf_idx, + mask_buf_idx=self.mask_buf_idx, + partition_size=self.partition_size, + ) + with contextlib.ExitStack() as stack: + for buf in self.fake_buffers: + stack.enter_context( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf)) + ) + FLEX_TEMPLATE = self.choose_flex_template(query, key, num_threads) + return self._template_from_string(INIT_PARAMS + FLEX_TEMPLATE).render( + **options + ) + + def codegen_softmax_fusion(self, kernel_name: str): + # TODO: use inductor IR to rewrite those fusions + return self._template_from_string(SOFTMAX_FUSIONS).render( + dict(kernel_name=kernel_name) + ) + + def codegen_brgemm_pack_function(self, kernel_name: str): + # TODO: make them general for common bmm templates + return self._template_from_string(BRGEMM_PACK_FUNCTIONS).render( + dict(kernel_name=kernel_name) + ) + + def codegen_allocate_buffer(self, buffer_name: str, buffer_dtype, buffer_size): + return self._template_from_string(ALLOCATE_BUFFER).render( + dict( + buffer_name=buffer_name, + buffer_dtype=buffer_dtype, + buffer_size=buffer_size, + ) + ) + + def micro_gemm_define(self, kernel_name: str): + from torch._inductor.codegen.cpp_gemm_template import ( + CppTemplateKernel, + parallel_num_threads, + ) + from torch._inductor.codegen.cpp_micro_gemm import CppMicroGemmFP32Vec + from torch._inductor.virtualized import V + + micro_gemm_trans = CppMicroGemmFP32Vec( + kernel_name + "_kernel_micro_gemm_transpose_b", + self.input_dtype, + self.input_dtype, + self.accumulate_dtype, + self.accumulate_dtype, + GemmBlocking(1, 16, 1), + 1, + True, + True, + ) + + micro_gemm = CppMicroGemmFP32Vec( + kernel_name + "_kernel_micro_gemm", + self.input_dtype, + self.input_dtype, + self.accumulate_dtype, + self.accumulate_dtype, + GemmBlocking(1, 16, 1), + 1, + True, + False, + ) + + with V.set_graph_handler(V.graph): + kernel = CppTemplateKernel("cpp_micro_gemm", parallel_num_threads()) + code_trans = micro_gemm_trans.codegen_define(kernel) + code = micro_gemm.codegen_define(kernel) + return code + code_trans + + def codegen_micro_gemm(self, kernel_name: str): + micro_gemm = self.micro_gemm_define(kernel_name) + GEMM_SOURCE_CODE = MICRO_GEMM_TEMPLATE.replace("GEMM_DEFINE", micro_gemm) + return self._template_from_string(GEMM_SOURCE_CODE).render() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_gemm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_gemm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7f52ed420e051b8a9b9ac70fdca5d8233369f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_gemm_template.py @@ -0,0 +1,1968 @@ +# mypy: allow-untyped-defs +import contextlib +import logging +import math +import os +from collections.abc import Callable +from functools import lru_cache +from typing import Any, cast, TypeVar +from unittest.mock import patch + +import torch +import torch.utils +from torch.utils._ordered_set import OrderedSet + +from ..._dynamo.utils import counters +from .. import config, ir, lowering as L +from ..kernel.mm_common import mm_args +from ..select_algorithm import DataProcessorTemplateWrapper +from ..utils import ( + has_free_symbols, + is_same_mkldnn_tensor, + is_same_tensor, + parallel_num_threads, +) +from ..virtualized import ops, V +from .cpp import get_export_declaration +from .cpp_micro_gemm import ( + CppMicroBrgemm, + CppMicroGemm, + CppMicroGemmAMX, + CppMicroGemmFP32Vec, + create_micro_gemm, + is_int8_woq_gemm_small_m_dim_corner_case, + LayoutType, +) +from .cpp_template import CppTemplate +from .cpp_template_kernel import CppTemplateKernel +from .cpp_utils import ( + create_epilogue_with_attr, + DTYPE_TO_CPP, + GemmBlocking, + get_gemm_template_output_and_compute_dtype, +) + + +log = logging.getLogger(__name__) + +GEMM_TEMPLATE_INIT_BLOCKING_BASIC_BLOCK = r""" + constexpr int64_t num_threads = {{num_threads}}; + constexpr int64_t N = {{N}}; + constexpr int64_t K = {{K}}; + constexpr int64_t Mr = {{micro_gemm.register_blocking.block_m}}; + constexpr int64_t Nr = {{micro_gemm.register_blocking.block_n}}; + constexpr int64_t Kr = {{micro_gemm.register_blocking.block_k}}; + constexpr int64_t Nr_blocks = (N + Nr - 1) / Nr; + constexpr int64_t Kr_blocks = (K + Kr - 1) / Kr; +{%- if is_dynamic_M %} + const int64_t M = {{kernel.size(GemmOut, 0)}}; + const int64_t Mr_blocks = (M + Mr - 1) / Mr; +{%- else %} + constexpr int64_t M = {{kernel.size(GemmOut, 0)}}; + constexpr int64_t Mr_blocks = (M + Mr - 1) / Mr; +{%- endif %} +""" + +GEMM_TEMPLATE_INIT_BLOCKING_EXTENDED = r""" +{%- if is_dynamic_M %} + {%- if num_threads > 1 %} + int64_t Mt_blocks, Nt_blocks, Kt_blocks; + mm_get_thread_blocking(num_threads, {{config.cpp.gemm_max_k_slices}}, M, N, K, Mr, Nr, Kr, Mt_blocks, Nt_blocks, Kt_blocks); + {%- else %} + const auto Mt_blocks = Mr_blocks; + const auto Nt_blocks = Nr_blocks; + const auto Kt_blocks = Kr_blocks; + {%- endif %} + int64_t Mc_blocks, Nc_blocks, Kc_blocks; + uint32_t L1_cache_size = {{L1_cache_size}}; + uint32_t L2_cache_size = {{L2_cache_size}}; + mm_get_cache_blocking<{{kernel.dtype(X)}}, {{kernel.dtype(W)}}>( + num_threads, + M, + N, + K, + Mr, + Nr, + Kr, + Mt_blocks, + Nt_blocks, + Kt_blocks, + Mc_blocks, + Nc_blocks, + Kc_blocks, + L1_cache_size, + L2_cache_size + ); + const int64_t num_Mc_blocks = (Mr_blocks + Mc_blocks - 1) / Mc_blocks; + const int64_t num_Nc_blocks = (Nr_blocks + Nc_blocks - 1) / Nc_blocks; + const int64_t num_Mt_blocks = (Mr_blocks + Mt_blocks - 1) / Mt_blocks; + const int64_t num_Nt_blocks = (Nr_blocks + Nt_blocks - 1) / Nt_blocks; + const int64_t num_Kt_blocks = (Kr_blocks + Kt_blocks - 1) / Kt_blocks; +{%- else %} + constexpr int64_t Mt_blocks = {{template.thread_blocking(num_threads).block_m}}; + constexpr int64_t Nt_blocks = {{template.thread_blocking(num_threads).block_n}}; + constexpr int64_t Kt_blocks = {{template.thread_blocking(num_threads).block_k}}; + constexpr int64_t Mc_blocks = {{template.cache_blocking(num_threads).block_m}}; + constexpr int64_t Nc_blocks = {{template.cache_blocking(num_threads).block_n}}; + constexpr int64_t Kc_blocks = {{template.cache_blocking(num_threads).block_k}}; + constexpr int64_t num_Mc_blocks = (Mr_blocks + Mc_blocks - 1) / Mc_blocks; + constexpr int64_t num_Nc_blocks = (Nr_blocks + Nc_blocks - 1) / Nc_blocks; + constexpr int64_t num_Mt_blocks = (Mr_blocks + Mt_blocks - 1) / Mt_blocks; + constexpr int64_t num_Nt_blocks = (Nr_blocks + Nt_blocks - 1) / Nt_blocks; + constexpr int64_t num_Kt_blocks = (Kr_blocks + Kt_blocks - 1) / Kt_blocks; +{%- endif %} +{%- if is_woq_int4 %} + int64_t group_size = *q_group_size; +{%- endif %} + + // make sure all partitions are assigned + {{kernel.assert_function}}( + Mt_blocks * Nt_blocks * Kt_blocks * {{num_threads}} >= Mr_blocks * Nr_blocks * Kr_blocks, + "Not all partitions are assigned." + ); +""" + +GEMM_TEMPLATE_MULTI_THREADS_PARAMS = r""" +const int64_t k_group_id = tid / num_Kt_blocks; +const int64_t k_slice_id = tid % num_Kt_blocks; +const int64_t n_group_id = k_group_id / num_Nt_blocks; +const int64_t n_slice_id = k_group_id % num_Nt_blocks; +const int64_t k_block_start = k_slice_id * Kt_blocks; +const int64_t k_block_end = std::min(k_block_start + Kt_blocks, Kr_blocks); +const int64_t n_block_start = n_slice_id * Nt_blocks; +const int64_t n_block_end = std::min(n_block_start + Nt_blocks, Nr_blocks); +const int64_t m_block_start = std::min(n_group_id * Mt_blocks, Mr_blocks); +const int64_t m_block_end = std::min(m_block_start + Mt_blocks, Mr_blocks); +const int64_t num_Mc_blocks_per_thread = (m_block_end - m_block_start + Mc_blocks - 1) / Mc_blocks; +""" + +GEMM_TEMPLATE_SINGLE_THREAD_PARAMS = r""" +constexpr int tid = 0; +constexpr int64_t k_group_id = 0; +constexpr int64_t k_slice_id = 0; +constexpr int64_t n_group_id = 0; +constexpr int64_t n_slice_id = 0; +constexpr int64_t m_block_start = 0; +constexpr int64_t n_block_start = 0; +constexpr int64_t n_block_end = Nr_blocks; +constexpr int64_t k_block_start = 0; +constexpr int64_t k_block_end = Kr_blocks; +{%- if is_dynamic_M %} +const int64_t num_Mc_blocks_per_thread = num_Mc_blocks; +const int64_t m_block_end = Mr_blocks; +{%- else %} +constexpr int64_t num_Mc_blocks_per_thread = num_Mc_blocks; +constexpr int64_t m_block_end = Mr_blocks; +{%- endif %} +""" + +GEMM_TEMPLATE_M_LOOP_PARAMS = r""" +const int64_t my_mc_block_id = (mc_block_id + n_slice_id) % num_Mc_blocks_per_thread; +const int64_t mc = m_block_start + my_mc_block_id * Mc_blocks; +const int64_t m_start = mc * Mr; +const int64_t m_end = std::min(std::min(mc + Mc_blocks, m_block_end) * Mr, M); +const int64_t m_size = m_end - m_start; +""" + +GEMM_TEMPLATE_N_LOOP_PARAMS = r""" +const int64_t n_start = nc * Nr; +const int64_t n_end = std::min(std::min(nc + Nc_blocks, n_block_end) * Nr, N); +const int64_t n_size = n_end - n_start; +// NB: assume we pad N, nc_block_end won't exceed padded N here. +const int64_t nc_block_end = std::min(nc + Nc_blocks, n_block_end); +""" + +GEMM_TEMPLATE_MICROKERNEL_DEF = r""" +{{template.header().getvalue()}} + +{{micro_gemm.codegen_define(kernel)}} +""" + +GEMM_TEMPLATE_STUB_DEF = r""" +{%- if x_scale is not none %} + {%- set kernel_args = {"X": X, "W": W, "inp": inp, "x_scale": x_scale, "x_zp": x_zp, "w_scale": w_scale, "w_zp": w_zp,} %} +{%- elif is_woq_int4 %} + {%- set kernel_args = {"X": X, "W": W, "q_group_size": q_group_size, "qscale_and_zeros": qscale_and_zeros} %} +{%- else %} + {%- set kernel_args = {"X": X, "W": W, "inp": inp} %} +{%- endif %} + +extern "C" {{export_declaration}} +{{kernel.def_kernel(inputs=kernel_args, outputs={"Y": Y}, aliases=aliases)}} +""" + +GEMM_TEMPLATE = r""" +{{ template.codegen_gemm_stub_def() }} +{ + {{ kernel.maybe_codegen_profile(template.get_kernel_prefix_name()) }} + {{ template.codegen_blocks( + num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOut, config, L1_cache_size, L2_cache_size, X, W + ) }} + +{%- if maybe_k_slicing %} + std::unique_ptr[]> local_buf_ptrs; + const int64_t num_Mc_blocks_per_thread_block = (Mt_blocks + Mc_blocks - 1) / Mc_blocks; + const int64_t num_Nc_blocks_per_thread_block = (Nt_blocks + Nc_blocks - 1) / Nc_blocks; + if (num_Kt_blocks > 1) { + local_buf_ptrs.reset(new std::unique_ptr<{{DTYPE_TO_CPP[acc_buf_dtype]}}[]>[ + num_Mt_blocks * num_Nt_blocks * + num_Mc_blocks_per_thread_block * num_Nc_blocks_per_thread_block * + num_Kt_blocks + ]); + } +{%- endif %} + +{%- if num_threads > 1 %} + {%- set use_dynamic_threads = ((config.cpp.threads < 1) and (num_threads == cpu_count)) or config.cpp.dynamic_threads %} + {%- if use_dynamic_threads %} + #pragma omp parallel + {%- else %} + #pragma omp parallel num_threads({{num_threads}}) + {%- endif %} + { + {{ micro_gemm.codegen_init(kernel) }} + #pragma omp for schedule(static, 1) + for (int64_t tid = 0; tid < {{num_threads}}; tid++) { + {{ template.codegen_multi_threads_params()|indent(12, false) }} +{%- else %} + { + {{ template.codegen_single_thread_params(is_dynamic_M)|indent(8, false) }} + {{ micro_gemm.codegen_init(kernel) }} +{%- endif %} +{%- if use_local_acc %} + {%- set acc_buf_name = "local_acc_buf" %} + {{ kernel.define_buffer(acc_buf_name, ["Mc_blocks*Mr", "Nc_blocks*Nr"], acc_buf_dtype) }} +{%- endif %} + for (int64_t mc_block_id = 0; mc_block_id < num_Mc_blocks_per_thread; mc_block_id++) { + {{ template.codegen_m_loop_params()|indent(12, false) }} + for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) { + {{ template.codegen_n_loop_params()|indent(16, false) }} +{%- if use_local_acc %} + {%- set acc = kernel.local_buffers[acc_buf_name] %} + {{ kernel.reinit_buffer_if_null(acc_buf_name) }} +{%- else %} + {%- set acc = kernel.slice_nd(GemmOut, [("m_start", "m_end"), ("n_start", "n_end")]) %} +{%- endif %} + for (int64_t kc = k_block_start; kc < k_block_end; kc += Kc_blocks) { + int64_t k_start = kc * Kr; + int64_t k_end = std::min(std::min(kc + Kc_blocks, k_block_end) * Kr, K); +{%- set tile_X = kernel.slice_nd(X, [("m_start", "m_end"), ("k_start", "k_end")]) %} + for (int64_t nci = nc; nci < nc_block_end; nci++) { +{%- set acc_slice = kernel.slice_nd(acc, [("0", "m_end - m_start"), ("(nci - nc)*Nr", "(nci - nc + 1)*Nr")]) %} +{%- if template.should_block_weights and not is_woq_int4 %} +{%- set tile_W_3d = kernel.slice_nd(W, [("nci", "nci + 1"), ("k_start", "k_end"), ()]) %} +{%- set tile_W = kernel.view(tile_W_3d, ["k_end - k_start", micro_gemm.register_blocking.block_n]) %} +{%- else %} + {%- if is_woq_int4 %} + {%- set tile_W = kernel.slice_nd(W, [("nci * Nr", "(nci + 1) * Nr"), ("k_start * Nr / 2", "k_end * Nr / 2")]) %} + {%- set tile_qparam = kernel.slice_nd( + qscale_and_zeros, [("k_start // group_size", "k_end // group_size"), ("nci * Nr", "(nci + 1) * Nr"), ()]) %} + {%- else %} + {%- set tile_W = kernel.slice_nd(W, [("k_start", "k_end"), ("n_start", "n_start + n_size")]) %} + {%- set tile_qparam = None %} + {%- endif %} +{%- endif %} + if (kc == k_block_start) { + {{ micro_gemm.codegen_call(kernel, + tile_X, + tile_W, + acc_slice, + accum=False, + qscale_and_zeros=tile_qparam)|indent(28, false) + }} + } else { + {{ micro_gemm.codegen_call(kernel, + tile_X, + tile_W, + acc_slice, + accum=True, + qscale_and_zeros=tile_qparam)|indent(28, false) + }} + } + } + } +{%- if maybe_k_slicing %} + if (num_Kt_blocks > 1) { + const int64_t n_cache_block_id = (nc - n_block_start) / Nc_blocks; + const int64_t mxn_cache_block_id = + ((n_group_id * num_Nt_blocks + n_slice_id) * + num_Mc_blocks_per_thread_block + my_mc_block_id) * + num_Nc_blocks_per_thread_block + + n_cache_block_id; + local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks + k_slice_id].reset( + {{ kernel.release_buffer(acc_buf_name) }}); + } else +{%- endif %} + { +{%- set tile_Y = kernel.slice_nd(Y_2d, [("m_start", "m_end"), ("n_start", "n_end")]) %} +{%- set tile_acc = kernel.slice_nd(acc, [("0", "m_end - m_start"), ("0", "n_end - n_start")]) %} + {{ kernel.store_output( + tile_Y, tile_acc, GemmOut, epilogue_nodes, offsets=("m_start", "n_start"), reindexers=reindexers + )|indent(20, false) + }} + } + } + } +{%- if num_threads > 1 %} + } +{%- if maybe_k_slicing %} + if (num_Kt_blocks > 1) { + #pragma omp for schedule(static, 1) + for (int64_t tid = 0; tid < {{num_threads}}; tid++) { + {{ template.codegen_multi_threads_params()|indent(16, false) }} + for (int64_t mc = m_block_start; mc < m_block_end; mc += Mc_blocks) { + // We slice M-dim and each thread in the k-slicing group works on a slice + const int64_t m_start_unsliced = mc * Mr; + const int64_t m_end_unsliced = std::min(std::min(mc + Mc_blocks, m_block_end) * Mr, M); + const int64_t m_size_unsliced = m_end_unsliced - m_start_unsliced; + const int64_t m_slice_size = (m_size_unsliced + num_Kt_blocks - 1) / num_Kt_blocks; + const int64_t m_start = std::min(m_start_unsliced + m_slice_size * k_slice_id, m_end_unsliced); + const int64_t m_end = std::min(m_start_unsliced + m_slice_size * (k_slice_id + 1), m_end_unsliced); + const int64_t m_size = m_end - m_start; + const int64_t m_offset = m_start - m_start_unsliced; + const int64_t m_cache_block_id = (mc - m_block_start) / Mc_blocks; + for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) { + const int64_t n_start = nc * Nr; + const int64_t n_end = std::min(std::min(nc + Nc_blocks, n_block_end) * Nr, N); + const int64_t n_size = n_end - n_start; + const int64_t n_cache_block_id = (nc - n_block_start) / Nc_blocks; + const int64_t mxn_cache_block_id = + ((n_group_id * num_Nt_blocks + n_slice_id) * + num_Mc_blocks_per_thread_block + m_cache_block_id) * + num_Nc_blocks_per_thread_block + + n_cache_block_id; + auto {{acc_buf_name}} = local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks].get(); + for (int64_t other_slice = 1; other_slice < num_Kt_blocks; other_slice++) { + auto other_acc = local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks + other_slice].get(); + for (int64_t m = m_offset; m < m_offset + m_size; m++) { + #pragma omp simd + for (int64_t n = 0; n < n_size; n++) { + {{acc_buf_name}}[m*Nc_blocks*Nr + n] += other_acc[m*Nc_blocks*Nr + n]; + } + } + } + {%- set tile_Y_m_slice = kernel.slice_nd(Y_2d, [("m_start", "m_start + m_size"), ("n_start", "n_start + n_size")]) %} + {%- set tile_acc_full = kernel.slice_nd(acc, [("0", "m_size_unsliced"), ("0", "n_size")]) %} + {%- set tile_acc_m_slice = kernel.slice_nd(tile_acc_full, [("m_offset", "m_offset + m_size"), ()]) %} + {{ kernel.store_output( + tile_Y_m_slice, tile_acc_m_slice, GemmOut, epilogue_nodes, offsets=("m_start", "n_start"), reindexers=reindexers + )|indent(20, false) + }} + } + } + } + } +{%- endif %} + {{ micro_gemm.codegen_finalize(kernel) }} + } +{%- else %} + {{ micro_gemm.codegen_finalize(kernel) }} + } +{%- endif %} +} +""" + +SMALL_M_GEMM_TEMPLATE = r""" +{{ template.codegen_gemm_stub_def() }} +{ + {{ kernel.maybe_codegen_profile() }} + {{ template.codegen_blocks( + num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOut, config, L1_cache_size, L2_cache_size, X, W + ) }} + # pragma omp parallel + { + #pragma omp for nowait + for (int64_t nr_block_id = 0; nr_block_id < Nr_blocks; nr_block_id++) { + // Handle one output M * Nr block in each thread + int64_t n_start = nr_block_id * Nr; + int64_t n_end = (nr_block_id + 1) * Nr; +{%- if use_local_acc %} + {%- set acc_buf_name = "local_acc_buf" %} + {{ kernel.define_stack_allocated_buffer(acc_buf_name, ["M", "Nr"], acc_buf_dtype) }} + {%- set acc = kernel.local_buffers[acc_buf_name] %} +{%- else %} + {%- set acc = kernel.slice_nd(GemmOut, [(0, "M"), ("n_start", "n_end")]) %} +{%- endif %} + for (int64_t kr_block_id = 0; kr_block_id < Kr_blocks; kr_block_id++) { + // this loop is not parallelized + int64_t k_start = kr_block_id * Kr; + int64_t k_end = std::min((kr_block_id + 1) * Kr, K); +{%- set tile_X = kernel.slice_nd(X, [(0, "M"), ("k_start", "k_end")]) %} +{%- set tile_W_3d = kernel.slice_nd(W, [("nr_block_id", "nr_block_id + 1"), ("k_start", "k_end"), ()]) %} +{%- set tile_W = kernel.view(tile_W_3d, ["k_end - k_start", micro_gemm.register_blocking.block_n]) %} + if C10_UNLIKELY(kr_block_id == 0) { + {{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=False, prefetch=True)|indent(20, false) }} + } else if C10_UNLIKELY(k_end == K) { + {{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=True, prefetch=False)|indent(20, false) }} + } else { + {{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=True, prefetch=True)|indent(20, false) }} + } + } +{%- set tile_Y = kernel.slice_nd(Y_2d, [("0", "M"), ("n_start", "n_end")]) %} +{%- set tile_acc = kernel.slice_nd(acc, [("0", "M"), ("0", "n_end - n_start")]) %} + {{ kernel.store_output( + tile_Y, tile_acc, GemmOut, epilogue_nodes, offsets=("0", "n_start"), reindexers=reindexers + )|indent(20, false) }} + } + } +} +""" + + +def _is_int8_gemm(inputs): + return ( + isinstance(inputs[0], ir.IRNode) + and inputs[0].get_dtype() in [torch.uint8, torch.int8] + ) or ( + isinstance(inputs[0], torch.Tensor) + and inputs[0].dtype in [torch.uint8, torch.int8] + ) + + +def get_padded_n(n, block_n): + return (n + block_n - 1) // block_n * block_n + + +_T = TypeVar("_T", ir.IRNode, torch.Tensor) + + +def transpose_w(W: _T, trans_w: bool) -> _T: + """ + Transpose W based on the trans_w flag. + """ + if isinstance(W, ir.IRNode): + if trans_w: + if not isinstance(W, ir.TensorBox): + # pyrefly: ignore [bad-assignment] + W = ir.TensorBox(W) + W = L.permute(W, [1, 0]) + else: + if trans_w: + if not isinstance(W, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(W)}") + # pyrefly: ignore [bad-assignment] + W = W.transpose(0, 1) + # pyrefly: ignore [bad-return] + return W + + +def expand_bias(B: _T | None, X: _T) -> _T | None: + """ + Expand Bias to the same size of X. + """ + if B is not None: + if isinstance(B, ir.IRNode): + if not isinstance(B, ir.TensorBox): + # pyrefly: ignore [bad-assignment] + B = ir.TensorBox(B) + if not hasattr(X, "get_size"): + raise AssertionError("expected X to have a get_size attribute") + # pyrefly: ignore [missing-attribute] + B = L.expand(B, (X.get_size()[0], B.get_size()[-1])) + else: + if not isinstance(B, torch.Tensor): + raise AssertionError(f"expected B to be torch.Tensor, got {type(B)}") + if not isinstance(X, torch.Tensor): + raise AssertionError(f"expected X to be torch.Tensor, got {type(X)}") + # pyrefly: ignore [bad-assignment] + B = B.expand(X.shape[0], B.shape[-1]) + return B + + +def prune_tensors(input_nodes: list[ir.IRNode], new_input_nodes: list[ir.IRNode]): + """ + Prune unused tensors from `V.graph` since the GEMM Template use new packed weight. + """ + + def share_storage(base_tensor: torch.Tensor, comp_tensor: torch.Tensor): + return base_tensor.is_mkldnn == comp_tensor.is_mkldnn and ( + is_same_tensor(base_tensor, comp_tensor) + or is_same_mkldnn_tensor(base_tensor, comp_tensor) + ) + + def get_candidates(input_nodes, new_input_nodes): + # Only Constant Buffer like weight and bias might be changed in GEMM Template. + # The Inductor IR Node may changed, but still share the storage. For example: + # bias in bfloat16 case which only do the expand + return [ + node + for node in input_nodes + if ( + node not in new_input_nodes + and isinstance(node, (ir.TensorBox, ir.StorageBox)) + and node.get_name() in V.graph.constants + and not any( + ( + isinstance(new_node, (ir.TensorBox, ir.StorageBox)) + and new_node.get_name() in V.graph.constants + and share_storage( + V.graph.constants[node.get_name()], + V.graph.constants[new_node.get_name()], + ) + ) + for new_node in new_input_nodes + ) + ) + ] + + for candidate_node in get_candidates(input_nodes, new_input_nodes): + # By using the new packed weight for the GEMM template, we can prune the + # old weight if it has no other users. This saves memory but makes the FX graph + # non-retraceable. To support retracing, we can add a repack node to the + # FX graph. For example: + # mkldnn._linear_pointwise <- repack_linear_wgt <- packed_wgt_for_template + candidate_tensor_users = 0 + candidate_tensor = V.graph.constants[candidate_node.get_name()] + for node in reversed(V.graph.graph.nodes): + # Case may happen when the candidate tensor is used by more than 1 get_attr node + # https://github.com/pytorch/pytorch/issues/134998 + if node.op == "get_attr" and hasattr( + V.graph.module, node.target + ): # candidate tensor might already be deleted + comp_tensor = getattr(V.graph.module, node.target) + if isinstance(comp_tensor, torch.Tensor) and share_storage( + candidate_tensor, comp_tensor + ): + candidate_tensor_users += 1 + + for node in reversed(V.graph.graph.nodes): + # The get_attr node has only 1 user fx node + # The candidate tensor has been used by only 1 get_attr node + if ( + node.op == "get_attr" + and node.target == candidate_node.get_name() + and len(node.users) == 1 + and candidate_tensor_users == 1 + ): + del V.graph.constants[node.target] + delattr(V.graph.module, node.target) + delattr(V.graph.graph.owning_module, node.target) + counters["inductor"]["select_algorithm_weight_prune"] += 1 + + +def gen_2d_view_of_epilogue_buf( + Y: ir.Buffer, + template_buffer: ir.Buffer, + epilogue_nodes: list[ir.IRNode], + reindexers: list[Callable[[list[Any]], list[Any]] | None], + default_reindexers: list[Callable[[list[Any]], list[Any]] | None], +) -> tuple[ + ir.Buffer | ir.ReinterpretView, + list[Callable[[list[Any]], list[Any]] | None], +]: + """ + The dimension and the indexing could be different between the GEMM output, i.e. `template_buffer`, which is + 2D with MxN) and the output from the template after epilogues, i.e. `Y`. In the GEMM template code, + we are not aware of the dimension and the indexing of the epilogues and always work on 2D tiles according to + the indexing of the GEMM output. + In this function, we return a 2D buffer (`Y_2d`) according to GEMM output (reinterpreted from `Y` if needed) and + build a reindexer that converts the indexing of `Y` into `Y_2d`. + """ + Y_2d: ir.Buffer | ir.ReinterpretView = Y + if ( + Y.get_size() == template_buffer.get_size() + and Y.get_stride() == template_buffer.get_stride() + ): + reindexers.extend(default_reindexers) + Y_2d = Y + else: + + def get_reindexer(epilogue_node, default_reindexer=None): + # From template_buffer to epilogue_node_ordered (ordered by stride decreasingly, in dense format), for example: + # template_buffer: + # size (324, 512), stride (512, 1) + # epilogue_node_ordered (ordered by stride decreasingly, in dense format): + # size (1, 18, 18, 512), stride (165888, 9216, 512, 1) + stride_order = list( + ir.get_stride_order( + V.graph.sizevars.guarding_hints_or_throw(epilogue_node.get_stride()) + ) + ) + fill_order = ir.stride_order2fill_order(stride_order) + reversed_fill_order = list(reversed(fill_order)) + size_with_stride_ordered_decreasingly = [ + epilogue_node.get_size()[i] for i in reversed_fill_order + ] + reshape_reindex = ir.View.dynamic_reshape_indexer( + size_with_stride_ordered_decreasingly, + template_buffer.get_size(), + ) + if default_reindexer: + reshape_reindex = ir.fuse_reindexing(reshape_reindex, default_reindexer) + + # From epilogue_node_ordered (ordered by stride decreasingly, in dense format) to epilogue_node, for example: + # epilogue_node_ordered (ordered by stride decreasingly, in dense format): + # size (1, 18, 18, 512), stride (165888, 9216, 512, 1) + # epilogue_node: + # size (1, 18, 18, 512), stride (165888, 1, 9216, 512) + from_stride_ordered_decreasingly_to_epilogue_node_order = [ + (len(stride_order) - 1) - stride_order[i] + for i in range(len(stride_order)) + ] + stride_reindex = ir.same_reorder( + from_stride_ordered_decreasingly_to_epilogue_node_order + ) + + reindexer = ir.fuse_reindexing(stride_reindex, reshape_reindex) # type: ignore[var-annotated] + return reindexer + + if default_reindexers is None: + default_reindexers = [None] * len(epilogue_nodes) + new_reindexers = [ + get_reindexer(epilogue_node, default_reindexer) + for epilogue_node, default_reindexer in zip( + epilogue_nodes, default_reindexers + ) + ] + reindexers.extend(new_reindexers) + if isinstance(Y, ir.BaseView): + storage = ir.StorageBox(Y.unwrap_view()) + else: + if not isinstance(Y, ir.Buffer): + raise AssertionError(f"expected ir.Buffer, got {type(Y)}") + storage = ir.StorageBox(Y) + Y_2d = ir.ReinterpretView(data=storage, layout=template_buffer.get_layout()) + return Y_2d, reindexers + + +class CppGemmTemplate(CppTemplate): + """ + GEMM Template for Inductor CPP Backend. + """ + + def __init__( + self, + input_nodes, + layout: ir.Layout, + num_threads: int, + register_blocking: GemmBlocking, + beta=1, + alpha=1, + has_bias=False, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + should_block_weights: bool = True, + name="packed_gemm", + ) -> None: + if layout.dtype not in [ + torch.float, + torch.bfloat16, + torch.half, + torch.uint8, + torch.int8, + ]: + raise AssertionError(f"Unsupported layout dtype: {layout.dtype}") + super().__init__( + name, + input_nodes, + layout, + num_threads, + epilogue_creator=epilogue_creator, + ) + self.beta = beta + self.alpha = alpha + self.has_bias = has_bias + self.register_blocking = register_blocking + m, n = layout.size[-2:] + k = input_nodes[0].get_size()[-1] + self.m, self.n, self.k = m, n, k + self.padded_n = get_padded_n(n, self.register_blocking.block_n) + self.is_dynamic_M = has_free_symbols((m,)) + self.should_block_weights = should_block_weights + self.thread_blocking = self.make_thread_blocking_cache() + self.cache_blocking = self.make_cache_blocking_cache() + + def make_thread_blocking_cache(self): + cache = lru_cache()(self._thread_blocking) + + def thread_blocking(num_threads: int) -> GemmBlocking: + return cache(num_threads) + + return thread_blocking + + def _thread_blocking(self, num_threads: int) -> GemmBlocking: + """ + NOTE [Thread blocking in Cpp GEMM] + We use simple heuristics to decide the thread blocking: + 1. Make sure all threads are occupied as much as possible. + 2. For (m, n) blocks, favor more square-sized thread blocks for better data reuse. + 3. If (m, n) blocks cannot occupy all the threads, we consider k-slicing. + TODO(jgong5): allow tuning various blocking options + """ + + def get_factors(number): + factors = [] + for i in range(int(number**0.5), 0, -1): + if number % i == 0: + factors.append(number // i) + factors.append(i) + return factors + + def get_blocking(m_factor, n_factor, k_factor, m_blocks, n_blocks, k_blocks): + thread_block_k = math.ceil(k_blocks / k_factor) + thread_block_n = math.ceil(n_blocks / n_factor) + thread_block_m = math.ceil(m_blocks / m_factor) + return GemmBlocking(thread_block_m, thread_block_n, thread_block_k) + + if self.is_dynamic_M: + raise AssertionError("Unable to determine thread blocking for dynamic M.") + register_blocking = self.register_blocking + m_blocks = math.ceil(self.m / register_blocking.block_m) + n_blocks = math.ceil(self.n / register_blocking.block_n) + k_blocks = math.ceil(self.k / register_blocking.block_k) + factors = get_factors(num_threads) + if len(factors) == 0: + raise AssertionError(f"expected at least one factor, got {factors}") + + if config.cpp.gemm_thread_factors is not None: + factors = [int(i) for i in config.cpp.gemm_thread_factors.split(",")] + if len(factors) != 3: + raise AssertionError(f"expected 3 thread factors, got {len(factors)}") + if math.prod(factors) != self.num_threads: + raise AssertionError( + f"expected factors product == {self.num_threads}, " + f"got {math.prod(factors)}" + ) + return get_blocking( + factors[0], factors[1], factors[2], m_blocks, n_blocks, k_blocks + ) + + # we favor square-sized thread blocks for good data reuse + def get_better_blocking(blocking, best_blocking): + if best_blocking is None: + best_blocking = blocking + else: + block_m_size = blocking.block_m * register_blocking.block_m + block_n_size = blocking.block_n * register_blocking.block_n + best_block_m_size = best_blocking.block_m * register_blocking.block_m + best_block_n_size = best_blocking.block_n * register_blocking.block_n + if blocking.block_k > best_blocking.block_k: + best_blocking = blocking + elif ( + blocking.block_k == best_blocking.block_k + and block_m_size + block_n_size + < best_block_m_size + best_block_n_size + ): + best_blocking = blocking + return best_blocking + + best_blocking = None + # check if we can have a thread-blocking to occupy all threads without k-slicing + for n_factor in factors: + m_factor = num_threads // n_factor + if n_blocks >= n_factor and m_blocks >= m_factor: + blocking = get_blocking( + m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks + ) + best_blocking = get_better_blocking(blocking, best_blocking) + + if best_blocking is None: + for k_factor in factors: + if k_blocks >= k_factor and ( + config.cpp.gemm_max_k_slices == 0 + or k_factor <= config.cpp.gemm_max_k_slices + ): + n_factors = get_factors(num_threads // k_factor) + for n_factor in n_factors: + m_factor = (num_threads // k_factor) // n_factor + if n_blocks >= n_factor and m_blocks >= m_factor: + blocking = get_blocking( + m_factor, + n_factor, + k_factor, + m_blocks, + n_blocks, + k_blocks, + ) + best_blocking = get_better_blocking(blocking, best_blocking) + + if best_blocking is None: + for n_factor in factors: + m_factor = num_threads // n_factor + if n_blocks >= n_factor or m_blocks >= m_factor: + blocking = get_blocking( + m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks + ) + best_blocking = get_better_blocking(blocking, best_blocking) + + if best_blocking is None: + raise AssertionError("expected a valid thread blocking, got None") + return best_blocking + + def make_cache_blocking_cache(self): + cache = lru_cache()(self._cache_blocking) + + def cache_blocking(num_threads: int) -> GemmBlocking: + return cache(num_threads) + + return cache_blocking + + def _cache_blocking(self, num_threads: int) -> GemmBlocking: + def get_cache_blocking(register_blocking, thread_blocking): + Mr = register_blocking.block_m + Nr = register_blocking.block_n + Kr = register_blocking.block_k + + Mt_blocks = thread_blocking.block_m + Nt_blocks = thread_blocking.block_n + Kt_blocks = thread_blocking.block_k + + if config.cpp.gemm_cache_blocking is not None: + blockings = [int(i) for i in config.cpp.gemm_cache_blocking.split(",")] + if len(blockings) != 3: + raise AssertionError( + f"expected 3 cache blockings, got {len(blockings)}" + ) + Mc_blocks, Nc_blocks, Kc_blocks = blockings + return ( + min(Mc_blocks, Mt_blocks), + min(Nc_blocks, Nt_blocks), + min(Kc_blocks, Kt_blocks), + ) + + # The ratios below are empirically determined to decide + # the effective sizes of L1 and L2. + # TODO: tune the factor here + L1_limit_factor = 0.8 + L2_limit_factor = 0.5 + + L1_cache_size = torch.cpu.get_capabilities().get( + "l1d_cache_size", 0 + ) # per core cache size in Bytes + if L1_cache_size <= 0: + raise AssertionError( + f"Expect L1_cache_size > 0 but got {L1_cache_size}" + ) + L1 = L1_cache_size * L1_limit_factor + + L2_cache_size = torch.cpu.get_capabilities().get( + "l2_cache_size", 0 + ) # per core cache size in Bytes + if L2_cache_size <= 0: + raise AssertionError( + f"Expect L2_cache_size > 0 but got {L2_cache_size}" + ) + L2 = L2_cache_size * L2_limit_factor + + def get_num_byte(dtype): + return torch.tensor([], dtype=dtype).element_size() + + dtype_A = self.input_nodes[0].get_dtype() + dtype_B = self.input_nodes[1].get_dtype() + num_byte_A = get_num_byte(dtype_A) + num_byte_B = get_num_byte(dtype_B) + if dtype_A is torch.bfloat16 and dtype_B is torch.int8 and Kr != 1: + # We will cache dequantized weights (BF16) in L1D for AMX micro-kernel. + # In this case, the choice of the micro-kernel being used can't be decoupled from + # the cache blocking. + # TODO: Decouple the choice of micro-kernel from cache blocking + num_byte_B *= num_byte_A + + # NOTE [CPP GEMM Cache Blocking Algorithm] + # Our overall strategy is to + # 1) Make cache blocks of B L1-reside and reused by multiple rows of A, i.e. Mc. + # Here, B is Kc x Nr where Nr is a single register block. We use L1 size to + # decide Kc. We want to make Mc large enough to better reuse B. + # 2) Make cache blocks of A L2-reside, which would limit Mc. We want to reuse A + # along N, where we have two sub-strategies (see notes below) to decide Mc and Nc. + + # Step 1: Decide Kc assuming B block is L1-reside. + size_cache_B = Kr * Kt_blocks * Nr * num_byte_B + + Kc_blocks = Kt_blocks + if size_cache_B > L1: + Kc_blocks = math.floor(L1 / (Kr * Nr * num_byte_B)) + + if ( + config.cpp.use_small_dequant_buffer + and dtype_A is torch.bfloat16 + and Mt_blocks == 1 + ): + if dtype_B is torch.uint8: + # A16W4 + # Make a small dequant_B buffer for woq int4 [q_group_size, Nr] + # Since when Mt_blocks == 1, L1-reside B block can't be reused by A. + if Kc_blocks * Kr >= self.q_group_size(): + Kc_blocks = self.q_group_size() // Kr + + elif dtype_B is torch.int8: + # A16W8 + # Make A, B, C buffer in L1 + A_buf_size_div_K = self.m * num_byte_A + B_buf_size_div_K = Nr * num_byte_B + # assume acc in float32/int32 and Mc_blocks = Nc_blocks = 1 + C_buf_size = Mr * Nr * 4 + K_block_size = (L1 - C_buf_size) // ( + A_buf_size_div_K + B_buf_size_div_K + ) + if Kc_blocks * Kr >= K_block_size: + Kc_blocks = (K_block_size + Kr - 1) // Kr + + # Step 2: Decide Mc assuming A block is L2-reside. + min_Mc_ratio = 2 # TODO(jgong5): something to tune? + min_Mc_blocks = math.ceil(min_Mc_ratio * Mr / Nr) + if min_Mc_blocks < 1: + raise AssertionError( + f"expected min_Mc_blocks >= 1, got {min_Mc_blocks}" + ) + Kt_bytes = Kt_blocks * Kr * num_byte_A + if min_Mc_blocks * Mr * Kt_bytes < L2: + # Strategy 1: A (Mc x Kt) resides in L2 and reused by all Nt + # when Nc_blocks is kept 1. Mc should be large enough (>= min_Mc_blocks) + # to reuse B (Kc x Nr) in L1. This makes C (Mc x Nr) small enough to reside + # in L1. + Mc_blocks = min(Mt_blocks, math.floor(L2 / (Mr * Kt_bytes))) + Nc_blocks = 1 + else: + # Strategy 2: Kt is too large to hold A (Mc x Kt) in L2, we reuse + # A (Mc x Kc) in L2 by B (Kc x Nc). C (Mc x Nc) resides in L2. + Mc_blocks = Mt_blocks + Nc_blocks = min(math.ceil(Mc_blocks * Mr / Nr), Nt_blocks) + Nc_bytes = Nc_blocks * Nr * 4 # assume C or acc is float32/int32 + Kc_bytes = Kc_blocks * Kr * num_byte_A + if Mc_blocks * Mr * (Kc_bytes + Nc_bytes) > L2: + # The following is the solution for 4*Mc*Nc + Mc*Kc_bytes = L2, + # assuming Mc == Nc for good data reuse. + M_max = (math.sqrt(Kc_bytes * Kc_bytes + 16 * L2) - Kc_bytes) / 8 + if M_max < Mc_blocks * Mr: + Mc_blocks = math.floor(M_max / Mr) + Nc_blocks = min(math.ceil(Mc_blocks * Mr / Nr), Nt_blocks) + + return Mc_blocks, Nc_blocks, Kc_blocks + + if self.is_dynamic_M: + raise AssertionError("Unable to determine cache blocking for dynamic M.") + register_blocking = self.register_blocking + thread_blocking = self.thread_blocking(num_threads) + + return GemmBlocking(*get_cache_blocking(register_blocking, thread_blocking)) + + def log_blockings(self): + log.debug(f"Register blocking: {self.register_blocking}") # noqa: G004 + if self.is_dynamic_M: + # thread and cache blockings are determined at runtime for dynamic shapes + return + log.debug( + f"Cache blocking: {self.cache_blocking(self.num_threads)}" # noqa: G004 + ) + thread_blocking = self.thread_blocking(self.num_threads) + log.debug(f"Thread blocking: {thread_blocking}") # noqa: G004 + + def get_occupancy(): + m_blocks = math.ceil(self.m / self.register_blocking.block_m) + n_blocks = math.ceil(self.n / self.register_blocking.block_n) + k_blocks = math.ceil(self.k / self.register_blocking.block_k) + m = math.ceil(m_blocks / thread_blocking.block_m) + n = math.ceil(n_blocks / thread_blocking.block_n) + k = math.ceil(k_blocks / thread_blocking.block_k) + return (m, n, k) + + log.debug( + f"Number of threads: {self.num_threads}, occupancy: {get_occupancy()}" # noqa: G004 + ) + + def maybe_k_slicing(self): + if self.num_threads == 1: + return False + if self.is_dynamic_M: + # TODO(jgong5): perhaps use size hint to decide? + return True + register_blocking = self.register_blocking + k_blocks = math.ceil(self.k / register_blocking.block_k) + thread_blocking = self.thread_blocking(self.num_threads) + return k_blocks > thread_blocking.block_k + + @classmethod + def add_choices( + cls, + choices, + layout, + input_nodes, + beta=1, + alpha=1, + has_bias=False, + trans_w=False, + input_indices=None, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + act_mapping: dict[int, ir.IRNode] | None = None, + ): + """ + Add choices for the GEMM template. + """ + # Fast path to save the epilogue calculation when x_scale/x_zp/w_scale are constant + use_int8_fast_compensation_path = _is_int8_gemm(input_nodes) and all( + ( + isinstance(input_nodes[idx], ir.TensorBox) + and isinstance(input_nodes[idx].data.data, ir.ConstantBuffer) + ) + for idx in [1, 2, 4] + ) + + if input_indices is None: + input_indices = list(range(len(input_nodes))) + + deduped_input_indices = [] + deduped_name_to_idx: dict[str, int] = {} + for input_node in input_nodes: + input_name = input_node.get_name() + if input_name not in deduped_name_to_idx: + deduped_name_to_idx[input_name] = len(deduped_name_to_idx) + deduped_input_indices.append(deduped_name_to_idx[input_name]) + + def indices_for_inputs(inputs): + if len(inputs) == len(input_nodes): + return input_indices + if len(inputs) != len(deduped_name_to_idx): + raise AssertionError( + f"expected {len(deduped_name_to_idx)} inputs, got {len(inputs)}" + ) + return [deduped_input_indices[idx] for idx in input_indices] + + def reorder_and_filter(inputs, layout_or_out): + current_input_indices = indices_for_inputs(inputs) + if has_bias: + if len(current_input_indices) < 3: + raise AssertionError( + f"expected >= 3 input indices, got {len(current_input_indices)}" + ) + # Assume the input order is [inp, x, w] and we reorder it to [x, w, inp] + inp_idx = current_input_indices[0] + x_idx = current_input_indices[1] + w_idx = current_input_indices[2] + return [ + inputs[x_idx], + inputs[w_idx], + inputs[inp_idx], + *[inputs[idx] for idx in current_input_indices[3:]], + ], layout_or_out + else: + if len(current_input_indices) < 2: + raise AssertionError( + f"expected >= 2 input indices, got {len(current_input_indices)}" + ) + return [inputs[idx] for idx in current_input_indices], layout_or_out + + new_inputs, new_layout = reorder_and_filter(input_nodes, layout) + is_mkldnn_wgt = ( + new_inputs[1].get_name() in V.graph.constants + and V.graph.constants[new_inputs[1].get_name()].is_mkldnn + ) + if is_mkldnn_wgt: + # It shouldn't happen as viewing an mkldnn tensor, we can extend the + # implementation if it does. + if isinstance(new_inputs[1], ir.BaseView): + raise AssertionError("expected mkldnn weight to not be a BaseView") + # Note that the layout of MKLDNN Tensor is with the wrong stride + view_size = new_inputs[1].layout.size + view_stride = new_inputs[1].layout.stride + view_offset = new_inputs[1].layout.offset + + def maybe_to_dense(inputs, layout_or_out): + new_inputs = list(inputs) + if isinstance(inputs[1], torch.Tensor): + W = inputs[1] + new_inputs[1] = W.to_dense() if W.is_mkldnn else W + return new_inputs, layout_or_out + + def normalize_shapes(inputs, layout_or_out): + new_inputs = list(inputs) + if not is_mkldnn_wgt and isinstance(new_inputs[1], torch.Tensor): + if has_free_symbols(view_size): + # If batch size B is dynamic, we need to set the batch size and possibly stride + if has_free_symbols(view_size[1:]): + raise AssertionError( + "expected no free symbols in view_size[1:]" + ) + view_size[:] = V.graph.sizevars.guarding_hints_or_throw(view_size) + view_stride[:] = V.graph.sizevars.guarding_hints_or_throw( + view_stride + ) + # With the assumptation that W is the storage of unwrap view + # thus view it back here + new_inputs[1] = new_inputs[1].as_strided( + view_size, view_stride, view_offset + ) + + if not trans_w: + return new_inputs, layout_or_out + X = new_inputs[0] + W = new_inputs[1] + B = new_inputs[2] if has_bias else None + W = transpose_w(W, trans_w) + B = expand_bias(B, X) # type:ignore[arg-type] + new_inputs[1] = W + if B is not None: + new_inputs[2] = B + return new_inputs, layout_or_out + + # TODO(jgong5): decide proper number of threads per problem size + num_threads = parallel_num_threads() + new_inputs, _ = normalize_shapes(*maybe_to_dense(new_inputs, new_layout)) + m, n, k, *_ = mm_args( + new_inputs[0], + new_inputs[1], + mat2_transposed=cls.is_woq_int4(), + use_4x2_dim=cls.is_woq_int4(), + ) + output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype( + new_inputs[0].get_dtype() + ) + micro_gemm = create_micro_gemm( + "micro_gemm", + m, + n, + k, + input_dtype=new_inputs[0].get_dtype(), + input2_dtype=new_inputs[1].get_dtype(), + output_dtype=output_dtype, + compute_dtype=compute_dtype, + alpha=alpha, + num_threads=num_threads, + use_ref=not cls.is_woq_int4(), + q_group_size=cls.q_group_size(), + ) + if micro_gemm is None: + raise AssertionError("expected micro_gemm to be created, got None") + pre_block_weights = cls.check_if_block_weight(new_inputs[1], micro_gemm) + micro_gemm.use_local_vnni_blocking(not pre_block_weights) + cpp_arg_indices: list[int] | None = None + + def dedupe_runtime_inputs(inputs): + nonlocal cpp_arg_indices + if not isinstance(inputs[0], torch.Tensor): + cpp_arg_indices = [] + seen_names: OrderedSet[str] = OrderedSet() + for idx, input_node in enumerate(inputs): + input_name = input_node.get_name() + if input_name not in seen_names: + seen_names.add(input_name) + cpp_arg_indices.append(idx) + return inputs + if cpp_arg_indices is None: + raise AssertionError("expected cpp_arg_indices to be initialized") + return [inputs[idx] for idx in cpp_arg_indices] + + def preprocessor(inputs, layout): + new_inputs, new_layout = normalize_shapes( + *maybe_to_dense(*reorder_and_filter(inputs, layout)) + ) + new_inputs, new_layout = cls.prep_weight( + new_inputs, + new_layout, + # pyrefly: ignore [bad-argument-type] + micro_gemm, + pre_block_weights, + use_int8_fast_compensation_path, + ) + return dedupe_runtime_inputs(new_inputs), new_layout + + def postprocessor(output): + if isinstance(output, ir.TensorBox): + # prepack the weight as input to the template buffer + template_buffer = ir.InputsKernel.unwrap_storage_for_input(output) + if not isinstance(template_buffer, ir.CppTemplateBuffer): + raise AssertionError( + f"expected CppTemplateBuffer, got {type(template_buffer)}" + ) + new_input_nodes, _ = reorder_and_filter(input_nodes, layout) + + W_node = new_input_nodes[1] + if W_node.get_name() not in V.graph.constants: + return output + W = V.graph.constants[W_node.get_name()] + new_input_nodes[1] = W + new_input_nodes, new_layout = normalize_shapes( + *maybe_to_dense(new_input_nodes, layout) + ) + new_input_nodes, _ = cls.prep_weight( + new_input_nodes, + new_layout, + # pyrefly: ignore [bad-argument-type] + micro_gemm, + pre_block_weights, + use_int8_fast_compensation_path, + skip_int8_compensation=True, + ) + W_packed = new_input_nodes[1] + W_packed_constant = V.graph.add_tensor_constant(W_packed) + new_input_nodes[1] = W_packed_constant + + # Prune unused tensors + prune_tensors(input_nodes, new_input_nodes) + + template_buffer.inputs[1] = ir.InputsKernel.unwrap_storage_for_input( + W_packed_constant + ) + return output + + template = DataProcessorTemplateWrapper( + cls, + preprocessor, + postprocessor, + input_nodes=input_nodes, + layout=layout, + num_threads=num_threads, + register_blocking=micro_gemm.register_blocking, + beta=beta, + alpha=alpha, + has_bias=has_bias, + epilogue_creator=epilogue_creator, + should_block_weights=pre_block_weights, + name=micro_gemm.__class__.__name__, + ) + template.maybe_append_choice(choices) + return template + + @staticmethod + def get_padded_size(n, block_n, k, should_block_weight): + padded_n = get_padded_n(n, block_n) + # We assume that all GEMM weight tensors should be blocked and padded + new_size = [padded_n // block_n, k, block_n] + return new_size, padded_n + + @staticmethod + def _maybe_remove_storage_offset(node: ir.IRNode): + if node.get_layout().offset == 0: + return node + # node may be contiguous but still have a non-zero storage offset. + # GEMM_TEMPLATE emits code like: + # W.data_ptr[node.offset + ...] + # but runtime W.data_ptr (after normalize_shapes()) already includes this offset. + # To avoid double-offsetting, we remove the offset in the node also in the generated code. + # W.data_ptr[...] + return ir.ExternKernel.copy_input(node) + + @classmethod + def prep_weight( + cls, + inputs, + layout: ir.Layout, + micro_gemm: CppMicroGemm, + should_block_weight: bool, + use_int8_fast_compensation_path: bool = False, + skip_int8_compensation: bool = False, + ): + """ + NOTE Weight prep consists of 2 separate steps: + 1. Blocking the weight tensor into a 3D shape: [n//block_n, k, block_n] + This is always done if the weight tensor is constant, i.e. for all GEMM and some BMM. + For BMM, we also block non-contiguous weight tensors, since they would be reshaped anyway. + This assumes that blocked, contiguous weights will be more efficient for the GEMM kernel, + and is worth the overhead of reshape and blocking. + + This blocking includes additional padding, when n is not a multiple of block_n. + This padding allows a more efficient microkernel implementation. For BMM, this is only done + if reshape would happen anyway, i.e. if the weight tensor is constant, is not contiguous, + or is using AMX VNNI layout. + 2. Packing the weight tensor into a VNNI-friendly shape. For constant input, + this is done at the same time as the weight blocking. + + At compile time, the constant weight tensors are blocked and packed. For non-constant tensors (e.g. BMM) + which will be blocked (non-contiguous or VNNI-layout tensors), the weight tensor is blocked and packed at runtime. + + CppBmmTemplate overrides the methods get_padded_size, and block_weight in order to accommodate + an additional dimension for the batch size and to determine if the weight tensor should be blocked. + """ + W = inputs[1] + new_inputs = list(inputs) + if cls.is_woq_int4(): + if not ( + len(W.get_size()) == 2 + if isinstance(W, ir.IRNode) + else len(W.shape) == 2 + ): + raise AssertionError("expected WOQ int4 weight to be 2D") + n, k = W.get_size() if isinstance(W, ir.IRNode) else W.shape + else: + k, n = W.get_size()[-2:] if isinstance(W, ir.IRNode) else W.shape[-2:] + _, block_n, _ = micro_gemm.register_blocking + new_size, padded_n = cls.get_padded_size(n, block_n, k, should_block_weight) + padding = padded_n - n + + if should_block_weight and not cls.is_woq_int4(): + blocked_w = cls.block_weight(W, new_size, padding) + new_inputs[1] = cls.pack_vnni_weight(blocked_w, micro_gemm, new_size) + elif should_block_weight: + if not cls.is_woq_int4(): + raise AssertionError("expected WOQ int4 in this branch") + new_inputs[1] = cls.block_weight(W, new_size, padding) + elif isinstance(W, ir.IRNode): + # Require W layout to be fixed & contiguous, happens inplace. + ir.ExternKernel.require_contiguous(W) + new_inputs[1] = cls._maybe_remove_storage_offset(W) + + if not skip_int8_compensation and _is_int8_gemm(new_inputs): + BCompensate = None + x_w_scale = None + + def _get_compensation_node(W, use_int8_fast_compensation_path): + BCompensate = V.graph.add_tensor_constant( + V.graph.constants[W.get_name() + "_BMatrixCompens"], + W.get_name() + "_BMatrixCompens", + ) + x_w_scale = None + if use_int8_fast_compensation_path: + x_w_scale = V.graph.add_tensor_constant( + V.graph.constants[W.get_name() + "_x_w_compens"], + W.get_name() + "_x_w_compens", + ) + return BCompensate, x_w_scale + + if use_int8_fast_compensation_path: + # new_inputs has been reordered: [x, w, optional[bias], x_scale, x_zp, w_scale, w_zp] + x_scale = new_inputs[-4] + x_zp = new_inputs[-3] + w_scale = new_inputs[-2] + if isinstance(W, ir.IRNode): + BCompensate, x_w_scale = _get_compensation_node( + W, use_int8_fast_compensation_path + ) + else: + # Use the original W, not the blocked_w in new_inputs[1] to calculate BCompensate + BCompensate = torch.sum(W.to_dense().to(torch.float), dim=0) # type: ignore[assignment] + if not all( + isinstance(item, torch.Tensor) + for item in (x_scale, x_zp, w_scale) + ): + raise AssertionError( + "expected x_scale, x_zp, w_scale to be tensors" + ) + BCompensate = BCompensate * x_scale * w_scale * x_zp + x_w_scale = x_scale * w_scale + new_inputs.append(BCompensate) + new_inputs.append(x_w_scale) + else: + if isinstance(W, ir.IRNode): + BCompensate, _ = _get_compensation_node( + W, use_int8_fast_compensation_path + ) + else: + # Use the original W, not the blocked_w in new_inputs[1] to calculate BCompensate + BCompensate = torch.sum(W.to_dense().to(torch.float), dim=0) # type: ignore[assignment] + new_inputs.append(BCompensate) + return new_inputs, layout + + @staticmethod + def check_if_block_weight(W, micro_gemm): + return True + + @classmethod + def block_weight(cls, W, new_size, padding): + # These are separated into two methods to allow subclasses to override them separately + if isinstance(W, ir.IRNode): + if W.get_name() in V.graph.constants: + # Create a new buffer, representing the constant blocked tensor + blocked_w = ir.Buffer( + name=W.get_name(), # Borrow the registered buffer name + layout=ir.FixedLayout( + W.get_device_or_error(), + W.get_dtype(), + new_size, + ir.FlexibleLayout.contiguous_strides(new_size), + 0, + ), + ) + else: + if not isinstance(W, ir.TensorBox): + W = ir.TensorBox(W) + permute_dims = list(range(len(new_size))) + permute_dims[-2], permute_dims[-3] = permute_dims[-3], permute_dims[-2] + permute_size = list(new_size) + permute_size[-2], permute_size[-3] = permute_size[-3], permute_size[-2] + blocked_w = L.constant_pad_nd(W, (0, padding)) + blocked_w = L.permute( + L.view(blocked_w, permute_size), + permute_dims, + ) + else: + if not isinstance(W, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(W)}") + # Pad the weight tensor and reshape it into a 3D blocked shape + blocked_size = list(new_size) + blocked_size[-2], blocked_size[-3] = blocked_size[-3], blocked_size[-2] + blocked_w = ( + torch.nn.functional.pad(W, (0, padding)) # type: ignore[assignment] + .reshape(*blocked_size) + .transpose(-3, -2) + .contiguous() + ) + return blocked_w + + @classmethod + def pack_vnni_weight(cls, W, micro_gemm, new_size): + # WOQ INT4 weights are reordered in microkernel so do not pack them here + should_pack = ( + micro_gemm.get_b_layout() != LayoutType.NORMAL + and not micro_gemm.is_woq_int4() + ) + + # These are separated into two methods to allow subclasses to override them separately + if isinstance(W, ir.IRNode): + if isinstance(W, ir.Buffer) and W.get_name() in V.graph.constants: + return W + k = new_size[-2] + if not isinstance(W, ir.TensorBox): + W = ir.TensorBox(W) + if should_pack: + permute_dims = list(range(len(new_size) + 1)) + permute_dims[-1], permute_dims[-2] = permute_dims[-2], permute_dims[-1] + vnni_size = 4 if micro_gemm.get_b_layout() == LayoutType.VNNI4 else 2 + vnni_view_size = list(new_size) + vnni_view_size[-2] = k // vnni_size + vnni_view_size.insert(-1, vnni_size) + W = L.view( + L.permute(L.view(W, vnni_view_size), permute_dims), + new_size, + ) + W = ir.ExternKernel.realize_input(W) + W = ir.ExternKernel.require_contiguous(W) + return W + else: + k = new_size[-2] + # Apply VNNI packing to the weight tensor + if should_pack: + # TODO: Move VNNI weight packing for non-constant tensors into the template, + # to improve cache locality and avoid full-tensor copy. + layout_str = ( + "VNNI4" + if micro_gemm.get_b_layout() == LayoutType.VNNI4 + else "VNNI2" + ) + if micro_gemm.get_b_layout() not in [ + LayoutType.VNNI2, + LayoutType.VNNI4, + ]: + raise AssertionError(f"We only support {layout_str} for now") + vnni_size = 4 if micro_gemm.get_b_layout() == LayoutType.VNNI4 else 2 + if k % vnni_size != 0: + raise AssertionError( + f"k should be divisible by vnni_size for {layout_str} layout" + ) + vnni_view_size = list(new_size) + vnni_view_size[-2] = k // vnni_size + vnni_view_size.insert(-1, vnni_size) + W = W.view(vnni_view_size).transpose(-1, -2).reshape(new_size) + # normalize stride to be "contiguous_strides" per size + # this avoids the problems in L.view during template codegen + new_stride = [1] + for sz in reversed(W.shape[1:]): + new_stride.insert(0, new_stride[0] * sz) + W = W.as_strided(W.shape, new_stride) + return W + + def get_default_reindexers(self, epilogues): + return [None] * len(epilogues) + + def get_options( + self, + kernel: CppTemplateKernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + flag_template_buffer_has_other_users: bool | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + ) -> dict[str, Any]: + if len(self.input_nodes) < 2: + raise AssertionError( + f"expected >= 2 input nodes, got {len(self.input_nodes)}" + ) + + int8_gemm = self.input_nodes[0].get_dtype() in [torch.uint8, torch.int8] + x_scale = None + x_zp = None + w_scale = None + w_zp = None + inp = None + q_group_size_node = None + qscale_and_zeros = None + if int8_gemm: + X, W = self.input_nodes[0], self.input_nodes[1] + bias_idx = 2 if self.has_bias else 1 + inp = self.input_nodes[bias_idx] if self.has_bias else None + x_scale = self.input_nodes[bias_idx + 1] + x_zp = self.input_nodes[bias_idx + 2] + w_scale = self.input_nodes[bias_idx + 3] + w_zp = self.input_nodes[bias_idx + 4] + Y = self.output_node + elif self.is_woq_int4(): + X, W = self.input_nodes[0], self.input_nodes[1] + Y = self.output_node + q_group_size_node = self.input_nodes[2] + qscale_and_zeros = self.input_nodes[3] + else: + X, W = self.input_nodes[0], self.input_nodes[1] + Y = self.output_node + inp = self.input_nodes[2] if self.has_bias else None + + template_buffer_has_other_users = None + + if template_buffer_node is not None: + # Use the updated prepacked weight buffer + W = template_buffer_node.inputs[1] + Y = template_buffer_node + + if flag_template_buffer_has_other_users is None: + raise AssertionError( + "expected flag_template_buffer_has_other_users to be set" + ) + template_buffer_has_other_users = flag_template_buffer_has_other_users + + template_buffer = Y + gemm_output_buffer = template_buffer + + epilogues: list[ir.IRNode] = [] + reindexers: list[Callable[[list[Any]], list[Any]] | None] = [] + epilogue_creators: list[Callable[[ir.Buffer], ir.Pointwise]] = [] + fake_buffers: list[ir.Buffer] = [] + Y_aliases: OrderedSet[str] = OrderedSet() + + use_local_acc = ( + self.layout.dtype != torch.float + or template_buffer_has_other_users + or int8_gemm + or self.padded_n != self.n + or self.maybe_k_slicing() + or (epilogue_nodes and epilogue_nodes[-1].get_dtype() != self.layout.dtype) + ) + + # TODO(jgong5): for int8 gemm, bias-add is handled outside of gemm template, + # but we'd better move it here to align with fp. + if inp is not None and self.beta != 0 and not int8_gemm: + # add an epilogue for bias add + def _bias_add_epilogue(buf): + return create_epilogue_with_attr( + buf, "bias_add", other=inp, beta=self.beta, dtype=self.layout.dtype + ) + + epilogue_creators.append(_bias_add_epilogue) + + if self.epilogue_creator is not None: + epilogue_creators.append(self.epilogue_creator) + + # When the GEMM output buffer is localized but it has users other than the epilogue nodes, + # we need to copy the value in the GEMM output local buffer to a global buffer. + def need_copy_from_local_to_global_buffer_epilogue( + use_local_acc, template_buffer_has_other_users, epilogue_creators + ): + # The GEMM output buffer is a global buffer, thus copy is not needed. + if not use_local_acc: + return False + + # The possible value of template_buffer_has_other_users is (None, False, True) + # It is None when generating the gemm template during autotune and it will have value during scheduler codegen. + # extra copy_from_local_to_global_buffer_epilogue is not needed in either of the below two cases: + # 1. template_buffer_has_other_users is None (i.e. when doing the codegen during autotune) + # 2. template_buffer_has_other_users is False, which means it's safe to keep the value in the + # GEMM output buffer in local buffer only (no users outside of the epilogues will use its value). + if not template_buffer_has_other_users: + return False + + # When bias is not None or self.epilogue_creator is not None, + # there will be epilogue_creators after the GEMM. + # The GEMM output buffer is localized while + # the output buffer of the epilogue_creators is a global buffer. + if epilogue_creators: + return False + + return True + + if need_copy_from_local_to_global_buffer_epilogue( + use_local_acc, template_buffer_has_other_users, epilogue_creators + ): + + def copy_from_local_to_global_buffer_epilogue(input_buffer: ir.Buffer): + dtype = self.layout.dtype + input_loader = input_buffer.make_loader() + + def copy_inner(index): + input = input_loader(index) + result = ops.to_dtype(input, dtype) + return result + + return ir.Pointwise( + device=input_buffer.get_device_or_error(), + dtype=self.layout.dtype, + inner_fn=copy_inner, + ranges=input_buffer.get_size(), + ) + + epilogue_creators.append(copy_from_local_to_global_buffer_epilogue) + + # NOTE [How CPP GEMM template epilogues are organized] + # gemm_output_buffer + # --> zero or more in-template epilogues (created by `epilogue_creators`) --> + # template_buffer + # --> zero or more out-of-template epilogues (`epilogue_nodes`) --> + # Y + if epilogue_creators: + if not isinstance(template_buffer, ir.IRNode): + raise AssertionError(f"expected ir.IRNode, got {type(template_buffer)}") + gemm_output_name = f"{template_buffer.get_name()}_GemmOut" + gemm_output_buffer = ir.Buffer( + name=gemm_output_name, + # pyrefly: ignore [missing-attribute] + layout=template_buffer.layout, + ) + current_input_buffer = gemm_output_buffer + # In-template epilogues are built over the GEMM output buffer's ranges, + # whose rank can exceed that of the 2D tiles the template stores into + # (the BMM template keeps a leading batch dim). Let the template supply + # the reindexers mapping the 2D tile indices onto those ranges. + creator_reindexers = self.get_default_reindexers(epilogue_creators) + for i, creator in enumerate(epilogue_creators): + if i == len(epilogue_creators) - 1: + buffer_name = template_buffer.get_name() + else: + buffer_name = f"{gemm_output_name}_epilogue_{i}" + epilogues.append( + ir.ComputedBuffer( + name=buffer_name, + # pyrefly: ignore [missing-attribute] + layout=template_buffer.layout, + data=creator(current_input_buffer), + ) + ) + fake_buffers.append(current_input_buffer) + Y_aliases.add(current_input_buffer.get_name()) + reindexers.append(creator_reindexers[i]) + if i < len(epilogue_creators) - 1: + current_input_buffer = ir.Buffer( + name=buffer_name, + # pyrefly: ignore [missing-attribute] + layout=template_buffer.layout, + ) + + if not isinstance(Y, (ir.Buffer, ir.ReinterpretView)): + raise AssertionError( + f"expected ir.Buffer or ir.ReinterpretView, got {type(Y)}" + ) + Y_2d: ir.Buffer | ir.ReinterpretView = Y + + if epilogue_nodes: + if not template_buffer_has_other_users: + if not isinstance(template_buffer, ir.IRNode): + raise AssertionError( + f"expected ir.IRNode, got {type(template_buffer)}" + ) + Y_aliases.add(template_buffer.get_name()) + epilogues.extend(epilogue_nodes) + if Y.get_numel() != epilogues[-1].get_numel(): + raise AssertionError( + f"expected Y numel == epilogue numel, got {Y.get_numel()} " + f"and {epilogues[-1].get_numel()}" + ) + Y = cast(ir.Buffer, epilogues[-1]) + if not isinstance(template_buffer, ir.Buffer): + raise AssertionError(f"expected ir.Buffer, got {type(template_buffer)}") + Y_2d, reindexers = gen_2d_view_of_epilogue_buf( + Y, + template_buffer, + epilogue_nodes, + reindexers, + default_reindexers=self.get_default_reindexers(epilogue_nodes), + ) + + output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype( + X.get_dtype() + ) + micro_gemm = create_micro_gemm( + f"{kernel.kernel_name}_micro_gemm", + self.m, + self.n, + self.k, + input_dtype=X.get_dtype(), + input2_dtype=W.get_dtype(), + output_dtype=output_dtype, + compute_dtype=compute_dtype, + alpha=self.alpha, + num_threads=self.num_threads, + use_ref=not self.is_woq_int4(), + q_group_size=self.q_group_size(), + ) + if micro_gemm is None: + raise AssertionError("expected micro_gemm to be created, got None") + micro_gemm.use_local_vnni_blocking(not self.should_block_weights) + if self.register_blocking != micro_gemm.register_blocking: + raise AssertionError( + f"expected register_blocking == {micro_gemm.register_blocking}, " + f"got {self.register_blocking}" + ) + self.log_blockings() + if isinstance(micro_gemm, CppMicroGemmAMX): + counters["inductor"]["cpp_micro_gemm_amx_counter"] += 1 + if isinstance(micro_gemm, CppMicroBrgemm): + counters["inductor"]["cpp_micro_brgemm_counter"] += 1 + + L1_cache_size = torch.cpu.get_capabilities().get( + "l1d_cache_size", 0 + ) # per core cache size in Bytes + if L1_cache_size <= 0: + raise AssertionError(f"Expect L1_cache_size > 0 but got {L1_cache_size}") + + L2_cache_size = torch.cpu.get_capabilities().get( + "l2_cache_size", 0 + ) # per core cache size in Bytes + if L2_cache_size <= 0: + raise AssertionError(f"Expect L2_cache_size > 0 but got {L2_cache_size}") + + options = dict( + X=X, + W=W, + inp=inp, + Y=Y, + N=self.n, + K=self.k, + PADDED_N=self.padded_n, + GemmOut=gemm_output_buffer, + aliases={alias: Y.get_name() for alias in Y_aliases}, + beta=self.beta, + alpha=self.alpha, + num_threads=self.num_threads, + micro_gemm=micro_gemm, + is_dynamic_M=self.is_dynamic_M, + template=self, + kernel=kernel, + export_declaration=get_export_declaration(), + epilogue_nodes=epilogues, + reindexers=reindexers, + Y_2d=Y_2d, + use_local_acc=use_local_acc, + maybe_k_slicing=self.maybe_k_slicing(), + x_scale=x_scale, + x_zp=x_zp, + w_scale=w_scale, + w_zp=w_zp, + acc_buf_dtype=torch.int32 if int8_gemm else torch.float, + DTYPE_TO_CPP=DTYPE_TO_CPP, + L1_cache_size=L1_cache_size, + L2_cache_size=L2_cache_size, + config=config, + fake_buffers=fake_buffers, + is_woq_int4=self.is_woq_int4(), + q_group_size=q_group_size_node, + qscale_and_zeros=qscale_and_zeros, + cpu_count=os.cpu_count(), + ) + return options + + def is_int8_woq_gemm_small_m_dim( + self, + X: ir.ReinterpretView, + W: ir.ReinterpretView, + N, + K, + micro_gemm, + ): + """Use SMALL_M_GEMM_TEMPLATE""" + return ( + isinstance(micro_gemm, CppMicroGemmFP32Vec) + and is_int8_woq_gemm_small_m_dim_corner_case( + micro_gemm, X.get_size()[0], N, K + ) + and X.get_dtype() is torch.bfloat16 + and W.get_dtype() is torch.int8 + ) + + def get_kernel_prefix_name(self) -> str: + return f"gemm_m{self.m}n{self.n}k{self.k}" + + def render( # type: ignore[override, return] + self, + kernel: CppTemplateKernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + flag_template_buffer_has_other_users: bool | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + **kwargs, + ) -> str: + options = self.get_options( + kernel=kernel, + template_buffer_node=template_buffer_node, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_nodes, + ) + self.render_options = options + + with contextlib.ExitStack() as stack: + for buf in options["fake_buffers"]: + stack.enter_context( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf)) + ) + if not options["is_dynamic_M"] and self.is_int8_woq_gemm_small_m_dim( + options["X"], + options["W"], + options["N"], + options["K"], + options["micro_gemm"], + ): + template_str = SMALL_M_GEMM_TEMPLATE + else: + template_str = GEMM_TEMPLATE + return self._template_from_string(template_str).render(**options) + + def codegen_blocks( + self, + num_threads, + N, + K, + micro_gemm, + is_dynamic_M, + kernel, + GemmOut, + config, + L1_cache_size, + L2_cache_size, + X, + W, + ): + options = dict( + num_threads=num_threads, + N=N, + K=K, + micro_gemm=micro_gemm, + is_dynamic_M=is_dynamic_M, + kernel=kernel, + GemmOut=GemmOut, + config=config, + L1_cache_size=L1_cache_size, + L2_cache_size=L2_cache_size, + template=self, + X=X, + W=W, + is_woq_int4=self.is_woq_int4(), + ) + template_str = GEMM_TEMPLATE_INIT_BLOCKING_BASIC_BLOCK + if not ( + not is_dynamic_M + and self.is_int8_woq_gemm_small_m_dim(X, W, N, K, micro_gemm) + ): + template_str += GEMM_TEMPLATE_INIT_BLOCKING_EXTENDED + return self._template_from_string(template_str).render(options) + + def codegen_microkernel_def(self): + return self._template_from_string(GEMM_TEMPLATE_MICROKERNEL_DEF).render( + self.render_options + ) + + def codegen_gemm_stub_def(self): + microkernel = self.codegen_microkernel_def() + return microkernel + self._template_from_string(GEMM_TEMPLATE_STUB_DEF).render( + self.render_options + ) + + def codegen_multi_threads_params(self): + return self._template_from_string(GEMM_TEMPLATE_MULTI_THREADS_PARAMS).render() + + def codegen_single_thread_params(self, is_dynamic_M): + options = dict( + is_dynamic_M=is_dynamic_M, + ) + return self._template_from_string(GEMM_TEMPLATE_SINGLE_THREAD_PARAMS).render( + options + ) + + def codegen_m_loop_params(self): + return self._template_from_string(GEMM_TEMPLATE_M_LOOP_PARAMS).render() + + def codegen_n_loop_params(self): + return self._template_from_string(GEMM_TEMPLATE_N_LOOP_PARAMS).render() + + @classmethod + def is_woq_int4(cls): + return False + + @classmethod + def q_group_size(cls): + return None + + +class CppWoqInt4GemmTemplateMeta(type): + def __getitem__(cls, q_group_size): + class CppWoqInt4GemmTemplateInstance(CppGemmTemplate): + def __init__( + self, + *args, + **kwargs, + ) -> None: + super().__init__( + *args, + **kwargs, + ) + + @classmethod + def is_woq_int4(cls): + return True + + @classmethod + def q_group_size(cls): + return q_group_size + + @staticmethod + def check_if_block_weight(W, micro_gemm): + # For WOQ INT4, weight is already packed + # However, for AMX microkernel, we want to change the blocking of weight + from .cpp_micro_gemm import CppMicroGemmWoQInt4Amx + + return isinstance(micro_gemm, CppMicroGemmWoQInt4Amx) + + @classmethod + def block_weight(cls, W, new_size, padding): + # This method is called only if AMX microkernels are used. + # In this case, we unpack and repack weight so that block_n=32 + # the format of packed weight is described here: + # https://github.com/pytorch/pytorch/blob/32eee8ed225d9f10fbbcb38c24b8b44c24c0c97c/aten/src/ATen/native/cpu/int4mm_kernel.cpp#L583 + if isinstance(W, ir.IRNode): + # in this case, we do nothing + ir.ExternKernel.require_contiguous(W) + blocked_w = W + else: + # in this case, we unpack and repack weight + if not isinstance(W, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(W)}") + if W.dim() != 2: + raise AssertionError(f"expected 2D weight, got {W.dim()}D") + N = W.size(0) + K = W.size(-1) * 2 + G = cls.q_group_size() + # x and qscales_and_zeros are in bfloat16 instead of float to use the optimized kernel + # so that the unpacking process is faster + x = torch.eye(K).bfloat16() + # Here we use scale=1 and qzero=8 because we want to unpack weight + # without dequantizing it. The qzero here is 8 instead of 0 because + # int4 values are converted to [-7, 8] in the _weight_int4pack_mm_for_cpu kernel: + # https://github.com/pytorch/pytorch/blob/32eee8ed225d9f10fbbcb38c24b8b44c24c0c97c/aten/src/ATen/native/cpu/int4mm_kernel.cpp#L95 + qscales_and_zeros = ( + torch.tensor([1.0, 8.0]) + .bfloat16() + .expand(K // G, N, 2) + .contiguous() + ) + # shape: [K, N] + unpacked_w = torch.ops.aten._weight_int4pack_mm_for_cpu( + x, + W, + G, + qscales_and_zeros, + ).to(torch.uint8) + block_n = 32 + # shape: [N // block_n, K, block_n] + w_blocked = ( + unpacked_w.view(K, N // block_n, block_n) + .permute(1, 0, 2) + .contiguous() + ) + # pack 2 int4 -> 1 int8 + # block_n: [a0, a1, ..., a15, b0, b1, ..., b15] + # -> [(a0 & 0xf) | (b0 << 4), (a1 & 0xf) | (b1 << 4), ...] + # shape: [N // block_n, K, 2, block_n // 2] + w_blocked = w_blocked.view(N // block_n, K, 2, block_n // 2) + # shape: [N // block_n, K, block_n // 2] + w_blocked_packed = (w_blocked[:, :, 0, :] & 0xF) | ( + w_blocked[:, :, 1, :] << 4 + ) + # shape: [N, K // 2] + blocked_w = w_blocked_packed.view(N, K // 2) + + return blocked_w + + return CppWoqInt4GemmTemplateInstance + + +class CppWoqInt4GemmTemplate(metaclass=CppWoqInt4GemmTemplateMeta): + pass diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_grouped_gemm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_grouped_gemm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..5ce9381fa2df71cfe5e2e165acc7790403aae7ce --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_grouped_gemm_template.py @@ -0,0 +1,554 @@ +import contextlib +import logging +import os +from collections.abc import Callable +from typing import Any, cast, TypeVar +from unittest.mock import patch + +import torch +import torch.utils +from torch.utils._ordered_set import OrderedSet + +from ..._dynamo.utils import counters +from .. import config, ir +from ..kernel.mm_common import mm_args +from ..select_algorithm import ChoiceCaller, DataProcessorTemplateWrapper +from ..utils import parallel_num_threads +from ..virtualized import V +from .cpp import get_export_declaration +from .cpp_gemm_template import ( + CppGemmTemplate, + expand_bias, + gen_2d_view_of_epilogue_buf, + prune_tensors, + transpose_w, +) +from .cpp_micro_gemm import CppMicroGemmAMX, create_micro_gemm +from .cpp_template_kernel import CppTemplateKernel +from .cpp_utils import ( + create_epilogue_with_attr, + GemmBlocking, + get_gemm_template_output_and_compute_dtype, +) + + +log = logging.getLogger(__name__) + +GEMM_TEMPLATE = r""" +{{template.header().getvalue()}} +{{micro_gemm.codegen_define(kernel)}} + +extern "C" {{export_declaration}} +{{kernel.def_kernel(inputs=kernel_args, outputs=Y_list, aliases=aliases)}} +{ + {{kernel.maybe_codegen_profile(template.get_kernel_prefix_name())}} + {{ template.codegen_blocks( + num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOuts[0], config, L1_cache_size, L2_cache_size, X_list[0], W_list[0] + ) }} +{%- if num_threads > 1 %} + {%- set use_dynamic_threads = ((config.cpp.threads < 1) and (num_threads == cpu_count)) or config.cpp.dynamic_threads %} + {%- if use_dynamic_threads %} + #pragma omp parallel + {%- else %} + #pragma omp parallel num_threads({{num_threads}}) + {%- endif %} + { + {{ micro_gemm.codegen_init(kernel) }} + #pragma omp for schedule(static, 1) + for (int64_t tid = 0; tid < {{num_threads}}; tid++) { + {{ template.codegen_multi_threads_params()|indent(12, false) }} +{%- else %} + { + {{ template.codegen_single_thread_params(is_dynamic_M)|indent(8, false) }} + {{ micro_gemm.codegen_init(kernel) }} +{%- endif %} +{%- set acc_buf_name_list=[] %} +{%- set acc_buf_name_prefix = "local_acc_buf_" %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set acc_buf_name = acc_buf_name_prefix + gemm_idx|string %} + {{ kernel.define_buffer(acc_buf_name, ["Mc_blocks*Mr", "Nc_blocks*Nr"], acc_buf_dtype) }} + {%- set acc_buf_name_list=acc_buf_name_list.append(acc_buf_name) %} +{%- endfor %} + for (int64_t mc_block_id = 0; mc_block_id < num_Mc_blocks_per_thread; mc_block_id++) { + {{ template.codegen_m_loop_params()|indent(12, false) }} + for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) { + {{ template.codegen_n_loop_params()|indent(16, false) }} +{%- set acc_list=[] %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set acc_list = acc_list.append( kernel.local_buffers[acc_buf_name_list[gemm_idx]] ) %} + {{ kernel.reinit_buffer_if_null(acc_buf_name_list[gemm_idx]) }} +{%- endfor %} + for (int64_t kc = k_block_start; kc < k_block_end; kc += Kc_blocks) { + int64_t k_start = kc * Kr; + int64_t k_end = std::min(std::min(kc + Kc_blocks, k_block_end) * Kr, K); +{%- set tile_X_list=[] %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set tile_X_list = tile_X_list.append( kernel.slice_nd(X_list[gemm_idx], [("m_start", "m_end"), ("k_start", "k_end")]) ) %} +{%- endfor %} + for (int64_t nci = nc; nci < nc_block_end; nci++) { +{%- set tile_W_3d_list=[] %} +{%- set tile_W_list=[] %} +{%- set acc_slice_list=[] %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set acc_slice_list = acc_slice_list.append( + kernel.slice_nd(acc_list[gemm_idx], [("0", "m_end - m_start"), ("(nci - nc)*Nr", "(nci - nc + 1)*Nr")]) + ) %} + {%- set tile_W_3d_list = tile_W_3d_list.append( + kernel.slice_nd(W_list[gemm_idx], [("nci", "nci + 1"), ("k_start", "k_end"), ()]) + ) %} +{%- endfor %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set tile_W_list = tile_W_list.append( + kernel.view(tile_W_3d_list[gemm_idx], ["k_end - k_start", micro_gemm.register_blocking.block_n]) + ) %} +{%- endfor %} + if (kc == k_block_start) { + {%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {{ micro_gemm.codegen_call( + kernel, tile_X_list[gemm_idx], tile_W_list[gemm_idx], acc_slice_list[gemm_idx], accum=False + )|indent(28, false) }} + {%- endfor %} + } else { + {%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {{ micro_gemm.codegen_call( + kernel, tile_X_list[gemm_idx], tile_W_list[gemm_idx], acc_slice_list[gemm_idx], accum=True + )|indent(28, false) }} + {%- endfor %} + } + } + } + { +{%- set tile_acc_list = [] %} +{%- set tile_Y_list = [] %} +{%- for gemm_idx in range(0, gemm_grouped_num, 1) %} + {%- set tile_acc_list = tile_acc_list.append( + kernel.slice_nd(acc_list[gemm_idx], [("0", "m_end - m_start"), ("0", "n_end - n_start")]) + ) %} + {%- set tile_Y_list = tile_Y_list.append( + kernel.slice_nd(Y_2d_list[gemm_idx], [("m_start", "m_end"), ("n_start", "n_end")]) + ) %} +{%- endfor %} + {{ kernel.store_outputs( + tile_Y_list, + tile_acc_list, + GemmOuts, + epilogue_nodes, + offsets=("m_start", "n_start"), + reindexers=reindexers, + multi_output_buffers=multi_output_buffers + )|indent(20, false) + }} + } + } + } +{%- if num_threads > 1 %} + } + {{ micro_gemm.codegen_finalize(kernel) }} + } +{%- else %} + {{ micro_gemm.codegen_finalize(kernel) }} + } +{%- endif %} +} +""" + + +def get_deduplicated_act(act_mapping: dict[int, ir.IRNode]) -> list[ir.IRNode]: + act_deduplicated = [] + act_deduplicated_name: OrderedSet[str] = OrderedSet() + for act_idx in range(len(act_mapping.values())): + act = act_mapping[act_idx] + if act.get_name() not in act_deduplicated_name: + act_deduplicated.append(act) + act_deduplicated_name.add(act.get_name()) + return act_deduplicated + + +class CppGroupedGemmTemplate(CppGemmTemplate): + def __init__( + self, + input_nodes: list[ir.IRNode], + layout: ir.Layout, + num_threads: int, + register_blocking: GemmBlocking, + beta: int = 1, + alpha: int = 1, + has_bias: bool = False, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + act_mapping: dict[int, ir.IRNode] | None = None, + gemm_grouped_num: int = 1, + ) -> None: + """ + Template for Group of GEMMs: + * Each GEMM has the same dimensions (m, n, k) and the same leading dimensions (lda, ldb, ldc) + for their A, B, and C matrices. + * Each GEMM has distinct or shared activations, has distinct weight, has unique bias or no bias, has distinct epilogues. + * In the current implementation, the outputs of all GEMMs are accumulated using pointwise epilogues. + This behavior can be extended in the future if needed. + """ + super().__init__( + input_nodes, + layout, + num_threads, + register_blocking, + beta, + alpha, + has_bias, + epilogue_creator, + ) + self.act_mapping = act_mapping + self.gemm_grouped_num = gemm_grouped_num + # pyrefly: ignore [bad-override] + self.output_node: list[ir.Buffer] = [ + ir.Buffer(name="buf_out" + str(idx), layout=layout) + for idx in range(gemm_grouped_num) + ] + + @classmethod + # pyrefly: ignore [bad-override] + def add_choices( + cls, + choices: list[ChoiceCaller], + layout: ir.Layout, + input_nodes: list[ir.IRNode], + beta: int = 1, + alpha: int = 1, + has_bias: tuple[bool, ...] = (False, False), + trans_w: bool = False, + input_indices: list[int] | None = None, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + act_mapping: dict[int, ir.IRNode] | None = None, # gemm idx to its act buf + ) -> DataProcessorTemplateWrapper: + # Input nodes order: x, optional[x1], ... w0, w1, ... optional[b0], optional[b1], ... + gemm_grouped_num = len(has_bias) + if not act_mapping: + raise AssertionError("expected non-empty act_mapping") + act_deduplicated = get_deduplicated_act(act_mapping) + wgt_start_idx = len(act_deduplicated) + bias_start_idx = wgt_start_idx + gemm_grouped_num + input_indices = list(range(len(input_nodes))) + + _T = TypeVar("_T", ir.IRNode, torch.Tensor) + _U = TypeVar("_U", ir.Layout, torch.Tensor) + + def reorder_and_filter( + inputs: list[_T], + layout_or_out: _U, + ) -> tuple[list[_T], _U]: + if input_indices is None: + raise AssertionError("input_indices must be set") + return [inputs[idx] for idx in input_indices], layout_or_out + + new_inputs, new_layout = reorder_and_filter(input_nodes, layout) + + def maybe_to_dense( + inputs: list[_T], + layout_or_out: _U, + ) -> tuple[list[_T], _U]: + new_inputs = list(inputs) + for idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num): + if isinstance(inputs[idx], torch.Tensor): + W = inputs[idx] + if not isinstance(W, torch.Tensor): + raise AssertionError("W must be a torch.Tensor") + # pyrefly: ignore [unsupported-operation] + new_inputs[idx] = W.to_dense() if W.is_mkldnn else W + return new_inputs, layout_or_out + + def normalize_shapes( + inputs: list[_T], + layout_or_out: _U, + ) -> tuple[list[_T], _U]: + new_inputs: list[_T] = list(inputs) + if not trans_w: + return new_inputs, layout_or_out + X = new_inputs[0] + for wgt_idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num): + new_input = new_inputs[wgt_idx] + new_inputs[wgt_idx] = transpose_w(new_input, trans_w) + for bias_idx in range(bias_start_idx, len(new_inputs)): + # pyrefly: ignore [bad-argument-type] + new_bias = expand_bias(new_inputs[bias_idx], X) + if new_bias is None: + raise AssertionError("expected new_bias to be not None") + # pyrefly: ignore [unsupported-operation] + new_inputs[bias_idx] = new_bias + return new_inputs, layout_or_out + + num_threads = parallel_num_threads() + new_inputs, _ = normalize_shapes(*maybe_to_dense(new_inputs, new_layout)) + m, n, k, *_ = mm_args(new_inputs[0], new_inputs[wgt_start_idx]) + output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype( + new_inputs[0].get_dtype() + ) + micro_gemm = create_micro_gemm( + "micro_gemm", + m, + n, + k, + input_dtype=new_inputs[0].get_dtype(), + input2_dtype=new_inputs[wgt_start_idx].get_dtype(), + output_dtype=output_dtype, + compute_dtype=compute_dtype, + alpha=alpha, + num_threads=num_threads, + ) + if micro_gemm is None: + raise AssertionError("expected micro_gemm to be not None") + _, block_n, _ = micro_gemm.register_blocking + new_size, padded_n = cls.get_padded_size( + n, block_n, k, should_block_weight=True + ) + padding = padded_n - n + + def pack_weight( + inputs: list[_T], + layout_or_out: _U, + ) -> tuple[list[_T], _U]: + new_W_list = [] + new_inputs = list(inputs) + W_list = new_inputs[wgt_start_idx : wgt_start_idx + gemm_grouped_num] + for W in W_list: + blocked_w = cls.block_weight(W, new_size, padding) + new_W_list.append(cls.pack_vnni_weight(blocked_w, micro_gemm, new_size)) + new_inputs[wgt_start_idx : wgt_start_idx + gemm_grouped_num] = new_W_list + return new_inputs, layout_or_out + + def preprocessor( + inputs: list[_T], + layout: _U, + ) -> tuple[list[_T], _U]: + return pack_weight( + *normalize_shapes(*maybe_to_dense(*reorder_and_filter(inputs, layout))) + ) + + def postprocessor(output: _T) -> _T: + if isinstance(output, ir.TensorBox): + template_buffer = ir.InputsKernel.unwrap_storage_for_input(output) + if not isinstance(template_buffer, ir.CppTemplateBuffer): + raise AssertionError( + "expected template_buffer to be ir.CppTemplateBuffer" + ) + new_input_nodes, _ = reorder_and_filter(input_nodes, layout) + W_nodes = new_input_nodes[ + wgt_start_idx : wgt_start_idx + gemm_grouped_num + ] + W_tensor = [] + for W_node in W_nodes: + if W_node.get_name() not in V.graph.constants: + raise AssertionError( + f"expected {W_node.get_name()} in V.graph.constants" + ) + # pyrefly: ignore [bad-argument-type] + W_tensor.append(V.graph.constants[W_node.get_name()]) + # pyrefly: ignore [unsupported-operation] + new_input_nodes[wgt_start_idx : wgt_start_idx + gemm_grouped_num] = ( + W_tensor # type: ignore[assignment] + ) + new_input_nodes, _ = pack_weight( + *normalize_shapes(*maybe_to_dense(new_input_nodes, layout)) + ) + # Prune unused tensors + prune_tensors(input_nodes, new_input_nodes) + for idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num): + W_packed = new_input_nodes[idx] + if not isinstance(W_packed, torch.Tensor): + raise AssertionError("expected W_packed to be a torch.Tensor") + W_packed_constant = V.graph.add_tensor_constant(W_packed) + template_buffer.inputs[idx] = ( + ir.InputsKernel.unwrap_storage_for_input(W_packed_constant) + ) + + return output + + template = DataProcessorTemplateWrapper( + CppGroupedGemmTemplate, + preprocessor, + postprocessor, + input_nodes=input_nodes, + layout=layout, + num_threads=num_threads, + register_blocking=micro_gemm.register_blocking, + beta=beta, + alpha=alpha, + has_bias=has_bias, + epilogue_creator=epilogue_creator, + act_mapping=act_mapping, + gemm_grouped_num=gemm_grouped_num, + ) + template.maybe_append_choice(choices) + return template + + def get_kernel_prefix_name(self) -> str: + return f"grouped_gemm_g{self.gemm_grouped_num}m{self.m}n{self.n}k{self.k}" + + def render( # type: ignore[override,return,no-untyped-def] + self, + kernel: CppTemplateKernel, + template_buffer_node: ir.CppTemplateBuffer | None = None, + flag_template_buffer_has_other_users: bool | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + **kwargs, + ) -> str: + if not self.act_mapping: + raise AssertionError("expected non-empty self.act_mapping") + act_deduplicated = get_deduplicated_act(self.act_mapping) + wgt_start_idx = len(act_deduplicated) + bias_start_idx = wgt_start_idx + self.gemm_grouped_num + X_list = list(self.act_mapping.values()) + W_list = self.input_nodes[wgt_start_idx : wgt_start_idx + self.gemm_grouped_num] + inp_list = [] + cur_idx = bias_start_idx + for inp_idx in range(self.gemm_grouped_num): + inp = None + # pyrefly: ignore [bad-index, index-error] + if self.has_bias[inp_idx]: + inp = self.input_nodes[cur_idx] + cur_idx += 1 + inp_list.append(inp) + + Y_list = self.output_node + multi_output_buffers = None + if template_buffer_node is not None: + W_list = template_buffer_node.inputs[ + wgt_start_idx : wgt_start_idx + self.gemm_grouped_num + ] + if not isinstance(template_buffer_node.outputs, list): + raise AssertionError( + "expected template_buffer_node.outputs to be a list" + ) + Y_list = template_buffer_node.outputs + counters["inductor"]["cpp_grouped_gemm_template"] += 1 + multi_output_buffers = template_buffer_node.outputs + + template_buffer = Y_list[0] + fake_buffers: list[ir.Buffer] = [] + Y_2d_list = Y_list + output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype( + X_list[0].get_dtype() + ) + micro_gemm = create_micro_gemm( + f"{kernel.kernel_name}_micro_gemm", + self.m, + self.n, + self.k, + input_dtype=X_list[0].get_dtype(), + input2_dtype=W_list[0].get_dtype(), + output_dtype=output_dtype, + compute_dtype=compute_dtype, + alpha=self.alpha, + num_threads=self.num_threads, + ) + if micro_gemm is None: + raise AssertionError("expected micro_gemm to be not None") + if self.register_blocking != micro_gemm.register_blocking: + raise AssertionError( + "expected self.register_blocking == micro_gemm.register_blocking" + ) + self.log_blockings() + if isinstance(micro_gemm, CppMicroGemmAMX): + counters["inductor"]["cpp_micro_gemm_amx_counter"] += 1 + + L1_cache_size = torch.cpu.get_capabilities().get( + "l1d_cache_size", 0 + ) # per core cache size in Bytes + if L1_cache_size <= 0: + raise AssertionError(f"Expect L1_cache_size > 0 but got {L1_cache_size}") + + L2_cache_size = torch.cpu.get_capabilities().get( + "l2_cache_size", 0 + ) # per core cache size in Bytes + if L2_cache_size <= 0: + raise AssertionError(f"Expect L2_cache_size > 0 but got {L2_cache_size}") + + epilogues: list[ir.IRNode] = [] + reindexers: list[Callable[[list[Any]], list[Any]] | None] = [] + gemm_output_buffers: list[ir.Buffer] = [] + for out_buf_idx in range(self.gemm_grouped_num): + gemm_output_name = f"{template_buffer.get_name()}_GemmOut" + str( + out_buf_idx + ) + gemm_output_buffers.append( + ir.Buffer(name=gemm_output_name, layout=template_buffer.layout) + ) + + if self.epilogue_creator: + raise AssertionError( + "epilogue_creator is not supported yet in Grouped GEMM Template" + ) + + kernel_args: dict[str, ir.IRNode | None] = {} + for x_idx in range(wgt_start_idx): + kernel_args["X" + str(x_idx)] = act_deduplicated[x_idx] + for w_idx in range(self.gemm_grouped_num): + kernel_args["W" + str(w_idx)] = W_list[w_idx] + for inp_idx in range(self.gemm_grouped_num): + kernel_args["inp" + str(inp_idx)] = inp_list[inp_idx] + + def _bias_add_epilogue(buf: ir.IRNode, inp: ir.IRNode) -> ir.Pointwise: + return create_epilogue_with_attr( + buf, "bias_add", other=inp, beta=self.beta, dtype=self.layout.dtype + ) + + for gemm_idx, inp in enumerate(inp_list): + if inp: + buffer_name = Y_list[gemm_idx].get_name() + epilogues.append( + ir.ComputedBuffer( + name=buffer_name, + layout=template_buffer.layout, + data=_bias_add_epilogue(gemm_output_buffers[gemm_idx], inp), + ) + ) + reindexers.append(None) + + if epilogue_nodes: + epilogues.extend(epilogue_nodes) + for epilogue_node in epilogue_nodes: + Y = cast(ir.Buffer, epilogue_node) + _, reindexers = gen_2d_view_of_epilogue_buf( + Y, + template_buffer, + [ + epilogue_node, + ], + reindexers, + default_reindexers=[ + None, + ], + ) + + options = dict( + N=self.n, + K=self.k, + PADDED_N=self.padded_n, + aliases={}, + beta=self.beta, + alpha=self.alpha, + num_threads=self.num_threads, + micro_gemm=micro_gemm, + is_dynamic_M=self.is_dynamic_M, + template=self, + kernel=kernel, + export_declaration=get_export_declaration(), + acc_buf_dtype=torch.float, + L1_cache_size=L1_cache_size, + L2_cache_size=L2_cache_size, + config=config, + epilogue_nodes=epilogues, + GemmOuts=gemm_output_buffers, + reindexers=reindexers, + kernel_args=kernel_args, + X_list=X_list, + W_list=W_list, + gemm_grouped_num=self.gemm_grouped_num, + Y_list={"Y" + str(idx): Y for idx, Y in enumerate(Y_list)}, + Y_2d_list=Y_2d_list, + multi_output_buffers=multi_output_buffers, + cpu_count=os.cpu_count(), + ) + with contextlib.ExitStack() as stack: + stack.enter_context( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(fake_buffers)) + ) + return self._template_from_string(GEMM_TEMPLATE).render(**options) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_micro_gemm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_micro_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..979230917aba5ea1f9e8a6dd8590ace58a3d7f05 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_micro_gemm.py @@ -0,0 +1,2278 @@ +# mypy: allow-untyped-defs +import dataclasses +import operator +import sys +from collections.abc import Callable +from enum import Enum + +import torch + +from .. import cpp_builder, ir +from ..cpu_vec_isa import ( + pick_vec_isa, + VecAMX, + VecAVX2, + VecAVX512, + VecAVX512VNNI, + VecISA, + VecNEON, + VecSVE, +) +from ..utils import IndentedBuffer, parallel_num_threads +from ..virtualized import V +from .common import KernelTemplate +from .cpp_template_kernel import CppTemplateKernel +from .cpp_utils import DTYPE_TO_CPP, GemmBlocking, value_to_cpp + + +class LayoutType(Enum): + NORMAL = 0 + VNNI2 = 1 + VNNI4 = 2 + + +_IS_WINDOWS = sys.platform == "win32" + + +def get_restrict_keyword() -> str: + if _IS_WINDOWS: + # https://learn.microsoft.com/en-us/cpp/cpp/extension-restrict?view=msvc-170 + return "__restrict" + else: + return "__restrict__" + + +class CppMicroGemm: + """ + A class that codegens a kernel that computes small-sized matrix multiplication. + + A micro GEMM kernel is responsible for register blocking, instruction selection, + and other CPU architecture-specific optimizations. + + The subclasses need to override `codegen_define` to define the kernel function + that is called by the code generated by `codegen_call`. + """ + + # TODO(jgong5): support constant shapes and lds as template args. + DECLARE_KERNEL = r""" +template +inline void {{kernel_name}}( +{%- if kernel_extra_args_declare %} + {{kernel_extra_args_declare}} +{%- endif %} + const {{input_t}}* {{restrict_keyword}} A, + const {{input2_t}}* {{restrict_keyword}} B, + {{output_t}}* {{restrict_keyword}} C, + int64_t M, + int64_t N, + int64_t K, + int64_t lda, + int64_t ldb, + int64_t ldc +) +""" + + def __init__( + self, + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + register_blocking, + alpha=1, + ) -> None: + self.name = name + self.input_dtype = input_dtype + if input2_dtype is None: + raise AssertionError("expected input2_dtype to be set, got None") + self.input2_dtype = input2_dtype + self.output_dtype = output_dtype + self.compute_dtype = compute_dtype + self.register_blocking = register_blocking + self.alpha = alpha + self.pack_vnni_B_locally = False + + def get_common_options(self): + if self.input_dtype in [torch.uint8, torch.int8]: + if self.compute_dtype != torch.int32: + raise AssertionError( + f"expected compute_dtype == torch.int32, got {self.compute_dtype}" + ) + if self.output_dtype != torch.int32: + raise AssertionError( + f"expected output_dtype == torch.int32, got {self.output_dtype}" + ) + if self.input2_dtype != torch.int8: + raise AssertionError( + f"expected input2_dtype == torch.int8, got {self.input2_dtype}" + ) + return { + "torch": torch, + "kernel_name": self.name, + "input_dtype": self.input_dtype, + "input2_dtype": self.input2_dtype, + "output_dtype": self.output_dtype, + "compute_dtype": self.compute_dtype, + "input_t": DTYPE_TO_CPP[self.input_dtype], + "input2_t": DTYPE_TO_CPP[self.input2_dtype], + "output_t": DTYPE_TO_CPP[self.output_dtype], + "compute_t": DTYPE_TO_CPP[self.compute_dtype], + "alpha": self.alpha, + "kernel_extra_args_declare": self.get_kernel_extra_args_declare(), + "int8_gemm": self.input_dtype in [torch.uint8, torch.int8], + "vnni_size": 4 if self.input_dtype in [torch.uint8, torch.int8] else 2, + "restrict_keyword": get_restrict_keyword(), + "pack_vnni_B_locally": self.pack_vnni_B_locally, + "template": self, + "is_woq_int4": self.is_woq_int4(), + } + + def get_kernel_declaration(self): + options = self.get_common_options() + return KernelTemplate._template_from_string(self.DECLARE_KERNEL).render(options) + + def get_kernel_extra_args_declare(self) -> str: + return "" + + def get_kernel_extra_args(self, **kwargs) -> list[str]: + return [] + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + raise NotImplementedError + + def codegen_call( + self, + kernel: CppTemplateKernel, + A: ir.Buffer, + B: ir.Buffer, + C: ir.Buffer, + accum: bool, + prefetch: bool = False, + **kwargs_for_extra_args, + ) -> str: + """ + Generate the code for calling the templated kernel that computes + `C += alpha * A @ B` if `accum` is True, or `C = alpha * A @ B` otherwise. + """ + A_ptr = f"&({kernel.index(A, [0, 0])})" + B_ptr = f"&({kernel.index(B, [0, 0])})" + C_ptr = f"&({kernel.index(C, [0, 0])})" + M = kernel.size(C, 0) + N = kernel.size(C, 1) + K = kernel.size(A, 1) + lda = kernel.stride(A, 0) + ldb = kernel.stride(B, 0) + ldc = kernel.stride(C, 0) + res = IndentedBuffer() + res.writeline( + f"{self.name}<{value_to_cpp(accum, 'bool')}, {value_to_cpp(prefetch, 'bool')}>(" + ) + with res.indent(): + kwargs_for_extra_args.update({"kernel": kernel}) + extra_args = self.get_kernel_extra_args(**kwargs_for_extra_args) + for arg in extra_args: + res.writeline(arg) + res.writeline(f"{A_ptr},") + res.writeline(f"{B_ptr},") + res.writeline(f"{C_ptr},") + res.writeline(f"{M},") + res.writeline(f"{N},") + res.writeline(f"{K},") + res.writeline(f"{lda},") + res.writeline(f"{ldb},") + res.writeline(f"{ldc}") + res.writeline(");") + return res.getvalue() + + def use_local_vnni_blocking(self, should_block_weight: bool): + self.pack_vnni_B_locally = should_block_weight + + def codegen_init( + self, + kernel: CppTemplateKernel, + ) -> str: + return "" + + def codegen_finalize( + self, + kernel: CppTemplateKernel, + ) -> str: + return "" + + def get_b_layout(self) -> LayoutType: + return LayoutType.NORMAL + + ALLOCATE_WEIGHT_BUFFER = r""" + {%- if is_msvc_compiler %} + // MSVC doesn't support stack-allocated dynamic-sized arrays, so using heap memory here. + auto heap_deq_b_buf_ptr = std::make_unique<{{buffer_dtype}}[]>({{buffer_size}}); + {{buffer_dtype}}* {{buffer_name}} = heap_deq_b_buf_ptr.get(); + {%- else %} + // It's safe to use a stack-allocated array since the blocking strategy would + // require us to allocate an array that's smaller than the size of L1D cache, + // and the default per thread max stack size on Linux is quite higher, + // so we need not worry about stack overflow. + alignas(4096) {{buffer_dtype}} {{buffer_name}}[{{buffer_size}}]; + {%- endif %} +""" + + def codegen_allocate_weight_buffer( + self, buffer_name: str, buffer_dtype: str, *size_args + ) -> str: + buffer_size = " * ".join(map(str, size_args)) + return KernelTemplate._template_from_string(self.ALLOCATE_WEIGHT_BUFFER).render( + { + "buffer_name": buffer_name, + "buffer_dtype": buffer_dtype, + "buffer_size": buffer_size, + "is_msvc_compiler": cpp_builder.is_msvc_cl(), + } + ) + + def is_woq_int4(self): + return False + + +@dataclasses.dataclass +class CppMicroGemmConfig: + input_dtype: torch.dtype + input2_dtype: torch.dtype + output_dtype: torch.dtype + compute_dtype: torch.dtype + vec_isa_cls: type[VecISA] + register_blocking: GemmBlocking + extra_check: Callable[..., bool] | None = None + + +micro_gemm_configs: dict[type[CppMicroGemm], list[CppMicroGemmConfig]] = {} + + +def register_micro_gemm(*configs): + def inner(cls): + if cls in micro_gemm_configs: + raise AssertionError(f"Duplicate micro_gemm registration for {cls}") + if len(configs) <= 0: + raise AssertionError(f"No micro_gemm configs provided for {cls}") + micro_gemm_configs[cls] = list(configs) + return cls + + return inner + + +def generate_gemm_config( + vec_isa_cls, + register_blockings, + input_dtype=torch.float, + input2_dtype=None, + output_dtype=None, + compute_dtype=None, + extra_check=None, +): + if output_dtype is None: + output_dtype = input_dtype + if compute_dtype is None: + compute_dtype = output_dtype + if input2_dtype is None: + input2_dtype = input_dtype + return [ + CppMicroGemmConfig( + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + vec_isa_cls, + GemmBlocking(*blocking), + extra_check, + ) + for blocking in register_blockings + ] + + +class CppMicroGemmRef(CppMicroGemm): + """ + A reference implementation of the CppMicroGemm class with naive C++ code. + It is used for correctness debugging. + """ + + TEMPLATE_ENTRY = r""" +{{declare_kernel}} { + for (int64_t m = 0; m < M; ++m) { + for (int64_t n = 0; n < N; ++n) { + {{compute_t}} result = accum ? C[m * ldc + n] : 0; + for (int64_t k = 0; k < K; ++k) { + result += ({{compute_t}})A[m * lda + k] * ({{compute_t}})B[k * ldb + n] * {{alpha}}; + } + C[m * ldc + n] = result; + } + } +} +""" + + def __init__( + self, name, input_dtype, input2_dtype, output_dtype, compute_dtype, alpha + ) -> None: + super().__init__( + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + GemmBlocking(1, 1, 1), + alpha, + ) + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + options = { + "declare_kernel": self.get_kernel_declaration(), + **self.get_common_options(), + } + return KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(options) + + +def is_int8_woq_gemm_small_m_dim_corner_case(config, m, n, k): + return ( + k % config.register_blocking.block_k == 0 + and n % config.register_blocking.block_n == 0 + and m < 16 + ) + + +# extra check for small M dimension for int8 WoQ case +def check_int8_woq_small_m_dim(config, m, n, k, alpha, num_threads, **kwargs): + return is_int8_woq_gemm_small_m_dim_corner_case(config, m, n, k) and not kwargs.get( + "dynamic_M", False + ) + + +# For int8 WoQ GEMM with small M, we use different blockings that shouldn't be used otherwise +def do_not_use_with_small_m_for_int8_woq(config, m, n, k, alpha, num_threads, **kwargs): + return not check_int8_woq_small_m_dim(config, m, n, k, alpha, num_threads, **kwargs) + + +@register_micro_gemm( + *generate_gemm_config( + VecAVX512, + [(8, 48, 1), (8, 32, 1), (16, 16, 1)], + input_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX512, + [(8, 48, 1), (8, 32, 1), (16, 16, 1)], + input_dtype=torch.bfloat16, + output_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX512, + [(8, 48, 1), (8, 32, 1), (16, 16, 1)], + input_dtype=torch.half, + output_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX512, + [(8, 48, 1), (8, 32, 1), (16, 16, 1)], + input_dtype=torch.bfloat16, + input2_dtype=torch.int8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=do_not_use_with_small_m_for_int8_woq, + ), + *generate_gemm_config( + VecAVX512, + [ + (4, 32, 64), + (8, 32, 64), + ], + input_dtype=torch.bfloat16, + input2_dtype=torch.int8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=check_int8_woq_small_m_dim, + ), + *generate_gemm_config( + VecAVX2, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX2, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.bfloat16, + output_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX2, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.half, + output_dtype=torch.float, + ), + *generate_gemm_config( + VecAVX2, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.bfloat16, + input2_dtype=torch.int8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=do_not_use_with_small_m_for_int8_woq, + ), + *generate_gemm_config( + VecAVX2, + [ + (2, 16, 64), + (4, 16, 64), + ], + input_dtype=torch.bfloat16, + input2_dtype=torch.int8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=check_int8_woq_small_m_dim, + ), + *generate_gemm_config( + VecNEON, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.float, + input2_dtype=torch.float, + output_dtype=torch.float, + compute_dtype=torch.float, + ), + *generate_gemm_config( + VecSVE, + [(4, 24, 1), (4, 16, 1), (8, 8, 1)], + input_dtype=torch.float, + input2_dtype=torch.float, + output_dtype=torch.float, + compute_dtype=torch.float, + ), +) +class CppMicroGemmFP32Vec(CppMicroGemm): + """ + This class generates the code for micro gemm using fp32 vec instructions for compute. + It supports input types of torch.float, torch.bfloat16, and torch.half with fp32 output. + The output of the microkernel is in FP32, but it would be converted to BF16/FP16 in the template, + if the desired output is BF16/FP16. + """ + + TEMPLATE_ENTRY = r""" +{{declare_kernel}} { + using Vectorized = at::vec::Vectorized<{{compute_t}}>; + constexpr auto VLEN = Vectorized::size(); + {{kernel.assert_function}}({{block_n}} % VLEN == 0, "block_n dimension must be multiple of Vector size"); + {{kernel.assert_function}}(K % {{block_k}} == 0, "K dimension must be multiple of {{block_k}}"); + // TODO(jgong5): loop unroll for M and N + for (int64_t m = 0; m < M; m += {{block_m}}) { + int64_t block_m = std::min(M - m, {{block_m}}); + for (int64_t n = 0; n < N; n += {{block_n}}) { + int64_t block_n = std::min(N - n, {{block_n}}); + if (block_m == {{block_m}} && block_n == {{block_n}}) { +{%- if not trans_b %} + {{kernel_name}}_kernel<{{block_m}}, {{block_n}}, accum, prefetch>( +{%- else %} + {{kernel_name}}_transpose_b_kernel<{{block_m}}, {{block_n}}, accum, prefetch>( +{%- endif %} + A + m * lda, +{%- if not trans_b %} + B + n, +{%- else %} + B + n * ldb, +{%- endif %} + C + m * ldc + n, + K, + lda, + ldb, + ldc + ); +{%- if tail_n %} + } else if (block_n == {{block_n}}){ +{%- else %} + } else { +{%- endif %} + switch (block_m) { +{%- for b in range(block_m - 1, 0, -1) %} + case {{b}}: + {%- if not trans_b %} + {{kernel_name}}_kernel<{{b}}, {{block_n}}, accum, prefetch>( + {%- else %} + {{kernel_name}}_transpose_b_kernel<{{b}}, {{block_n}}, accum, prefetch>( + {%- endif %} + A + m * lda, + {%- if not trans_b %} + B + n, + {%- else %} + B + n * ldb, + {%- endif %} + C + m * ldc + n, + K, + lda, + ldb, + ldc + ); + break; +{%- endfor %} + default: + {{kernel.assert_function}}(false, "Unsupported block_m: {{block_m}}"); + } + +{%- if tail_n %} + } else { + switch (block_m) { + {%- for b in range(block_m, 0, -1) %} + case {{b}}: + {%- if not trans_b %} + {{kernel_name}}_ntail_kernel<{{b}}, {{block_n}}, accum, prefetch>( + {%- else %} + {{kernel_name}}_ntail_transpose_b_kernel<{{b}}, {{block_n}}, accum, prefetch>( + {%- endif %} + A + m * lda, + {%- if not trans_b %} + B + n, + {%- else %} + B + n * ldb, + {%- endif %} + C + m * ldc + n, + block_n, + K, + lda, + ldb, + ldc + ); + break; + {%- endfor %} + default: + {{kernel.assert_function}}(false, "Unsupported block_m: {{block_m}}"); + } + } +{%- else %} + } +{%- endif %} + } + } +} +""" + + TEMPLATE_KERNEL = r""" + +template +{%- if not trans_b %} + {%- if tail_n %} +inline void {{kernel_name}}_ntail_kernel( + {%- else %} +inline void {{kernel_name}}_kernel( + {%- endif %} +{%- else %} + {%- if tail_n %} +inline void {{kernel_name}}_ntail_transpose_b_kernel( + {%- else %} +inline void {{kernel_name}}_transpose_b_kernel( + {%- endif %} +{%- endif %} + const {{input_t}}* {{restrict_keyword}} A, + const {{input2_t}}* {{restrict_keyword}} B, + {{output_t}}* {{restrict_keyword}} C, +{%- if tail_n %} + int64_t N, +{%- endif %} + int64_t K, + int64_t lda, + int64_t ldb, + int64_t ldc +) { + using Vectorized = at::vec::Vectorized<{{compute_t}}>; +{%- if input2_dtype in [torch.bfloat16, torch.float16] %} + using VectorizedIn = at::vec::Vectorized<{{input_t}}>; +{%- endif %} + +{%- if not trans_b %} + constexpr auto VLEN = Vectorized::size(); + constexpr auto ROWS = BLOCK_M; + constexpr auto COLS = BLOCK_N / VLEN; + + Vectorized va; + at::vec::VectorizedN<{{compute_t}}, COLS> vb; + at::vec::VectorizedN<{{compute_t}}, ROWS*COLS> vc; + + {%- if tail_n %} + int64_t rCOLS = (N + VLEN - 1) / VLEN; + int ntail = N % VLEN; + {%- endif %} + auto loadc = [&](auto i) { + if constexpr (accum) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + {%- if tail_n %} + int load_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN; + if (col < rCOLS) { + vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN, load_size); + } + {%- else %} + vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN); + {%- endif %} + } else { + vc[i] = Vectorized(0.0f); + } + }; + c10::ForcedUnroll{}(loadc); + + auto compute = [&, COLS](auto i, int k) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + {%- if tail_n %} + int load_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN; + {%- endif %} + if constexpr (col == 0) { + {%- if alpha != 1 %} + va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + k]) * {{alpha}}); + {%- else %} + va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + k])); + {%- endif %} + } + + if constexpr (row == 0) { + {%- if tail_n %} + if (col < rCOLS) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + auto b = VectorizedIn::loadu(B + k * ldb + col * VLEN, load_size); + vb[col] = at::vec::convert<{{compute_t}}>(b); + {%- elif input2_dtype == torch.int8 %} + // Convert VLEN int8 elements to int32, and then fp32 + auto b32 = at::vec::convert_to_int32(B + k * ldb + col * VLEN, load_size); + vb[col] = at::vec::convert(b32); + {%- else %} + vb[col] = Vectorized::loadu(B + k * ldb + col * VLEN, load_size); + {%- endif %} + } else { + vb[col] = Vectorized(0.0f); + } + + {%- else %} + + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + auto b = VectorizedIn::loadu(B + k * ldb + col * VLEN, VLEN); + vb[col] = at::vec::convert<{{compute_t}}>(b); + {%- elif input2_dtype == torch.int8 %} + // Convert VLEN int8 elements to int32, and then fp32 + auto b32 = at::vec::convert_to_int32(B + k * ldb + col * VLEN); + if constexpr (prefetch) { + _mm_prefetch(B + (k + {{block_k}}) * ldb + col * VLEN, _MM_HINT_T0); + } + vb[col] = at::vec::convert(b32); + {%- else %} + vb[col] = Vectorized::loadu(B + k * ldb + col * VLEN); + {%- endif %} + {%- endif %} + + } + + constexpr int idx = row * COLS + col; + {%- if tail_n %} + if (col < rCOLS) { + vc[idx] = at::vec::fmadd(va, vb[col], vc[idx]); + } + {%- else %} + vc[idx] = at::vec::fmadd(va, vb[col], vc[idx]); + {%- endif %} + }; + + for (int k = 0; k < K; ++k) { + c10::ForcedUnroll{}(compute, k); + } + + // store to C + auto storec = [&](auto i) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + {%- if tail_n %} + int store_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN; + if (col < rCOLS) { + vc[i].store(C + row * ldc + col * VLEN, store_size); + } + {%- else %} + vc[i].store(C + row * ldc + col * VLEN); + {%- endif %} + }; + c10::ForcedUnroll{}(storec); + +{%- else %} + // Use 2 implementations for the transposed B: + // First implementation: + // Transpose first and then perform outer product calculation in sub-blocks, + // which introduces an additional transpose overhead of [K, N] compared to the non-transpose version. + // Second implementation: + // Directly perform inner product calculation in sub-blocks, + // which introduces an additional vector reduction of [M, N] compared to the non-transpose version. + // Therefore, when M * N / (K * N) is large, the first implementation has better performance. + {%- if tail_n %} + if (K % Vectorized::size() == 0 && N % Vectorized::size() == 0 && 24 * BLOCK_M > K) { + {%- else %} + if (K % Vectorized::size() == 0 && 24 * BLOCK_M > K) { + {%- endif %} + // First implementation: + constexpr auto VLEN = Vectorized::size(); + constexpr auto ROWS = BLOCK_M; + constexpr auto COLS = BLOCK_N / VLEN; + int _K = K / VLEN; + Vectorized va; + at::vec::VectorizedN<{{compute_t}}, VLEN> vb; + at::vec::VectorizedN<{{compute_t}}, ROWS*COLS> vc; + auto loadc = [&](auto i) { + if constexpr (accum) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN); + } else { + vc[i] = Vectorized(0.0f); + } + }; + c10::ForcedUnroll{}(loadc); + auto unroll_loadB = [&](auto i, const {{input2_t}}* {{restrict_keyword}} src_ptr) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + auto b = VectorizedIn::loadu(src_ptr + i * ldb, VLEN); + vb[i] = at::vec::convert<{{compute_t}}>(b); + {%- elif input2_dtype == torch.int8 %} + auto b32 = at::vec::convert_to_int32(src_ptr + i * ldb, VLEN); + vb[i] = at::vec::convert(b32); + {%- else %} + vb[i] = Vectorized::loadu(src_ptr + i * ldb, VLEN); + {%- endif %} + }; + auto compute_trans = [&, COLS](auto i, int k) { + constexpr int row = i % ROWS; + constexpr int col = i / ROWS; + constexpr int e_col = col * VLEN; + int idk = k * VLEN; + if constexpr (row == 0) { + c10::ForcedUnroll{}(unroll_loadB, B + e_col * ldb + idk); + at::vec::transpose_block(vb); + } + constexpr int idx = row * COLS + col; + {{kernel.unroll_pragma(16)}} + for (int j = 0; j < VLEN; j++) { + {%- if alpha != 1 %} + va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + idk + j]) * {{alpha}}); + {%- else %} + va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + idk + j])); + {%- endif %} + vc[idx] = at::vec::fmadd(va, vb[j], vc[idx]); + } + }; + for (int k = 0; k < _K; ++k) { + c10::ForcedUnroll{}(compute_trans, k); + } + // store to C + auto storec = [&](auto i) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + vc[i].store(C + row * ldc + col * VLEN); + }; + c10::ForcedUnroll{}(storec); + } else { + // Second implementation + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + constexpr auto VLEN = VectorizedIn::size(); + {%- else %} + constexpr auto VLEN = Vectorized::size(); + {%- endif %} + int _K = (K + VLEN - 1) / VLEN; + // sub-block size of BLOCK_N and BLOCK_M + constexpr int sM = {{sub_block_m}}; + constexpr int sN = {{sub_block_n}}; + {%- if tail_n %} + int bN = (N + sN - 1) / sN; + {%- else %} + constexpr int bN = (BLOCK_N + sN - 1) / sN; + {%- endif %} + constexpr int bM = (BLOCK_M + sM - 1) / sM; + + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + at::vec::VectorizedN<{{compute_t}}, 2> va; + at::vec::VectorizedN<{{compute_t}}, 2 * sN> vb; + {%- else %} + at::vec::Vectorized<{{compute_t}}> va; + at::vec::VectorizedN<{{compute_t}}, sN> vb; + {%- endif %} + at::vec::VectorizedN<{{compute_t}}, sN * sM> vmid; + + {%- if tail_n %} + int ntail = N % sN; + {%- else %} + constexpr int ntail = BLOCK_N % sN; + {%- endif %} + constexpr int mtail = BLOCK_M % sM; + int ktail = K % VLEN; + + auto compute_trans = [&](int m, int n, int k) { + {%- if tail_n %} + int e_n = (n == bN - 1 && ntail != 0) ? (N - n * sN) : sN; + {%- else %} + int e_n = (n == bN - 1 && ntail != 0) ? (BLOCK_N - n * sN) : sN; + {%- endif %} + int e_m = (m == bM - 1 && mtail != 0) ? (BLOCK_M - m * sM) : sM; + int e_k = (k == _K - 1 && ktail != 0) ? (K - k * VLEN) : VLEN; + {{kernel.unroll_pragma(sub_block_n)}} + for (int i = 0; i < e_n; i++) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + auto b = VectorizedIn::loadu(B + (sN * n + i) * ldb + k * VLEN, e_k); + std::tie(vb[2 * i], vb[2 * i + 1]) = at::vec::convert_to_float<{{input_t}}>(b); + {%- elif input2_dtype == torch.int8 %} + auto b32 = at::vec::convert_to_int32(B + (sN * n + i) * ldb + k * VLEN, e_k); + vb[i] = at::vec::convert(b32); + {%- else %} + vb[i] = Vectorized::loadu(B + (sN * n + i) * ldb + k * VLEN, e_k); + {%- endif %} + } + + {{kernel.unroll_pragma(sub_block_m)}} + for (int s = 0; s < e_m; s++) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + auto a = VectorizedIn::loadu(A + (sM * m + s) * lda + k * VLEN, e_k); + std::tie(va[0], va[1]) = at::vec::convert_to_float<{{input_t}}>(a); + {%- elif input2_dtype == torch.int8 %} + auto a32 = at::vec::convert_to_int32(A + (sM * m + s) * lda + k * VLEN, e_k); + va = at::vec::convert(a32); + {%- else %} + va = Vectorized::loadu(A + (sM * m + s) * lda + k * VLEN, e_k); + {%- endif %} + + {%- if alpha != 1 %} + va = va * Vectorized({{alpha}}); + {%- endif %} + if (k == 0) { + {{kernel.unroll_pragma(sub_block_n)}} + for (int i = 0; i < e_n; i++) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + vmid[sN * s + i] = at::vec::fmadd(va[0], vb[2 * i], Vectorized(0.0f)); + vmid[sN * s + i] = at::vec::fmadd(va[1], vb[2 * i + 1], vmid[sN * s + i]); + {%- else %} + vmid[sN * s + i] = at::vec::fmadd(va, vb[i], Vectorized(0.0f)); + {%- endif %} + } + } else { + {{kernel.unroll_pragma(sub_block_n)}} + for (int i = 0; i < e_n; i++) { + {%- if input2_dtype in [torch.bfloat16, torch.float16] %} + vmid[sN * s + i] = at::vec::fmadd(va[0], vb[2 * i], vmid[sN * s + i]); + vmid[sN * s + i] = at::vec::fmadd(va[1], vb[2 * i + 1], vmid[sN * s + i]); + {%- else %} + vmid[sN * s + i] = at::vec::fmadd(va, vb[i], vmid[sN * s + i]); + {%- endif %} + } + } + } + + // store to C + if (k == _K - 1) { + {{kernel.unroll_pragma(sub_block_m)}} + for (int s = 0; s < e_m; s++) { + {{kernel.unroll_pragma(sub_block_n)}} + for (int i = 0; i < e_n; i++) { + auto v = at::vec::vec_reduce_all([](Vectorized& x, Vectorized& y) { return x + y; }, vmid[sN * s + i]); + if constexpr (accum) { + auto c = *(C + (sM * m + s) * ldc + sN * n + i); + *(C + (sM * m + s) * ldc + sN * n + i) = c + v; + } else { + *(C + (sM * m + s) * ldc + sN * n + i) = v; + } + } + } + } + }; + + for (int n = 0; n < bN; ++n) { + for (int m = 0; m < bM; ++m) { + for (int k = 0; k < _K; ++k) { + compute_trans(m, n, k); + } + } + } + } +{%- endif %} +} +""" + + # set trans_b to generate gemm that supports transposed B matrix + # set tail_n to support the tail of N + # TODO add trans_b support for other micro gemms + # and move setting of trans_b to the init of CppMicroGemm + def __init__( + self, + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + register_blocking, + alpha=1, + tail_n=False, + trans_b=False, + ) -> None: + super().__init__( + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + register_blocking, + alpha, + ) + self.tail_n = tail_n + # trans_b is only supported on platforms that + # support avx512 or avx2 since transpose_block is + # only implemented on these platforms + if trans_b: + vec_isa = pick_vec_isa() + if not ( + issubclass(vec_isa.__class__, VecAVX512) + or issubclass(vec_isa.__class__, VecAVX2) + ): + raise AssertionError( + f"trans_b requires AVX512 or AVX2 vec ISA, got {vec_isa.__class__}" + ) + self.trans_b = trans_b + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + options = { + "declare_kernel": self.get_kernel_declaration(), + "kernel": kernel, + "block_m": self.register_blocking.block_m, + "block_n": self.register_blocking.block_n, + "block_k": self.register_blocking.block_k, + "trans_b": False, + "tail_n": False, + "restrict_keyword": get_restrict_keyword(), + **self.get_common_options(), + } + if self.trans_b: + # TODO supports tuning of sub_block_m/sub_block_n + # to get better performance for specific shapes + sub_block_m = min(1, self.register_blocking.block_m) + sub_block_n = min(4, self.register_blocking.block_n) + # update options to generate kernel with trans_b and sub-block size + options.update( + { + "trans_b": self.trans_b, + "sub_block_m": sub_block_m, + "sub_block_n": sub_block_n, + } + ) + result = KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render( + options + ) + # update options to generate the kernel for the tail of N + if self.tail_n: + options.update( + { + "tail_n": self.tail_n, + } + ) + result += KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render( + options + ) + result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render( + options + ) + return result + + +def check_vnni_extra(config, m, n, k, alpha, num_threads, **kwargs): + if not (config.input_dtype == torch.uint8 and config.input2_dtype == torch.int8): + raise AssertionError( + "expected input_dtype == torch.uint8 and input2_dtype == torch.int8, " + f"got {config.input_dtype}, {config.input2_dtype}" + ) + vnni_size = 4 + return k % vnni_size == 0 + + +@register_micro_gemm( + *generate_gemm_config( + VecAVX512VNNI, + # (block_m, block_n, block_k) + [(6, 64, 4)], + input_dtype=torch.uint8, + input2_dtype=torch.int8, + output_dtype=torch.int32, + compute_dtype=torch.int32, + extra_check=check_vnni_extra, + ), +) +class CppMicroGemmAVX512VNNI(CppMicroGemm): + """ + This class generates the code for micro gemm using AVX512 VNNI instructions for compute. + It supports u8s8s32 GEMM only. + AVX512_VNNI ISA has been available since the 3rd gen of Intel Xeon. + """ + + TEMPLATE_ENTRY = r""" +{{declare_kernel}} { + {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}"); + {{kernel.assert_function}}(K % {{vnni_size}} == 0, "K dimension must be multiple of {{vnni_size}}"); + constexpr int64_t M_BLOCK = {{block_m}}; + const int64_t M_TAIL = M % M_BLOCK; + const int64_t M_MAIN = M - M_TAIL; + for (int64_t m = 0; m < M_MAIN; m += M_BLOCK) { + for (int64_t n = 0; n < N; n += {{block_n}}) { + {{kernel_name}}_kernel( + A + m * lda, + B + n, + C + m * ldc + n, + K, + lda, + ldb, + ldc + ); + } + } + if (M_TAIL > 0) { + switch (M_TAIL) { +{%- for m_tail in range(block_m - 1, 0, -1) %} + case ({{m_tail}}): + for (int64_t n = 0; n < N; n += {{block_n}}) { + {{kernel_name}}_kernel<{{m_tail}}, {{block_n}}, accum>( + A + M_MAIN * lda, + B + n, + C + M_MAIN * ldc + n, + K, + lda, + ldb, + ldc + ); + } + break; +{%- endfor %} + default: + {{kernel.assert_function}}(false, "Unsupported M_TAIL"); + } // switch M_TAIL + } // if M_TAIL +} +""" + + TEMPLATE_KERNEL = r""" +template +inline void {{kernel_name}}_kernel( + const {{input_t}}* {{restrict_keyword}} A, + const {{input2_t}}* {{restrict_keyword}} B, + {{output_t}}* {{restrict_keyword}} C, + int64_t K, + int64_t lda, + int64_t ldb, + int64_t ldc +) { + constexpr const int COLS = N / {{vec_len}}; + __m512i va; + __m512i vb[COLS]; + __m512i vc[M * COLS]; + + c10::ForcedUnroll{}([&](auto i) { vc[i] = _mm512_setzero_epi32(); }); + + auto compute = [&](auto i, int k) { + constexpr const int row = i / COLS; + constexpr const int col = i % COLS; + + if constexpr (col == 0) { + va = _mm512_set1_epi32(*(int32_t*)(A + row * lda + k)); + } + + if constexpr (row == 0) { + // B block in VNNI layout: [K / {{vnni_size}}, N, {{vnni_size}}] + int64_t offset = k * ldb + col * {{vec_len}} * {{vnni_size}}; + vb[col] = _mm512_loadu_si512((__m512i const*)(B + offset)); + } + vc[i] = _mm512_dpbusd_epi32(vc[i], va, vb[col]); + }; + + // Accumulate along k + constexpr const int k_unroll = 2; + int k = 0; + int k_limit = K / {{vnni_size}} / k_unroll; + for (; k < k_limit; k++) { + c10::ForcedUnroll{}( + [&](auto i) { + c10::ForcedUnroll{}(compute, {{vnni_size}} * (k * k_unroll + i)); + } + ); + } + k *= {{vnni_size}} * k_unroll; + for (; k < K; k += {{vnni_size}}) { + c10::ForcedUnroll{}(compute, k); + } + + // Store to C + auto store_c = [&](auto i) { + constexpr const int row = i / COLS; + constexpr const int col = i % COLS; + if constexpr (accum) { + __m512i vc_old = _mm512_loadu_si512((__m512i const*)(C + row * ldc + col * {{vec_len}})); + vc[i] = _mm512_add_epi32(vc[i], vc_old); + } + _mm512_storeu_si512((__m512i*)(C + row * ldc + col * {{vec_len}}), vc[i]); + }; + c10::ForcedUnroll{}(store_c); +} +""" + + def __init__( + self, + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + register_blocking, + alpha=1, + ) -> None: + super().__init__( + name, + input_dtype, + input2_dtype, + output_dtype, + compute_dtype, + register_blocking, + alpha, + ) + if not (input_dtype == torch.uint8 and input2_dtype == torch.int8): + raise AssertionError( + f"Only u8s8s32 GEMM is supported by AVX512VNNI microkernel, got A:{input_dtype}, B:{input2_dtype}, C:{output_dtype}." + ) + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + options = { + "declare_kernel": self.get_kernel_declaration(), + "kernel": kernel, + "block_m": self.register_blocking.block_m, + "block_n": self.register_blocking.block_n, + "block_k": self.register_blocking.block_k, + "restrict_keyword": get_restrict_keyword(), + "vec_len": 16, # = 512 / 32 for C + **self.get_common_options(), + } + return KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render( + options + ) + KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(options) + + def get_b_layout(self): + return LayoutType.VNNI4 + + +# extra check for CppMicroGemmAMX +def check_amx_extra(config, m, n, k, alpha, num_threads, **kwargs): + vnni_size = 4 if config.input_dtype in [torch.uint8, torch.int8] else 2 + return k % vnni_size == 0 and alpha == 1 + + +def check_int8_bf16_amx_extra(config, m, n, k, alpha, num_threads, **kwargs): + # We need avx512_bf16 to dequant int8 to bf16 + vec_isa = kwargs.get("vec_isa") + if vec_isa is None: + raise AssertionError("expected vec_isa to be set, got None") + return vec_isa.is_avx512_bf16_supported() and check_amx_extra( + config, m, n, k, alpha, num_threads, **kwargs + ) + + +# amx_fp16 need to be checked separately since it is not always supported when amx is supported +def check_amx_fp16_extra(config, m, n, k, alpha, num_threads, **kwargs): + if not (config.input_dtype == torch.float16 and config.output_dtype == torch.float): + raise AssertionError( + "expected input_dtype == torch.float16 and output_dtype == torch.float, " + f"got {config.input_dtype}, {config.output_dtype}" + ) + vec_isa = kwargs.get("vec_isa") + if vec_isa is None: + raise AssertionError("expected vec_isa to be set, got None") + vnni_size = 2 + return vec_isa.is_amx_fp16_supported() and k % vnni_size == 0 and alpha == 1 + + +@register_micro_gemm( + *generate_gemm_config( + VecAMX, + [(32, 32, 64), (48, 16, 64)], + input_dtype=torch.int8, + input2_dtype=torch.int8, + output_dtype=torch.int32, + compute_dtype=torch.int32, + extra_check=check_amx_extra, + ), + *generate_gemm_config( + VecAMX, + [(32, 32, 32), (48, 16, 32)], + input_dtype=torch.bfloat16, + input2_dtype=torch.int8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=check_int8_bf16_amx_extra, + ), + *generate_gemm_config( + VecAMX, + [(32, 16, 32), (32, 32, 32), (48, 16, 32), (16, 48, 32)], + input_dtype=torch.bfloat16, + output_dtype=torch.float, + extra_check=check_amx_extra, + ), + *generate_gemm_config( + VecAMX, + [(32, 32, 32), (48, 16, 32), (16, 48, 32)], + input_dtype=torch.float16, + output_dtype=torch.float, + extra_check=check_amx_fp16_extra, + ), + *generate_gemm_config( + VecAMX, + [(32, 32, 64), (48, 16, 64)], + input_dtype=torch.uint8, + input2_dtype=torch.int8, + output_dtype=torch.int32, + compute_dtype=torch.int32, + extra_check=check_amx_extra, + ), +) +class CppMicroGemmAMX(CppMicroGemm): + """ + This class generates the code for micro gemm using Advanced Matrix extension (AMX) + instructions available in 4th generation Intel Xeon for compute. + It supports input types of torch.bfloat16 with fp32 output. + """ + + TEMPLATE_ENTRY = r""" +{{declare_kernel}} { + {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}"); + {{kernel.assert_function}}(K % 2 == 0, "K dimension must be multiple of 2"); +{%- if pack_vnni_B_locally %} + {{template.codegen_allocate_weight_buffer("packed_B_buf", input2_t, "K", block_n)}} +{%- endif %} +{%- if use_cached_dequantized_B %} + // Create a stack-allocated buffer for tiles of B. + // Except maybe for the tail-case, an AMX tile of B has 16x32 BF16 elements. + // we cache K * {{block_n}} elements of dequantized B + {{template.codegen_allocate_weight_buffer("dequantized_B_buf", input_t, "K", block_n)}} + const auto buf_size = K * {{block_n}}; + auto load_dequantized_B = [&](int base_idx) { + // Load a tile of B & cache it in L1D. + {{input2_t}}* base_addr = const_cast<{{input2_t}}*>(B) + base_idx; + for (int idx_dq = 0, idx_q = 0; idx_dq < buf_size; idx_q += ldb, idx_dq += {{block_n}}) { + {%- for vec_idx in range(0, block_n, 32) %} + _mm_prefetch(base_addr + idx_q + 64 * ldb, _MM_HINT_T0); + {%- if (block_n - vec_idx) >= 32 %} + // 1) Load 32 x int8 + __m256i v8 = _mm256_loadu_si256((const __m256i*)(base_addr + idx_q + {{vec_idx}})); + // 2) Extract two halves + __m128i v8_lo = _mm256_extracti128_si256(v8, 0); + __m128i v8_hi = _mm256_extracti128_si256(v8, 1); + // 3) Widen each half to i32 + __m512i v32_lo = _mm512_cvtepi8_epi32(v8_lo); + __m512i v32_hi = _mm512_cvtepi8_epi32(v8_hi); + // 4) Convert to f32 + __m512 f_lo = _mm512_cvtepi32_ps(v32_lo); + __m512 f_hi = _mm512_cvtepi32_ps(v32_hi); + // 5) f32 -> bf16 (round-to-nearest-even) and pack 32 lanes to 512b + // Packs the second operand (f_lo) into the lower 16 bf16 lanes and the first (f_hi) into the upper 16. + __m512i bf = (__m512i)_mm512_cvtne2ps_pbh(f_hi, f_lo); + // 6) Store 32 x bf16 (512 bits) + _mm512_storeu_si512((__m512i*)(dequantized_B_buf + idx_dq + {{vec_idx}}), bf); + {%- elif (block_n - vec_idx) >= 16 %} + // 1) Load 16 x int8 (128 bits) + __m128i v8 = _mm_loadu_si128((const __m128i*)(base_addr + idx_q + {{vec_idx}})); + // 2) Widen: 16 x i8 -> 16 x i32 + __m512i v32 = _mm512_cvtepi8_epi32(v8); + // 3) Convert to f32 + __m512 f32 = _mm512_cvtepi32_ps(v32); + // 4) Convert f32 -> bf16 (round-to-nearest-even) + __m256i bf16 = (__m256i)_mm512_cvtneps_pbh(f32); + // 5) Store 16 x bf16 (256 bits) + _mm256_storeu_si256((__m256i*)(dequantized_B_buf + idx_dq + {{vec_idx}}), bf16); + {%- else %} + auto b_int8_tail = at::vec::Vectorized::loadu( + base_addr + idx_q + {{block_n - (block_n % 32)}}, + static_cast({{block_n % 32}}) + ); + auto b_bf16_tail = at::vec::convert<{{input_t}}>(b_int8_tail); + b_bf16_tail.store( + dequantized_B_buf + idx_dq + {{block_n - (block_n % 32)}}, + static_cast({{block_n % 32}}) + ); + {%- endif %} + {%- endfor %} + } + }; +{%- endif %} +// The ldb would not be block_n if N != block_n +{%- if use_cached_dequantized_B or pack_vnni_B_locally %} + const int64_t updated_ldb = {{block_n}}; +{%- else %} + const int64_t updated_ldb = ldb; +{%- endif %} + // TODO(jgong5): loop unroll for M and N + for (int64_t n = 0; n < N; n += {{block_n}}) { +{%- if pack_vnni_B_locally %} + // Pack non-constant weights into VNNI interleaved format in packed_B_buf + at::vec::pack_vnni2(B + n, packed_B_buf, ldb, K, {{block_n}}); +{%- elif use_cached_dequantized_B %} + // Dequantize K * block_n int8 B elements into BF16 + load_dequantized_B(n); +{%- endif %} + for (int64_t m = 0; m < M; m += {{block_m}}) { + int64_t block_m = std::min(M - m, {{block_m}}); + int64_t m_tail = m; +{%- for num_rows in range(block_m, 0, -16) %} + {%- if num_rows != block_m %} + else + {%- endif %} + if (block_m >= {{num_rows}}) { + {{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}( + amx_state, + A + m * lda, +{%- if use_cached_dequantized_B %} + dequantized_B_buf, +{%- elif pack_vnni_B_locally %} + packed_B_buf, +{%- else %} + B + n, +{%- endif %} + C + m * ldc + n, + K, + lda, + updated_ldb, + ldc, + 16 + ); + block_m -= {{num_rows}}; + m_tail += {{num_rows}}; + } +{%- endfor %} + if (block_m > 0) { + {{kernel_name}}_amx_kernel_16_{{num_columns}}( + amx_state, + A + m_tail * lda, +{%- if use_cached_dequantized_B %} + dequantized_B_buf, +{%- elif pack_vnni_B_locally %} + packed_B_buf, +{%- else %} + B + n, +{%- endif %} + C + m_tail * ldc + n, + K, + lda, + updated_ldb, + ldc, + block_m + ); + } + } + } +} +""" + + TEMPLATE_KERNEL = r""" + +template +inline void {{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}( + AMXState& amx_state, + const {{input_t}}* {{restrict_keyword}} A, +{%- if use_cached_dequantized_B %} + const {{input_t}}* {{restrict_keyword}} B, +{%- else %} + const {{input2_t}}* {{restrict_keyword}} B, +{%- endif %} + {{output_t}}* {{restrict_keyword}} C, + int64_t K, + int64_t lda, + int64_t ldb, + int64_t ldc, + uint8_t tilecfg_rows +) { + // TODO(jgong5): add prefetch hint for A, B, C + auto loadconfig = [](const amx_tilecfg& cfg) { + _tile_loadconfig(&cfg); + }; + const auto last_k_offset = K / {{block_k}} * {{block_k}}; + const auto tail_k_size = K - last_k_offset; + if C10_LIKELY (last_k_offset > 0) { + amx_state.configure(tilecfg_rows, 64, {{num_rows}} / 16, {{num_columns}}, loadconfig); + } else { + amx_state.configure(tilecfg_rows, tail_k_size * sizeof({{input_t}}), {{num_rows}} / 16, {{num_columns}}, loadconfig); + } + auto load_c = [&]() { +{%- for tile_row in range(num_rows // 16) %} + {%- for tile_col in range(num_columns) %} + {%- set tile_idx = tile_row * num_columns + tile_col %} + _tile_loadd({{tile_idx}}, C + {{tile_row * 16}} * ldc + {{tile_col * 16}}, ldc * sizeof({{output_t}})); + {%- endfor %} +{%- endfor %} + }; + auto zero_c = [&]() { +{%- for tile_row in range(num_rows // 16) %} + {%- for tile_col in range(num_columns) %} + {%- set tile_idx = tile_row * num_columns + tile_col %} + _tile_zero({{tile_idx}}); + {%- endfor %} +{%- endfor %} + }; + + if constexpr (accum) { + load_c(); + } else { + zero_c(); + } + + auto compute = [&](int k) { +{%- set tile_offset_a = num_rows // 16 * num_columns %} +{%- set tile_offset_b = tile_offset_a + num_rows // 16 %} +{%- for tile_row in range(num_rows // 16) %} + {%- for tile_col in range(num_columns) %} + {%- set tile_idx_a = tile_offset_a + tile_row %} + {%- set tile_idx_b = tile_offset_b + tile_col %} + {%- set tile_idx_c = tile_row * num_columns + tile_col %} + {%- if tile_col == 0 %} + _tile_stream_loadd({{tile_idx_a}}, A + {{tile_row * 16}} * lda + k, lda * sizeof({{input_t}})); + {%- endif %} + {%- if tile_row == 0 %} + _tile_loadd({{tile_idx_b}}, B + k * ldb + {{tile_col * 16 * vnni_size}}, ldb * {{vnni_size}} * sizeof({{input_t}})); + {%- endif %} + {%- if int8_gemm %} + {%- if input_dtype == torch.int8 %} + _tile_dpbssd({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}}); + {%- else %} + _tile_dpbusd({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}}); + {%- endif %} + {%- else %} + {%- if input_dtype == torch.float16 %} + _tile_dpfp16ps({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}}); + {%- else %} + _tile_dpbf16ps({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}}); + {%- endif %} + {%- endif %} + {%- endfor %} +{%- endfor %} + }; + + {{kernel.unroll_pragma(4)}} + for (int k = 0; k < last_k_offset; k += {{block_k}}) { + compute(k); + } + + auto store_c = [&]() { + // store to C +{%- for tile_row in range(num_rows // 16) %} + {%- for tile_col in range(num_columns) %} + {%- set tile_idx = tile_row * num_columns + tile_col %} + _tile_stored({{tile_idx}}, C + {{tile_row * 16}} * ldc + {{tile_col * 16}}, ldc * sizeof({{output_t}})); + {%- endfor %} +{%- endfor %} + }; + + // TODO(jgong5): move tail k computation to separate loopnest to save tile configuration overhead + if C10_UNLIKELY (tail_k_size > 0) { + if C10_LIKELY (last_k_offset > 0) { + store_c(); + amx_state.configure(tilecfg_rows, tail_k_size * sizeof({{input_t}}), {{num_rows}} / 16, {{num_columns}}, loadconfig); + load_c(); + } + compute(last_k_offset); + } + + store_c(); +} +""" + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + block_m, block_n, block_k = self.register_blocking + if block_m % 16 != 0: + raise AssertionError("Only support block_m % 16 == 0 for AMX") + if block_n % 16 != 0: + raise AssertionError("Only support block_n % 16 == 0 for AMX") + if self.input_dtype in [torch.uint8, torch.int8]: + if block_k != 64: + raise AssertionError("Only support block_k = 64 for AMX INT8") + else: + if block_k != 32: + raise AssertionError( + "Only support block_k = 32 for AMX Bfloat16/Float16" + ) + num_columns = block_n // 16 + options = { + "declare_kernel": self.get_kernel_declaration(), + "use_cached_dequantized_B": ( + self.input_dtype == torch.bfloat16 + and self.input2_dtype in [torch.int8, torch.uint8] + ), + "kernel": kernel, + "block_m": block_m, + "block_n": block_n, + "block_k": block_k, + "num_columns": num_columns, + "restrict_keyword": get_restrict_keyword(), + **self.get_common_options(), + } + result = "" + for num_rows in range(block_m, 0, -16): + amx_kernel_options = {**options, "num_rows": num_rows} + result += KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render( + amx_kernel_options + ) + result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render( + options + ) + return result + + def codegen_init( + self, + kernel: CppTemplateKernel, + ) -> str: + return "AMXState amx_state;" + + def codegen_finalize( + self, + kernel: CppTemplateKernel, + ) -> str: + return "amx_state.release([]() { _tile_release(); });" + + def get_kernel_extra_args_declare(self) -> str: + return "AMXState& amx_state," + + def get_kernel_extra_args(self, **kwargs) -> list[str]: + return ["amx_state,"] + + def get_b_layout(self): + if self.input_dtype in [torch.uint8, torch.int8]: + return LayoutType.VNNI4 + else: + return LayoutType.VNNI2 + + +# extra check for CppMicroBrgemm +def check_brgemm_extra(config, m, n, k, alpha, num_threads, **kwargs): + if not (config.input_dtype == torch.half and config.output_dtype == torch.float): + raise AssertionError( + "expected input_dtype == torch.half and output_dtype == torch.float, " + f"got {config.input_dtype}, {config.output_dtype}" + ) + vnni_size = 2 + # use brgemm for Half when amx_fp16 is supported + return torch.cpu._is_amx_fp16_supported() and k % vnni_size == 0 and alpha == 1 + + +@register_micro_gemm( + *generate_gemm_config( + VecAMX, + [(32, 32, 32), (48, 16, 32), (16, 48, 32)], + input_dtype=torch.half, + output_dtype=torch.float, + extra_check=check_brgemm_extra, + ), +) +class CppMicroBrgemm(CppMicroGemm): + """ + This class generates the code for micro gemm using oneDNN brgemm. + It supports input types of torch.half. + """ + + TEMPLATE_ENTRY = r""" +#include +{{declare_kernel}} { +{%- if pack_vnni_B_locally %} + {{template.codegen_allocate_weight_buffer("packed_B_buf", input2_t, "K * N")}} + at::vec::pack_vnni2(B, packed_B_buf, ldb, K, N); +{%- endif %} + at::native::cpublas::brgemm( + M, N, K, + {%- if pack_vnni_B_locally %} + lda, N, ldc, + {%- else %} + lda, ldb, ldc, + {%- endif %} + accum, + A, + {%- if pack_vnni_B_locally %} + packed_B_buf, + {%- else %} + B, + {%- endif %} + C); +} +""" + + def codegen_define(self, kernel: CppTemplateKernel) -> str: + options = { + "declare_kernel": self.get_kernel_declaration(), + "kernel": kernel, + "block_m": self.register_blocking.block_m, + "block_n": self.register_blocking.block_n, + "block_k": self.register_blocking.block_k, + "restrict_keyword": get_restrict_keyword(), + **self.get_common_options(), + } + result = "" + result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render( + options + ) + return result + + def codegen_finalize( + self, + kernel: CppTemplateKernel, + ) -> str: + return "at::native::cpublas::brgemm_release();" + + def get_b_layout(self): + if not (self.input_dtype == torch.half and torch.cpu._is_amx_fp16_supported()): + raise AssertionError( + "expected input_dtype == torch.half and AMX fp16 support, " + f"got {self.input_dtype}" + ) + return LayoutType.VNNI2 + + +def check_woq_int4_extra(config, m, n, k, alpha, num_threads, **kwargs): + if alpha != 1: + return False + q_group_size = kwargs.get("q_group_size") + if q_group_size is None: + raise AssertionError("expected q_group_size to be set, got None") + if ( + q_group_size not in [32, 64, 128] + or k % q_group_size != 0 + or config.register_blocking.block_k > q_group_size + ): + return False + return k % config.register_blocking.block_k == 0 and n % 64 == 0 + + +@register_micro_gemm( + # TODO: support float/half input + *generate_gemm_config( + VecAVX512, + [(4, 64, 32), (4, 64, 64), (4, 64, 128)], + input_dtype=torch.bfloat16, + input2_dtype=torch.uint8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=check_woq_int4_extra, + ), +) +class CppMicroGemmWoQInt4Avx512(CppMicroGemmFP32Vec): + """ + This class generates the code for WoQ int4 micro gemm using AVX512 intrinsics. + It is based on the corresponding ATen kernel. + Shape of packed weight = [N // 64, K, 32], viewed as [N, K // 2] + Shape of packed ScalesAndZeros = [K // group_size, N, 2] + """ + + TEMPLATE_ENTRY = r""" +{{declare_kernel}} { + {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}"); + {{kernel.assert_function}}(K % {{block_k}} == 0, "K dimension must be multiple of {{block_k}}"); + auto group_size = q_group_size; + for (int64_t m = 0; m < M; m += {{block_m}}) { + int64_t block_m = std::min(M - m, {{block_m}}); + for (int64_t n = 0; n < N; n += {{block_n}}) { + if (block_m == {{block_m}}) { + {{kernel_name}}_kernel<{{block_m}}, {{block_n}}, accum>( + A + m * lda, + reinterpret_cast(B) + n * ldb, + C + m * ldc + n, + K, + lda, + /* ldb */ {{block_n}} / 2, + ldc, + group_size, + ScaleAndZeros + n * 2, + lds, + k_start + ); + } else { + switch (block_m) { + {%- for b in range(block_m - 1, 0, -1) %} + case {{b}}: + {{kernel_name}}_kernel<{{b}}, {{block_n}}, accum>( + A + m * lda, + reinterpret_cast(B) + n * ldb, + C + m * ldc + n, + K, + lda, + /* ldb */ {{block_n}} / 2, + ldc, + group_size, + ScaleAndZeros + n * 2, + lds, + k_start + ); + break; + {%- endfor %} + default: + {{kernel.assert_function}}(false, "Unsupported block_m"); + } + } + } + } +} +""" + + TEMPLATE_KERNEL = r""" +inline bool {{kernel_name}}_is_block_start(int index, int k_start, int group_size) { + return (k_start + index) % group_size == 0; +} + +inline __m128i {{kernel_name}}_convert_int4_to_int8(const uint8_t* data) { + __m128i tmp = _mm_loadu_si64((const __m128i*)data); + __m128i bytes = _mm_cvtepu8_epi16(tmp); + const __m128i lowMask = _mm_set1_epi8(0xF); + __m128i high = _mm_andnot_si128(lowMask, bytes); + __m128i low = _mm_and_si128(lowMask, bytes); + high = _mm_slli_epi16(high, 4); + bytes = _mm_or_si128(low, high); + return bytes; +} + +template +inline void {{kernel_name}}_kernel( + const {{input_t}}* {{restrict_keyword}} A, + const uint8_t* {{restrict_keyword}} B, + {{output_t}}* {{restrict_keyword}} C, + int64_t K, + int64_t lda, + int64_t ldb, + int64_t ldc, + int64_t q_group_size, + const at::BFloat16* {{restrict_keyword}} ScaleAndZeros, + int64_t lds, // leading dimension of ScaleAndZeros + int64_t k_start) { + constexpr int BLOCK_K = {{block_k}}; + constexpr int ROWS = BLOCK_M; + constexpr int COLS = BLOCK_N / 16; + + const int PREFETCH_SIZE_K = 16 * 4; + const int PREFETCH_SIZE_KB = (PREFETCH_SIZE_K + BLOCK_K - 1) / BLOCK_K; + + // number of blocks on K + const int KB = K / BLOCK_K; + + __m512 va; + __m512 vb[COLS]; + __m512 vc[ROWS * COLS]; + __m512 scale[COLS]; + __m512 zero[COLS]; + + // Lookup table to de-quantize int4 values to bf16. + // Values are dequantized as truly int4 [-8, 7] range; + // + // dequant = (bf16(int4_value) * bf16_scale) + bf16_zero + // + static const __m512 lut = _mm512_set_ps( + 7.0f, 6.0f, 5.0f, 4.0f, + 3.0f, 2.0f, 1.0f, 0.0f, + -1.0f, -2.0f, -3.0f, -4.0f, + -5.0f, -6.0f, -7.0f, -8.0f); + + // index for transpose + static const __m512i idx1 = _mm512_set_epi32( + 30, 28, 26, 24, 22, 20, 18, 16, + 14, 12, 10, 8, 6, 4, 2, 0); + static const __m512i idx2 = _mm512_set_epi32( + 31, 29, 27, 25, 23, 21, 19, 17, + 15, 13, 11, 9, 7, 5, 3, 1); + + // load scale and zero point + auto load_scale_and_zeros = [&](int i, int _kb) { + // load 2x bfloat16 vector + __m512i t = _mm512_loadu_si512((__m512i*)(ScaleAndZeros + _kb * lds + 32 * i)); + _mm_prefetch(ScaleAndZeros + (_kb + PREFETCH_SIZE_KB) * lds + 32 * i, _MM_HINT_T0); + + // convert to 2x f32 vector + __m512 a, b; + at::vec::cvtbf16_fp32(t, a, b); + + // transpose scale_and_zero from {16, 2} to {2, 16} + // inputs: + // a: {s0, z0, s1, z1, ..., s7, z7} + // b: {s8, z8, s9, z9, ..., s15, z15} + // output: + // scale: {s0, s1, s2, ..., s15} + // zero: {z0, z1, z2, ..., z15} + scale[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b); + zero[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b); + }; + + auto loadc = [&](auto i) { + if constexpr (accum) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + vc[i] = _mm512_loadu_ps(C + row * ldc + col * 16); + } else { + vc[i] = _mm512_setzero_ps(); + } + }; + c10::ForcedUnroll{}(loadc); + + auto compute = [&, COLS](auto i, int k) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + + if constexpr (col == 0) { + float aa = static_cast(A[row * lda + k]); + _mm_prefetch(A + row * lda + k + PREFETCH_SIZE_K, _MM_HINT_T0); + va = _mm512_set1_ps(aa); + } + + if constexpr (row == 0) { + if constexpr (COLS == 4) { + // when BLOCK_N = 64, handle each row at a time + // to reduce de-quantize overhead. + if constexpr (col == 0) { + __m256i b4 = _mm256_loadu_si256((__m256i*)(B + k * ldb)); + _mm_prefetch(B + (k + PREFETCH_SIZE_K) * ldb, _MM_HINT_T0); + + __m512i b32 = _mm512_cvtepu8_epi32(_mm256_castsi256_si128(b4)); + vb[0] = _mm512_permutexvar_ps(b32, lut); + vb[0] = _mm512_fmadd_ps(vb[0], scale[0], zero[0]); + vb[2] = _mm512_permutexvar_ps(_mm512_srli_epi32(b32, 4), lut); + vb[2] = _mm512_fmadd_ps(vb[2], scale[2], zero[2]); + + b32 = _mm512_cvtepu8_epi32(_mm256_extracti128_si256(b4, 1)); + vb[1] = _mm512_permutexvar_ps(b32, lut); + vb[1] = _mm512_fmadd_ps(vb[1], scale[1], zero[1]); + vb[3] = _mm512_permutexvar_ps(_mm512_srli_epi32(b32, 4), lut); + vb[3] = _mm512_fmadd_ps(vb[3], scale[3], zero[3]); + } + } else { + __m128i b8 = {{kernel_name}}_convert_int4_to_int8(B + k * ldb + col * 8); + __m512i b32 = _mm512_cvtepu8_epi32(b8); + vb[col] = _mm512_permutexvar_ps(b32, lut); + vb[col] = _mm512_fmadd_ps(vb[col], scale[col], zero[col]); + } + } + + constexpr int idx = row * COLS + col; + vc[idx] = _mm512_fmadd_ps(va, vb[col], vc[idx]); + }; + + for (int k = 0, kb = 0; k < K; ++k) { + if ({{kernel_name}}_is_block_start(k, k_start, q_group_size)) { + c10::ForcedUnroll{}(load_scale_and_zeros, kb++); + } + c10::ForcedUnroll{}(compute, k); + } + + //store to C + auto storec = [&, COLS](auto i) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + _mm512_storeu_ps(C + row * ldc + col * 16, vc[i]); + }; + c10::ForcedUnroll{}(storec); +} +""" + + def get_kernel_extra_args_declare(self) -> str: + return ( + "const int64_t q_group_size,\n" + " const at::BFloat16* __restrict__ ScaleAndZeros,\n" + " const int64_t lds,\n" + " int64_t k_start," + ) + + def get_kernel_extra_args(self, **kwargs) -> list[str]: + if "kernel" not in kwargs: + raise AssertionError("expected 'kernel' in kwargs") + if "qscale_and_zeros" not in kwargs: + raise AssertionError("expected 'qscale_and_zeros' in kwargs") + kernel = kwargs["kernel"] + qscale_and_zeros = kwargs["qscale_and_zeros"] + return [ + "group_size,", + f"&({kernel.index(qscale_and_zeros, [0, 0, 0])}),", + "N * 2,", # lds + "k_start,", + ] + + def is_woq_int4(self): + return True + + +@register_micro_gemm( + *generate_gemm_config( + VecAMX, + [ # (block_m, block_n, block_k) + (16, 32, 32), + (32, 32, 32), + ], + input_dtype=torch.bfloat16, + input2_dtype=torch.uint8, + output_dtype=torch.float, + compute_dtype=torch.float, + extra_check=check_amx_extra, + ), +) +class CppMicroGemmWoQInt4Amx(CppMicroGemmAMX): + """ + This class generates the code for WoQ int4 micro gemm using AMX intrinsics, + which are available on 4th and newer generations of Intel Xeon. + Shape of packed weight = [N // 32, K, 16], viewed as [N, K // 2] + Shape of packed ScalesAndZeros = [K // group_size, N, 2] + Reuse TEMPLATE_KERNEL of CppMicroGemmAMX. + """ + + TEMPLATE_ENTRY = r""" +inline bool {{kernel_name}}_is_block_start(int index, int k_start, int group_size) { + // check if (k_start + index) % group_size == 0, assuming group_size = 32/64/128 + return ((k_start + index) & (group_size - 1)) == 0; +} + +{{declare_kernel}} { + {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}"); + {{kernel.assert_function}}(K % 2 == 0, "K dimension must be multiple of 2"); + {{kernel.assert_function}}({{block_n}} == 32, "block_n must be 32 for WOQ int4"); + + // Create a stack-allocated buffer for tiles of B. + // Except maybe for the tail-case, an AMX tile of B has 16x32 BF16 elements. + // we cache K * {{block_n}} elements of dequantized B + {{template.codegen_allocate_weight_buffer("dequantized_B_buf", input_t, "K", block_n)}} + + constexpr int BLOCK_K = {{block_k}}; + constexpr int64_t BLOCK_N = {{block_n}}; + constexpr int COLS = BLOCK_N / 16; + const int PREFETCH_SIZE_K = 16 * 4; + const int PREFETCH_SIZE_KB = (PREFETCH_SIZE_K + BLOCK_K - 1) / BLOCK_K; + const int KB = K / BLOCK_K; + + __m512i b32[COLS * 2]; + __m512 vb[COLS * 2]; + __m512 scale[COLS]; + __m512 zero[COLS]; + + // Lookup table to de-quantize int4 values to bf16. + // Values are dequantized as truly int4 [-8, 7] range; + // + // dequant = (bf16(int4_value) * bf16_scale) + bf16_zero + // + static const __m512 lut = _mm512_set_ps( + 7.0f, 6.0f, 5.0f, 4.0f, + 3.0f, 2.0f, 1.0f, 0.0f, + -1.0f, -2.0f, -3.0f, -4.0f, + -5.0f, -6.0f, -7.0f, -8.0f); + + // index for transpose + static const __m512i idx1 = _mm512_set_epi32( + 30, 28, 26, 24, 22, 20, 18, 16, + 14, 12, 10, 8, 6, 4, 2, 0); + static const __m512i idx2 = _mm512_set_epi32( + 31, 29, 27, 25, 23, 21, 19, 17, + 15, 13, 11, 9, 7, 5, 3, 1); + + // Indices for VNNI layout conversion + __m512i idx_low = _mm512_set_epi32( + 0x17, + 0x07, + 0x16, + 0x06, + 0x15, + 0x05, + 0x14, + 0x04, + 0x13, + 0x03, + 0x12, + 0x02, + 0x11, + 0x01, + 0x10, + 0x00); + __m512i idx_high = _mm512_set_epi32( + 0x1f, + 0x0f, + 0x1e, + 0x0e, + 0x1d, + 0x0d, + 0x1c, + 0x0c, + 0x1b, + 0x0b, + 0x1a, + 0x0a, + 0x19, + 0x09, + 0x18, + 0x08); + + // load scale and zero point + auto load_scale_and_zeros = [&](int i, int _kb) { + // load 2x bfloat16 vector + __m512i t = _mm512_loadu_si512((__m512i*)(ScaleAndZeros + _kb * lds + 32 * i)); + _mm_prefetch(ScaleAndZeros + (_kb + PREFETCH_SIZE_KB) * lds + 32 * i, _MM_HINT_T0); + + // convert to 2x f32 vector + __m512 a, b; + at::vec::cvtbf16_fp32(t, a, b); + + // transpose scale_and_zero from {16, 2} to {2, 16} + // inputs: + // a: {s0, z0, s1, z1, ..., s7, z7} + // b: {s8, z8, s9, z9, ..., s15, z15} + // output: + // scale: {s0, s1, s2, ..., s15} + // zero: {z0, z1, z2, ..., z15} + scale[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b); + zero[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b); + }; + + // Dequantize a B block of 2 * block_n into bf16 + // So, it handles k and k+1 at the same time + auto dequantize_B = [&](int n) { + constexpr int64_t ldb_int4 = BLOCK_N / 2; // 16 + for (int k = 0, kb = 0; k < K; k += 2) { + // Since block_k must be 32 for AMX microkernels, k_start may not be + // a multiple of q_group_size. In that case, we need to load scales + // and zero points immediately when k == 0 here + if ({{kernel_name}}_is_block_start(k, k_start, q_group_size) || k == 0) { + c10::ForcedUnroll{}(load_scale_and_zeros, kb++); + } + + _mm_prefetch(B + (k + PREFETCH_SIZE_K) * ldb_int4, _MM_HINT_T0); + + // load 256 bits = 64 elements in int4 + __m128i b4 = _mm_loadu_si128((__m128i*)(B + n / 2 * K + k * ldb_int4)); + b32[0] = _mm512_cvtepu8_epi32(b4); + b32[1] = _mm512_srli_epi32(b32[0], 4); + vb[0] = _mm512_permutexvar_ps(b32[0] , lut); + vb[0] = _mm512_fmadd_ps(vb[0], scale[0], zero[0]); + vb[1] = _mm512_permutexvar_ps(b32[1], lut); + vb[1] = _mm512_fmadd_ps(vb[1], scale[1], zero[1]); + + __m128i b4_2 = _mm_loadu_si128((__m128i*)(B + n / 2 * K + (k + 1) * ldb_int4)); + b32[0 + COLS] = _mm512_cvtepu8_epi32(b4_2); + b32[1 + COLS] = _mm512_srli_epi32(b32[0 + COLS], 4); + vb[0 + COLS] = _mm512_permutexvar_ps(b32[0 + COLS] , lut); + vb[0 + COLS] = _mm512_fmadd_ps(vb[0 + COLS], scale[0], zero[0]); + vb[1 + COLS] = _mm512_permutexvar_ps(b32[1 + COLS], lut); + vb[1 + COLS] = _mm512_fmadd_ps(vb[1 + COLS], scale[1], zero[1]); + + for (int i = 0; i < COLS; i++) { + // convert to VNNI + auto low = _mm512_permutex2var_ps(vb[i], idx_low, vb[i + COLS]); + auto high = _mm512_permutex2var_ps(vb[i], idx_high, vb[i + COLS]); + // convert lower 16 float32 values to bfloat16 + auto v0_bf16 = reinterpret_cast<__m256i>(_mm512_cvtneps_pbh(low)); + // convert higher 16 float32 values to bfloat16 + auto v1_bf16 = reinterpret_cast<__m256i>(_mm512_cvtneps_pbh(high)); + // combine the lower 16 and higher 16 bfloat16 values + auto v = _mm512_castsi256_si512(v0_bf16); + v = _mm512_inserti64x4(v, v1_bf16, 1); + // store the VNNI format bfloat16 values + {{input_t}}* addr = dequantized_B_buf + k * 32 + (i % 2) * 32; + _mm512_storeu_si512(addr, v); + } + } + }; + + for (int64_t n = 0; n < N; n += {{block_n}}) { + // Dequantize K * block_n int8 B elements into BF16 + dequantize_B(n); + for (int64_t m = 0; m < M; m += {{block_m}}) { + int64_t block_m = std::min(M - m, {{block_m}}); + int64_t m_tail = m; + {%- for num_rows in range(block_m, 0, -16) %} + {%- if num_rows != block_m %} + else + {%- endif %} + if (block_m >= {{num_rows}}) { + {{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}( + amx_state, + A + m * lda, + dequantized_B_buf + n * K, + C + m * ldc + n, + K, + lda, + {{block_n}}, + ldc, + 16 + ); + block_m -= {{num_rows}}; + m_tail += {{num_rows}}; + } + {%- endfor %} + if (block_m > 0) { + {{kernel_name}}_amx_kernel_16_{{num_columns}}( + amx_state, + A + m_tail * lda, + dequantized_B_buf + n * K, + C + m_tail * ldc + n, + K, + lda, + {{block_n}}, + ldc, + block_m + ); + } + } // for m + } // for n +} +""" + + def get_kernel_extra_args_declare(self) -> str: + return ( + "AMXState& amx_state,\n" + " const int64_t q_group_size,\n" + " const c10::BFloat16* __restrict__ ScaleAndZeros,\n" + " const int64_t lds,\n" + " int64_t k_start," + ) + + def get_kernel_extra_args(self, **kwargs) -> list[str]: + if "kernel" not in kwargs: + raise AssertionError("expected 'kernel' in kwargs") + if "qscale_and_zeros" not in kwargs: + raise AssertionError("expected 'qscale_and_zeros' in kwargs") + kernel = kwargs["kernel"] + qscale_and_zeros = kwargs["qscale_and_zeros"] + return [ + "amx_state,", + "group_size,", + f"&({kernel.index(qscale_and_zeros, [0, 0, 0])}),", + "N * 2,", # lds + "k_start,", + ] + + def is_woq_int4(self): + return True + + +def create_micro_gemm( + name, + m, + n, + k, + input_dtype, + input2_dtype, + output_dtype=None, + compute_dtype=None, + alpha=1, + num_threads=-1, + use_ref=True, + q_group_size=None, +) -> CppMicroGemm | None: + """ + Based on the provided info, try to find the config of the micro-kernel that would + deliver the best performance in terms of lower latency for this case. + """ + + def create_from_config(cls, config: CppMicroGemmConfig): + return cls( + name, + config.input_dtype, + config.input2_dtype, + config.output_dtype, + config.compute_dtype, + config.register_blocking, + alpha, + ) + + def skip_amx_kernel_for_woq(dynamic_M): + # For WoQ GEMM, AMX micro-kernel may not perform well if m is small. + # Exception: for dynamic shapes, we consider using the AMX micro-kernel. + if ( + dynamic_M + or input_dtype != torch.bfloat16 + or input2_dtype not in [torch.int8, torch.uint8] + ): + return False + m_threshold = 5 + return m < m_threshold + + if not (isinstance(n, int) or n.is_number): + raise AssertionError(n) + if not (isinstance(k, int) or k.is_number): + raise AssertionError(k) + from ..utils import has_free_symbols + + dynamic_M = has_free_symbols((m,)) + m = V.graph.sizevars.optimization_hint(m, fallback=1) + if not (isinstance(m, int) or m.is_number): + raise AssertionError(m) + if output_dtype is None: + output_dtype = input_dtype + if compute_dtype is None: + compute_dtype = output_dtype + if num_threads < 0: + num_threads = parallel_num_threads() + vec_isa = pick_vec_isa() + matched_configs = [] + for cls, configs in micro_gemm_configs.items(): + for config in configs: + if not issubclass(vec_isa.__class__, config.vec_isa_cls): + continue + if ( + config.input_dtype == input_dtype + and config.compute_dtype == compute_dtype + and config.input2_dtype == input2_dtype + and config.output_dtype == output_dtype + # The output_dtype here is the output dtype of the micro-kernel. + # In some cases, the actual output dtype of the op for which the micro-kernel + # is being created would be same as that of the activation, but the micro-kernels + # compute output in Float/int32, which is converted in the GEMM template. This is + # subject to change in the future. + ): + if config.extra_check is not None and not config.extra_check( + config, + m, + n, + k, + alpha, + num_threads, + dynamic_M=dynamic_M, + q_group_size=q_group_size, + vec_isa=vec_isa, + ): + continue + block_m, block_n, block_k = config.register_blocking + if config.vec_isa_cls == VecAMX and skip_amx_kernel_for_woq(dynamic_M): + continue + # Criteria on the ranking of configurations + # 1. ISA: AMX > VNNI > VEC + # 2. Dividable by block sizes (block_m, block_n, block_k) + # 3. Number of mxn blocks is large enough to occupy all the threads + # 4. Register blocks are larger + isa_score = 0 + if config.vec_isa_cls == VecAMX: + isa_score += 2 + elif config.vec_isa_cls == VecAVX512VNNI: + isa_score += 1 + dividable_score = 0 + if m % block_m == 0: + dividable_score += 1 + if n % block_n == 0: + dividable_score += 1 + if k % block_k == 0: + dividable_score += 1 + occupancy_score = 0 + n_blocks = (n + block_n - 1) // block_n + total_mxn_blocks = n_blocks * ((m + block_m - 1) // block_m) + if n_blocks >= num_threads: + occupancy_score += 1 + if total_mxn_blocks >= num_threads: + occupancy_score += 1 + register_bytes = ( + block_m * block_n * config.compute_dtype.itemsize + + (block_m * block_k + block_k * block_n) + * config.input_dtype.itemsize + ) + size_score = register_bytes + # if number of mxn blocks can not occupy all the threads, + # we favor smaller register blocks. + if occupancy_score == 0: + size_score = 0 - register_bytes + matched_configs.append( + ( + (isa_score, dividable_score, occupancy_score, size_score), + cls, + config, + ) + ) + if len(matched_configs) == 0: + if use_ref: + return CppMicroGemmRef( + name, input_dtype, input2_dtype, output_dtype, compute_dtype, alpha + ) + else: + return None + # TODO(jgong5): allow autotuning on choices of configs + return create_from_config(*max(matched_configs, key=operator.itemgetter(0))[1:]) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template.py new file mode 100644 index 0000000000000000000000000000000000000000..ee331272d1c2724889786cf7782a406be82671aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template.py @@ -0,0 +1,142 @@ +# mypy: allow-untyped-defs +import ctypes +import functools +import itertools +import logging +import sys +from collections.abc import Callable, Iterable +from unittest.mock import patch + +import sympy + +from .. import config, ir +from ..autotune_process import CppBenchmarkRequest, TensorMeta +from ..utils import IndentedBuffer, Placeholder, unique +from ..virtualized import V +from .common import KernelTemplate +from .cpp_template_kernel import CppTemplateCaller, CppTemplateKernel + + +log = logging.getLogger(__name__) + + +class CppTemplate(KernelTemplate): + index_counter = itertools.count() + + def __init__( + self, + name: str, + input_nodes, + layout: ir.Layout, + num_threads: int, + epilogue_creator: Callable[[ir.Buffer], ir.Pointwise] | None = None, + ) -> None: + super().__init__(name) + self.input_nodes = input_nodes + self.index = next(self.index_counter) + self.output_node: ir.Buffer | list[ir.Buffer] = ir.Buffer( + name=f"buf_out{self.index}", layout=layout + ) + self.layout = layout + self.num_threads = num_threads + self.epilogue_creator = epilogue_creator + + def generate(self, **kwargs): + kernel_name = f"cpp_{self.name}" + with ( + patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)), + patch.object(ir.FlexibleLayout, "allow_indexing", True), + V.graph.set_current_device(self.layout.device), + CppTemplateKernel( + kernel_name=kernel_name, num_threads=self.num_threads + ) as kernel, + ): + code = kernel.render(self, **kwargs) + _, call_args, _, _ = kernel.args.python_argdefs() + log.debug("Generated Code:\n%s", code) + log.debug( + "Args: cpp_argdefs: %s, python_argdefs: %s", + kernel.args.cpp_argdefs(), + kernel.args.python_argdefs(), + ) + + expected_args = list( + unique(input_node.get_name() for input_node in self.input_nodes) + ) + if isinstance(self.output_node, Iterable): + expected_args.extend([node.get_name() for node in self.output_node]) + else: + expected_args.extend([self.output_node.get_name()]) + if list(call_args)[: len(expected_args)] != expected_args: + raise AssertionError( + ( + call_args, + expected_args, + ) + ) + # extra_args are only used for benchmarking, not compiled kernel correctness + extra_args = V.graph.sizevars.optimization_hints( + map(sympy.expand, call_args[len(expected_args) :]) + ) + # Cast the size hint from int to ctypes.c_ulonglong explicitly + # since in cpp kernel, we bind it to C long + extra_args = tuple(ctypes.c_ulonglong(x) for x in extra_args) + + kernel_hash_name = f"cpp_{self.name}_{self.index}" + + # Create the BenchmarkRequest for CPP + bmreq = CppBenchmarkRequest( + 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: ir.CppTemplateBuffer, + flag_template_buffer_has_other_users: bool, + epilogue_nodes: list[ir.IRNode] | None = None, + ): + kernel = CppTemplateKernel( + kernel_name=str(Placeholder.KERNEL_NAME), num_threads=self.num_threads + ) + render = functools.partial( + kernel.render, + self, + template_buffer_node=template_node, + flag_template_buffer_has_other_users=flag_template_buffer_has_other_users, + epilogue_nodes=epilogue_nodes, + **kwargs, + ) + return kernel, render + + return CppTemplateCaller( + kernel_hash_name, + self.name, + self.input_nodes, + # pyrefly: ignore [bad-index, index-error] + self.output_node[0].get_layout() + if isinstance(self.output_node, Iterable) + else self.output_node.get_layout(), + make_kernel_render, + bmreq, + self, + ) + + def header(self) -> IndentedBuffer: + res = IndentedBuffer() + res.writeline("#include ") + # TODO: add c10::ForcedUnroll test to test_aoti_abi_check + res.splice("""#include """) + res.splice("""#include """) + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + if enable_kernel_profile: + res.writelines(["#include "]) + return res + + def render(self, **kwargs) -> str: + raise NotImplementedError diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template_kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..6d1f14bea3de835838b782d1481991696fe0694e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_template_kernel.py @@ -0,0 +1,666 @@ +# mypy: allow-untyped-defs +import itertools +from collections.abc import Callable, Iterable +from typing import Any +from unittest.mock import patch + +import sympy +from sympy.parsing.sympy_parser import parse_expr + +import torch +from torch._inductor.utils import do_bench_using_profiling +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.symbol import SymT + +from .. import config, cpp_builder, ir, lowering as L +from ..autotune_process import CppBenchmarkRequest +from ..loop_body import LoopBody +from ..select_algorithm import PartialRender +from ..utils import sympy_index_symbol, sympy_index_symbol_with_prefix +from ..virtualized import V +from .common import REMOVED +from .cpp import CppKernel, CppKernelProxy, KernelGroup, ParallelDepth +from .cpp_utils import cexpr_index, DTYPE_TO_CPP, LocalBufferContext + + +def parse_expr_with_index_symbols(expr): + if isinstance(expr, sympy.Expr): + return expr + elif isinstance(expr, (list, tuple)): + return [parse_expr_with_index_symbols(e) for e in expr] + else: + expr = parse_expr(str(expr)) + int_symbols = {sym: sympy_index_symbol(sym.name) for sym in expr.free_symbols} + return expr.subs(int_symbols) + + +def wrap_with_tensorbox(node) -> ir.TensorBox: + return ( + ir.TensorBox.create(node) if isinstance(node, ir.Buffer) else ir.TensorBox(node) + ) + + +class CppTemplateKernel(CppKernel): + def __init__(self, kernel_name, num_threads): + super().__init__(None, num_threads) + self.kernel_name = kernel_name + self.render_hooks = {} + self.local_buffers = {} + + def render(self, template, **kwargs): + return PartialRender( + template.render(kernel=self, **kwargs), self.render_hooks + ).finalize_all() + + def def_kernel( + self, + inputs: dict[str, ir.Buffer], + outputs: dict[str, ir.Buffer], + aliases: dict[str, str] | None = None, + function_name: str = "", + extra_sizevars: list[sympy.Expr] | None = None, + placeholder: str = "", + ) -> str: + if len(function_name) == 0: + function_name = str(self.kernel_name) + for name, inp in inputs.items(): + if inp is not None: + self.args.input_buffers[inp.get_name()] = name + for name, out in outputs.items(): + self.args.output_buffers[out.get_name()] = name + if aliases is not None: + for alias, orig in aliases.items(): + if orig in self.args.input_buffers: + self.args.input_buffers[alias] = self.args.input_buffers[orig] + if orig in self.args.output_buffers: + self.args.output_buffers[alias] = self.args.output_buffers[orig] + + unique_sizevars = OrderedSet( + s + for input in inputs.values() + if input is not None + for sym in itertools.chain(input.get_size(), input.get_stride()) + if isinstance(sym, sympy.Expr) + for s in sym.free_symbols + ) + unique_sizevars.update( + s + for sym in extra_sizevars or [] + if isinstance(sym, sympy.Expr) + for s in sym.free_symbols + ) + unique_sizevars.update( + s + for output in outputs.values() + for sym in itertools.chain(output.get_size(), output.get_stride()) + if isinstance(sym, sympy.Expr) + for s in sym.free_symbols + ) + sizevars = sorted(unique_sizevars, key=str) + for sizevar in sizevars: + self.args.sizevars[sizevar] = f"k{sizevar}" + + def hook(): + # remove all aliases before generate function definition + if aliases is not None: + for alias in aliases: + if alias in self.args.input_buffers: + raise AssertionError( + f"input_buffers cannot be removed: {alias}" + ) + if alias in self.args.output_buffers: + self.args.output_buffers[alias] = REMOVED + cpp_argdefs, _, _ = self.args.cpp_argdefs() + return f"void {function_name}({', '.join(cpp_argdefs)})" + + if placeholder in self.render_hooks: + raise AssertionError(f"placeholder already registered: {placeholder}") + self.render_hooks[placeholder] = hook + return placeholder + + def call_kernel(self, name: str, node: ir.CppTemplateBuffer): + wrapper = V.graph.wrapper_code + _, call_args, arg_types = self.args.cpp_argdefs() + wrapper.generate_kernel_call(name, call_args, triton=False, arg_types=arg_types) + + def dtype(self, node: ir.Buffer) -> str: + return DTYPE_TO_CPP[node.get_dtype()] + + def acc_dtype(self, node: ir.Buffer) -> str: + if node.get_dtype() in [torch.float32, torch.bfloat16, torch.half]: + return "float" + else: + raise NotImplementedError(f"Unsupported dtype: {node.get_dtype()}") + + def size(self, node: ir.Buffer, dim: int) -> str: + return cexpr_index(self.rename_indexing(node.get_size()[dim])) + + def stride(self, node: ir.Buffer, dim: int) -> str: + return cexpr_index(self.rename_indexing(node.get_stride()[dim])) + + def index(self, node: ir.Buffer, indices: list[Any]) -> str: + indexer = node.get_layout().as_fixed().make_indexer() + index = indexer(parse_expr_with_index_symbols(indices)) + index = self.rename_indexing(index) + outer_name = node.get_name() + inner_name = ( + outer_name + if outer_name in self.local_buffers + else self.args.input(node.get_name()) + ) + return f"{inner_name}[{cexpr_index(index)}]" + + def slice_nd(self, node, ranges: list[tuple[Any, Any]]) -> ir.ReinterpretView: + """ + Slice the given node with a list of ranges (start and end) corresponding to its dims. + The dim is not sliced if the corresponding range is empty. + """ + if len(ranges) != len(node.get_size()): + raise AssertionError(f"{ranges=}, {node=}") + sliced = wrap_with_tensorbox(node) + for dim, _range in enumerate(ranges): + if len(_range) == 0: + continue + if len(_range) != 2: + raise AssertionError(f"expected range of length 2, got {len(_range)}") + start, end = parse_expr_with_index_symbols(_range) + sliced = L.slice_(sliced, dim, start, end, clamp=False) + if not isinstance(sliced, ir.TensorBox): + raise AssertionError(f"expected ir.TensorBox, got {type(sliced)}") + if not isinstance(sliced.data, ir.ReinterpretView): + raise AssertionError(sliced.data) + return sliced.data + + def select(self, node, dim: int, idx: int) -> ir.ReinterpretView: + # We avoid using L.select here because we need clamp=False so the dim after slicing + # is 1 instead of a sympy expression of symbol - dim_size. + node = wrap_with_tensorbox(node) + idx = ir.View.handle_negative_index(idx, node.get_size()[dim]) + sliced = L.squeeze(L.slice_(node, dim, idx, idx + 1, clamp=False), dim) + if not isinstance(sliced.data, ir.ReinterpretView): + raise AssertionError(sliced.data) + return sliced.data + + def view(self, node, sizes: list[Any]) -> ir.IRNode: + node = wrap_with_tensorbox(node) + sizes = parse_expr_with_index_symbols(sizes) + return L.view(node, sizes).data + + def permute(self, node, dims): + node = wrap_with_tensorbox(node) + permuted = L.permute(node, dims).data + if not isinstance(permuted, ir.ReinterpretView): + raise AssertionError(f"expected ir.ReinterpretView, got {type(permuted)}") + return permuted + + def maybe_codegen_profile(self, prefix_kernel_name: str | None = None) -> str: + if config.cpp.enable_kernel_profile: + graph_id = V.graph.graph_id + prefix = "graph_" + str(graph_id) + "_" if graph_id is not None else "" + if prefix and prefix_kernel_name: + prefix += prefix_kernel_name + "_" + handle_str = ( + "torch::aot_inductor::RAIIAtenRecordFunctionHandle " + f'record_{prefix}{self.kernel_name}_("{prefix}{self.kernel_name}", nullptr);' + ) + return handle_str + else: + return "" + + def unroll_pragma(self, unroll): + if cpp_builder.is_gcc(): + return f"#pragma GCC unroll {unroll}" + else: + return f"#pragma unroll {unroll}" + + def define_buffer(self, name, sizes: list[Any], dtype=torch.float) -> str: + """Define kernel local buffer""" + sizes = parse_expr_with_index_symbols(sizes) + buf = ir.Buffer( + name=name, layout=ir.FixedLayout(torch.device("cpu"), dtype, sizes) + ) + self.local_buffers[name] = buf + ctype = f"{DTYPE_TO_CPP[dtype]}" + numel = f"{cexpr_index(buf.get_numel())}" + return f"auto _{name} = std::make_unique<{ctype}[]>({numel}); auto {name} = _{name}.get();" + + def define_stack_allocated_buffer( + self, name, sizes: list[Any], dtype=torch.float + ) -> str: + """Define stack-allocated buffer""" + sizes = parse_expr_with_index_symbols(sizes) + buf = ir.Buffer( + name=name, layout=ir.FixedLayout(torch.device("cpu"), dtype, sizes) + ) + self.local_buffers[name] = buf + ctype = f"{DTYPE_TO_CPP[dtype]}" + numel = f"{cexpr_index(buf.get_numel())}" + return f"alignas(64) {ctype} _{name}[{numel}]; {ctype}* {name} = _{name};" + + def reinit_buffer_if_null(self, name): + """Reinit the previously defined local buffer if it is null""" + if name not in self.local_buffers: + raise AssertionError(f"unknown local buffer: {name}") + buf = self.local_buffers[name] + ctype = f"{DTYPE_TO_CPP[buf.layout.dtype]}" + numel = f"{cexpr_index(buf.get_numel())}" + return f"if (_{name} == nullptr) {{ _{name} = std::make_unique<{ctype}[]>({numel}); {name} = _{name}.get(); }}" + + def release_buffer(self, name): + """Codegen the code to release the ownership of a local buffer to others""" + if name not in self.local_buffers: + raise AssertionError(f"unknown local buffer: {name}") + return f"_{name}.release()" + + def store_pointwise_nodes( + self, + dst: ir.Buffer, + nodes: list[ir.IRNode], + offsets: list[sympy.Expr] | None = None, + reindexers: list[Callable[[list[Any]], list[Any]] | None] | None = None, + ) -> str: + var_sizes = (tuple(dst.get_size()), ()) + var_ranges = { + sympy_index_symbol_with_prefix(SymT.INDEX, i): sz + for i, sz in enumerate(var_sizes[0]) + } + if not offsets: + offsets = [sympy.S.Zero] * len(var_sizes[0]) + if not reindexers: + reindexers = [None] * len(nodes) + if len(offsets) != len(var_sizes[0]): + raise AssertionError( + f"expected {len(var_sizes[0])} offsets, got {len(offsets)}" + ) + output_index = dst.get_layout().make_indexer()([*var_ranges.keys()]) + kernel_group = KernelGroup() + kernel_group.args = self.args + cpp_kernel_proxy = CppKernelProxy(kernel_group) + bodies = [] + var_sizes_list = [] + for i, node in enumerate(nodes): + output_name = node.get_name() if i < len(nodes) - 1 else dst.get_name() + node = node.data if isinstance(node, ir.ComputedBuffer) else node + if not isinstance(node, ir.Pointwise): + raise AssertionError(node) + + def fn(*args): + if len(args) != 2: + raise AssertionError(f"expected 2 args, got {len(args)}") + if len(args[0]) != len(var_sizes[0]): + raise AssertionError( + f"expected {len(var_sizes[0])} indices, got {len(args[0])}" + ) + if len(args[1]) != 0: + raise AssertionError( + f"expected no reduction vars, got {len(args[1])}" + ) + new_args = [arg + offset for arg, offset in zip(args[0], offsets)] # type: ignore[arg-type] + if reindexers[i] is not None: + new_args = reindexers[i](new_args) # type: ignore[misc] + V.ops.store( + output_name, + output_index, + node.make_loader()(new_args).value, + ) + + body = LoopBody( + fn, + (list(var_ranges.keys()), ()), + var_ranges, + list(var_ranges.keys()), + tuple(), + ) + bodies.append(body) + var_sizes_list.append(var_sizes) + + cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list) + + def max_parallel_depth(): + return ParallelDepth(parallel_depth=0, start_depth=0) + + # This loop is not parallelized since it is not the outermost loop. + with patch.object( + cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth + ): + kernel_group.finalize_kernel(cpp_kernel_proxy, []) + return kernel_group.loops_code.getvalue() + + def store_grouped_gemm_pointwise_nodes( + self, + dst: tuple[ir.Buffer], + nodes: list[ir.IRNode], + offsets: list[sympy.Expr], + reindexers: list[Callable[[list[Any]], list[Any]] | None], + output_names: list[str], + ) -> str: + ref_dst = dst[0] + var_sizes = (tuple(ref_dst.get_size()), ()) + var_ranges = { + sympy_index_symbol_with_prefix(SymT.INDEX, i): sz + for i, sz in enumerate(var_sizes[0]) + } + if not offsets: + raise AssertionError("offsets should be set outside") + if not all(len(offset) == len(var_sizes[0]) for offset in offsets): + raise AssertionError(f"expected all offsets of length {len(var_sizes[0])}") + output_index = ref_dst.get_layout().make_indexer()([*var_ranges.keys()]) + kernel_group = KernelGroup() + kernel_group.args = self.args + cpp_kernel_proxy = CppKernelProxy(kernel_group) + bodies = [] + var_sizes_list = [] + for i, node in enumerate(nodes): + output_name = output_names[i] + node = node.data if isinstance(node, ir.ComputedBuffer) else node + if not isinstance(node, ir.Pointwise): + raise AssertionError(node) + + def fn(*args): + if len(args) != 2: + raise AssertionError(f"expected 2 args, got {len(args)}") + if len(args[0]) != len(var_sizes[0]): + raise AssertionError( + f"expected {len(var_sizes[0])} indices, got {len(args[0])}" + ) + if len(args[1]) != 0: + raise AssertionError( + f"expected no reduction vars, got {len(args[1])}" + ) + new_args = [arg + offset for arg, offset in zip(args[0], offsets[i])] # type: ignore[arg-type] + if reindexers[i] is not None: + new_args = reindexers[i](new_args) # type: ignore[misc] + V.ops.store( + output_name, + output_index, + node.make_loader()(new_args).value, + ) + + body = LoopBody( + fn, + (list(var_ranges.keys()), ()), + var_ranges, + list(var_ranges.keys()), + tuple(), + ) + bodies.append(body) + var_sizes_list.append(var_sizes) + + cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list) + + def max_parallel_depth(): + return ParallelDepth(parallel_depth=0, start_depth=0) + + # This loop is not parallelized since it is not the outermost loop. + with patch.object( + cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth + ): + kernel_group.finalize_kernel(cpp_kernel_proxy, []) + return kernel_group.loops_code.getvalue() + + def store_output( + self, + dst: ir.Buffer, + src: ir.Buffer, + orig_src: ir.Buffer | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + offsets: list[Any] | None = None, + reindexers: list[Callable[[list[Any]], list[Any]] | None] | None = None, + ): + """ + Store the `src` buffer to the `dst` buffer. The size of `src` and `dst` should match. + If `epilogue_nodes` is provided, the `src` buffer is firstly computed with the epilogues + before stored to `dst`. The `epilogues_nodes` are all pointwise. + + Notes: + 1. `src` and `dst` buffer could be the same buffer in which case we are doing in-place compute + and stores. In case `epilogue_nodes` are not provided, we do nothing. + 2. The `epilogue_nodes`, if exist, have computations on `src` before storing to `dst` but since + they come from the original Inductor IR, they might need to be adjusted before working with + `src` and `dst` as outlined below: + a) `src` or `dst` buffer could be a sub-slice of the ranges the `epilogue_nodes`work on. + In this case, the `offsets` could be provided to adjust the indices passed to + `epilogue_nodes` during codegen and the data ranges are also configured according to + the sizes of `src` and `dst`. + b) `dst` might be indexed in a different way as the `epilogue_nodes`, hence a `reindexer` is + needed on the indices to `epilogue_nodes` to match the indexing of `dst`. + c) If `src` is local, we need to add a local buffer for it and localize the `orig_src` buffer + in `epilogue_nodes` with `src`. + """ + if not isinstance(dst, (ir.Buffer, ir.ReinterpretView)): + raise AssertionError( + f"expected ir.Buffer or ir.ReinterpretView, got {type(dst)}" + ) + if dst.get_size() != src.get_size(): + raise AssertionError(f"{dst=}, {src=}") + if offsets: + offsets = parse_expr_with_index_symbols(offsets) + if epilogue_nodes: + with LocalBufferContext(self.args) as scope: + if orig_src is None: + raise AssertionError("orig_src must not be None") + if orig_src.get_name() != src.get_name(): + scope.add_local_buffer( + src, + [ + orig_src, + ], + ) + epilogue_nodes = scope.localize_nodes(epilogue_nodes) + return self.store_pointwise_nodes( + dst, + epilogue_nodes, # type: ignore[arg-type] + offsets, + reindexers, + ) + else: + if dst.get_name() != src.get_name(): + # src is local + copy = L.copy(dst, src).data.data + with LocalBufferContext(self.args) as scope: + scope.add_local_buffer(src) + + return self.store_pointwise_nodes(dst, [copy]) + else: + if dst.layout != src.layout: + raise AssertionError(f"{dst=}, {src=}") + return "" + + def store_outputs( + self, + dst: tuple[ir.Buffer], + src: tuple[ir.IRNode], + orig_src: tuple[ir.IRNode] | None = None, + epilogue_nodes: list[ir.IRNode] | None = None, + offsets: list[Any] | None = None, + reindexers: list[Callable[[list[Any]], list[Any]] | None] | None = None, + multi_output_buffers: tuple[ir.MultiOutput, ...] | None = None, + ): + if not isinstance(dst, Iterable): + raise AssertionError(f"expected Iterable, got {type(dst)}") + if not all(_dst.get_size() == _src.get_size() for _src, _dst in zip(src, dst)): + raise AssertionError("src and dst sizes must match") + if offsets: + offsets = parse_expr_with_index_symbols(offsets) + gemm_num = len(src) + final_offsets = [] + output_names = [] + if epilogue_nodes: + if not reindexers: + reindexers = [None] * len(epilogue_nodes) + with LocalBufferContext(self.args) as scope: + if orig_src is None: + raise AssertionError("orig_src must not be None") + localize_epilogue_nodes = [] + all_read_names = [] + for epilogue in epilogue_nodes: + all_read_names.extend(list(epilogue.get_read_names())) + localize_epilogue_nodes.extend(scope.localize_nodes(epilogue_nodes)) + final_offsets.extend([offsets] * len(localize_epilogue_nodes)) + output_names.extend( + [node.get_name() for node in localize_epilogue_nodes] + ) + for gemm_idx in range(gemm_num): + if orig_src[gemm_idx].get_name() != src[gemm_idx].get_name(): + if orig_src[gemm_idx].get_name() in all_read_names or ( + multi_output_buffers + and multi_output_buffers[gemm_idx].get_name() + in all_read_names + ): + # If any of the Epilogue nodes use this GEMM output, let's localize the GEMM output + global_buffers = [orig_src[gemm_idx]] + if ( + multi_output_buffers + and multi_output_buffers[gemm_idx].get_name() + in all_read_names + and orig_src[gemm_idx].get_name() not in all_read_names + ): + # Epilogue might directly read the MultiOutput, Localize MultiOutput to the local Buffer + # if this MultiOutput has not been stored by in-template epilogue + # otherwise, use the cse store cache if it will be stored before used + global_buffers.append(multi_output_buffers[gemm_idx]) + scope.add_local_buffer( + src[gemm_idx], + global_buffers, + ) + else: + scope.add_local_buffer(src[gemm_idx]) + localize_epilogue_nodes.extend( + [L.copy(dst[gemm_idx], src[gemm_idx]).data.data] + ) + reindexers.append(None) + output_names.append(dst[gemm_idx].get_name()) + final_offsets.append( + [sympy.S.Zero] * len(dst[gemm_idx].get_size()) + ) + res = self.store_grouped_gemm_pointwise_nodes( + dst, + localize_epilogue_nodes, + final_offsets, + reindexers, + output_names=output_names, + ) + for gemm_idx in range(gemm_num): + if ( + multi_output_buffers + and multi_output_buffers[gemm_idx].get_name() in all_read_names + ): + # If the MultiOutput is used in the Epilogue, let's remove it from args + multi_output_name = multi_output_buffers[gemm_idx].get_name() + if ( + multi_output_name in self.args.output_buffers + and self.args.output_buffers[multi_output_name] + is not REMOVED + ): + self.remove_buffer(multi_output_name) + return res + else: + if dst[0].get_name() != src[0].get_name(): + copy_list = [] + with LocalBufferContext(self.args) as scope: + for _src, _dst in zip(src, dst): + copy_list.extend([L.copy(_dst, _src).data.data]) + scope.add_local_buffer(_src) + output_names.append(_dst.get_name()) + final_offsets.append([sympy.S.Zero] * len(_dst.get_size())) + reindexers = [None] * len(copy_list) + return self.store_grouped_gemm_pointwise_nodes( + dst, + nodes=copy_list, + offsets=final_offsets, + reindexers=reindexers, + output_names=output_names, + ) + else: + if not all( + _src.get_name() == _dst.get_name() for _src, _dst in zip(src, dst) + ): + raise AssertionError("src and dst names must match") + if not all( + _src.get_layout() == _dst.get_layout() + for _src, _dst in zip(src, dst) + ): + raise AssertionError("src and dst layouts must match") + return "" + + def check_bounds(self, expr, size, lower, upper): + # CppTemplateKernel does not need codegen related operations + return + + +class CppTemplateCaller(ir.ChoiceCaller): + """ + CppTemplateCaller + + This class represents a caller for CPP template kernels. It is a subclass of ir.ChoiceCaller. + Attributes: + name (str): The name of the caller. + category (str): The category of the caller. + bmreq (CppBenchmarkRequest): The benchmark request for the caller. + template_buffer (ir.CppTemplateBuffer): The template buffer for the caller. + """ + + def __init__( + self, + name: str, + category: str, + input_nodes: list[ir.Buffer], + layout: ir.Layout, + make_kernel_render: Callable[ + [ + ir.CppTemplateBuffer, + bool, + list[ir.IRNode] | None, + ], + str, + ], + bmreq: CppBenchmarkRequest, + template: "CppTemplate", # type: ignore[name-defined] # noqa: F821 + info_kwargs: dict[str, ir.PrimitiveInfoType | list[ir.PrimitiveInfoType]] + | None = 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("bmreq must not be None") + self.bmreq.precompile() + + def benchmark(self, *args, out) -> float: + if self.bmreq is None: + raise AssertionError("bmreq must not be None") + 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 hash_key(self) -> str: + return "-".join( + [ + self.category, + self.bmreq.hash_key, + ] + ) + + def info_dict( + self, + ) -> dict[str, ir.PrimitiveInfoType | list[ir.PrimitiveInfoType]]: + return {"backend": "CPP", "op_type": "unknown"} + + def output_node(self) -> ir.TensorBox: + buffer = ir.CppTemplateBuffer( + layout=self.layout, + inputs=self.input_nodes, + make_kernel_render=self.make_kernel_render, + template=self.template, + choice=self, + ) + # Pass KTC annotation to the buffer for encoding + if "ktc" in self.annotations: + buffer.annotations["ktc"] = self.annotations["ktc"] + return ir.TensorBox.create(buffer) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4c07b5df9472b171a239e2f64635a73297b9e12c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_utils.py @@ -0,0 +1,824 @@ +# mypy: allow-untyped-defs +import contextlib +import dataclasses +import functools +import math +import sys +from collections import namedtuple +from collections.abc import Callable, Sequence +from typing import Any +from unittest.mock import patch + +import sympy + +import torch +from torch._prims_common import is_integer_dtype +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.printers import CppPrinter as _CppPrinter +from torch.utils._sympy.symbol import symbol_is_type, SymT +from torch.utils._sympy.value_ranges import ValueRanges + +from .. import ir +from ..dependencies import Dep +from ..loop_body import LoopBody +from ..scheduler import BaseSchedulerNode, SchedulerBuffer +from ..shape_propagation import BlockShapeType +from ..utils import IndentedBuffer, sympy_index_symbol_with_prefix, sympy_subs +from ..virtualized import ops, OpsValue, V +from .common import CSEVariable, Kernel, KernelArgs, OptimizationContext + + +DTYPE_TO_CPP = { + torch.float32: "float", + torch.float64: "double", + torch.float16: "at::Half", + torch.int64: "int64_t", + torch.int32: "int32_t", + torch.int16: "int16_t", + torch.int8: "int8_t", + torch.uint64: "uint64_t", + torch.uint32: "uint32_t", + torch.uint16: "uint16_t", + torch.uint8: "uint8_t", + torch.bool: "bool", + torch.bfloat16: "at::BFloat16", + torch.complex32: "at::complex", + torch.bcomplex32: "at::complex", + torch.complex64: "at::complex", + torch.complex128: "at::complex", + torch.float8_e4m3fn: "at::Float8_e4m3fn", + torch.float8_e5m2: "at::Float8_e5m2", + torch.float8_e4m3fnuz: "at::Float8_e4m3fnuz", + torch.float8_e5m2fnuz: "at::Float8_e5m2fnuz", + torch.float8_e8m0fnu: "at::Float8_e8m0fnu", +} + +DTYPE_TO_ATEN = { + torch.float32: "at::kFloat", + torch.float64: "at::kDouble", + torch.float16: "at::kHalf", + torch.int64: "at::kLong", + torch.int32: "at::kInt", + torch.int16: "at::kShort", + torch.int8: "at::kChar", + torch.uint64: "at::kUInt64", + torch.uint32: "at::kUInt32", + torch.uint16: "at::kUInt16", + torch.uint8: "at::kByte", + torch.uint32: "at::kUInt32", + torch.uint64: "at::kUInt64", + torch.bool: "at::kBool", + torch.bfloat16: "at::kBFloat16", + torch.complex32: "at::kComplexHalf", + torch.bcomplex32: "at::kBComplex32", + torch.complex64: "at::kComplexFloat", + torch.complex128: "at::kComplexDouble", + torch.float8_e4m3fn: "at::kFloat8_e4m3fn", + torch.float8_e5m2: "at::kFloat8_e5m2", + torch.float8_e4m3fnuz: "at::kFloat8_e4m3fnuz", + torch.float8_e5m2fnuz: "at::kFloat8_e5m2fnuz", + torch.float8_e8m0fnu: "at::kFloat8_e8m0fnu", +} + +DEVICE_TO_ATEN = { + "meta": "at::kMeta", + "cpu": "at::kCPU", + "cuda": "at::kCUDA", + "xpu": "at::kXPU", + "mps": "at::kMPS", +} + +LAYOUT_TO_ATEN = { + torch.strided: "at::kStrided", + torch._mkldnn: "at::kMkldnn", # type: ignore[attr-defined] +} + +# matches c10/core/DeviceType.h +DEVICE_TO_INT = {"cpu": 0, "cuda": 1} + +_IS_WINDOWS = sys.platform == "win32" + +INDEX_TYPE = "int64_t" + +GemmBlocking = namedtuple("GemmBlocking", ["block_m", "block_n", "block_k"]) + + +def get_promote_dtype(args): + return ( + # pyrefly: ignore [no-matching-overload] + functools.reduce( + torch.promote_types, # type: ignore[arg-type] + # pyrefly: ignore [bad-argument-type] + [n.dtype for n in args if isinstance(n, CppCSEVariable)], + ) + if all(n.dtype is not None for n in args if isinstance(n, CppCSEVariable)) + else None # not enough info to calculate the promote dtype + ) + + +def promote_args(new_args): + def promote_arg(arg, promote_type): + if ( + isinstance(arg, CppCSEVariable) + and arg.dtype + and promote_type + and arg.dtype != promote_type + ): + arg = ops.to_dtype(arg, promote_type) + arg = arg.value if isinstance(arg, OpsValue) else arg + arg.dtype = promote_type + return arg + + promote_type = get_promote_dtype(new_args) + promote_fn = functools.partial( + promote_arg, + promote_type=promote_type, + ) + if ( + all( + new_arg.dtype is not None + for new_arg in new_args + if isinstance(new_arg, CppCSEVariable) + ) + and promote_type + ): + new_args = list(map(promote_fn, new_args)) + return new_args + + +class CppCSEVariable(CSEVariable): + def __init__( + self, + name, + bounds: ValueRanges[Any], + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ) -> None: + super().__init__(name, bounds, dtype, shape=shape) + self.is_vec = False + self.dependent_itervars = OrderedSet[sympy.Symbol]() + + def __repr__(self) -> str: + return ( + f"CppCSEVariable(name: {self.name}, bounds: {self.bounds}, is_vec: {self.is_vec}, dtype: {self.dtype}, " + f"dependent_itervars: {self.dependent_itervars})" + ) + + def update_on_args(self, name, args, kwargs): + if name == "load": + # args[2] is index + self._set_dependent_itervars(args[2]) + else: + # propagate relevant itervars and is_vec from args + self.dependent_itervars.update( + *[ + arg.dependent_itervars + for arg in args + if isinstance(arg, CppCSEVariable) + ] + ) + if name in ("index_expr", "value_expr"): + self._set_dependent_itervars(args[0]) + if any(arg.is_vec for arg in args if isinstance(arg, CppCSEVariable)): + self.is_vec = True + + def _set_dependent_itervars(self, index: sympy.Expr): + """ + Set the relevant itervars for this variable based on the `index` expression. + This includes the itervars directly used in the `index` as well as relevant itervars + of other cse variables used in the `index`. + """ + for s in index.free_symbols: + if s in V.kernel.itervars: + self.dependent_itervars.add(s) # type: ignore[arg-type] + elif s.name in V.kernel.cse.varname_map: # type: ignore[attr-defined] + self.dependent_itervars.update( + V.kernel.cse.varname_map[s.name].dependent_itervars # type: ignore[attr-defined] + ) + + def depends_on(self, itervar: sympy.Symbol): + return itervar in self.dependent_itervars + + +class CppPrinter(_CppPrinter): + def doprint(self, expr, *, simplify: bool = True, p=True): + # TODO: why are people passing strings to the printer here :think: + if simplify and isinstance(expr, sympy.Expr) and hasattr(V.graph, "sizevars"): + expr = V.graph.sizevars.simplify(expr) + return super().doprint(expr) + + def parenthesize(self, item: sympy.Expr, level: int, strict: bool = False) -> str: + if isinstance(item, sympy.Mod): + # use parenthesis to enforce precedence. + # in sympy 1.13.3, -2*Mod(x,y) becomes -2*x%y, which is wrong. + # pyrefly: ignore [missing-attribute] + return f"({self._print(item)})" + else: + return super().parenthesize(item, level, strict) + + +# A function to print, useful for printing sympy symbols. +cexpr = CppPrinter().doprint + + +def cexpr_index(index): + return f"static_cast<{INDEX_TYPE}>({cexpr(index)})" + + +def value_to_cpp(value, cpp_type): + if value == float("-inf"): + return f"-std::numeric_limits<{cpp_type}>::infinity()" + elif value == float("inf"): + return f"std::numeric_limits<{cpp_type}>::infinity()" + elif isinstance(value, bool): + return f"static_cast<{cpp_type}>({str(value).lower()})" + elif math.isnan(value): + return f"std::numeric_limits<{cpp_type}>::quiet_NaN()" + else: + return f"static_cast<{cpp_type}>({repr(value)})" + + +def rewrite_index_for_function( + localize_buffer_handler: "LocalizeBufferHandler", + index: sympy.Expr, + global_buf_name: str, +): + # Local buffer at the inner dimensions + snode = V.graph.scheduler.name_to_buf[global_buf_name].defining_op + if snode is None: + raise AssertionError(f"expected defining_op for {global_buf_name}, got None") + local_buf = localize_buffer_handler.global_to_local[global_buf_name] + scheduler_nodes = snode.get_nodes() + _, (group, reduction_group) = max( + scheduler_nodes, key=lambda x: int(x.is_reduction()) + ).group + call_ranges = tuple(group) + tuple(reduction_group) + indices_to_keep = [ + f"x{len(call_ranges) - (idx + 1)}" + for idx in range(len(local_buf.get_layout().size)) + ] + sorted_symbols = sorted(index.free_symbols, key=lambda s: s.name) # type: ignore[attr-defined] + replacements = {} + for x in sorted_symbols: + if x.name.startswith("x") and x.name not in indices_to_keep: # type: ignore[attr-defined] + # Only keep index used by local buffer + replacements[x] = sympy.core.numbers.Zero() + index = sympy_subs(index, replacements) # type: ignore[arg-type] + return index + + +def rewrite_index_for_nodes( + localize_buffer_handler: "LocalizeBufferHandler", + index: sympy.Expr, + global_buf_name: str, +): + used_vars = OrderedSet( + s for s in index.free_symbols if symbol_is_type(s, SymT.INDEX) + ) + index_vars = [] + local_buf = localize_buffer_handler.global_to_local[global_buf_name] + for i in range(len(local_buf.get_size())): + var = sympy_index_symbol_with_prefix(SymT.INDEX, i) + index_vars.append(var if var in used_vars else 0) + index = local_buf.get_layout().make_indexer()(index_vars) + return index + + +class LocalizeBufferHandler(V.WrapperHandler): # type: ignore[name-defined] + def __init__( + self, + inner, + global_to_local: dict[str, ir.Buffer], + rewrite_index: Callable[["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr], + ) -> None: + super().__init__(inner) + self.global_to_local = global_to_local + self.rewrite_index = rewrite_index + + def localize(self, name: str, index: sympy.Expr): + if self.global_to_local and name in self.global_to_local: + if self.rewrite_index is None: + raise AssertionError("expected rewrite_index to be set, got None") + index = self.rewrite_index(self, index, name) + name = self.global_to_local[name].get_name() + return name, index + + def load(self, name: str, index: sympy.Expr): + return self._inner.load(*self.localize(name, index)) + + def store(self, name, index, value, mode=None): + local_buffer_name, local_buffer_index = self.localize(name, index) + res = self._inner.store(local_buffer_name, local_buffer_index, value, mode) + if ( + self.global_to_local + and name in self.global_to_local + and isinstance(V.kernel, Kernel) + ): + # Remove name of local buffer from Kernel.store_buffer_names + # local_buffer_name is added to Kernel.store_buffer_names in Kernel.CSEProxy.store. + V.kernel.store_buffer_names.discard(local_buffer_name) + return res + + def store_reduction(self, name, index, value): + # pyrefly: ignore [bad-argument-count] + return self._inner.store_reduction(*self.localize(name, index), value) + + +class LocalBufferContext: + """ + This class creates a context that helps to generate code involving Inductor IR with + function local buffers. These buffers are constructed during the codegen process and + are used to store intermediate results such as local accumulators. We do not want to + add them to `V.graph` since they are not global and we do not want to add them as + function arguments either. So we patch the codegen processes under this scope to support + these buffers without exposure to the outside world. + """ + + def __init__(self, kernel_args: KernelArgs) -> None: + self.kernel_args = kernel_args + self.exit_stack = contextlib.ExitStack() + # map local buffer name to local buffer + self.local_buffers: dict[str, ir.Buffer] = {} + # map global buffer name to global buffer + self.global_buffers: dict[str, ir.Buffer] = {} + # map global buffer name to local buffer + self.global_to_local: dict[str, ir.Buffer] = {} + # record the global buffers that are removed by this LocalBufferContext + self.removed_buffers: OrderedSet[str] = OrderedSet() + + def __enter__(self): + self.exit_stack.__enter__() + original_get_dtype = V.graph.get_dtype + + def get_dtype(name): + if name in self.local_buffers: + return self.local_buffers[name].get_dtype() + return original_get_dtype(name) + + self.exit_stack.enter_context(patch.object(V.graph, "get_dtype", get_dtype)) + + original_input = self.kernel_args.input + + def input(name): + if name in self.local_buffers: + return name + return original_input(name) + + self.exit_stack.enter_context(patch.object(self.kernel_args, "input", input)) + + original_output = self.kernel_args.output + + def output(name): + if name in self.local_buffers: + return name + return original_output(name) + + self.exit_stack.enter_context(patch.object(self.kernel_args, "output", output)) + + # Set current LocalBufferContext into V + self.exit_stack.enter_context(V.set_local_buffer_context(self)) + + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.local_buffers.clear() + self.exit_stack.__exit__(exc_type, exc_val, exc_tb) + + def add_local_buffer( + self, local_buffer: ir.Buffer, global_buffers: list[ir.Buffer] | None = None + ): + if local_buffer.get_name() in self.local_buffers: + raise AssertionError( + f"local buffer {local_buffer.get_name()} already registered" + ) + self.local_buffers[local_buffer.get_name()] = local_buffer + if global_buffers: + for global_buffer in global_buffers: + global_buffer_name = global_buffer.get_name() + if not ( + global_buffer_name not in self.global_buffers + and global_buffer_name not in self.global_to_local + ): + raise AssertionError( + f"global buffer {global_buffer_name} already registered" + ) + self.global_buffers[global_buffer_name] = global_buffer + self.global_to_local[global_buffer_name] = local_buffer + if global_buffer_name not in V.graph.removed_buffers: + # Record the global buffers that are removed by this LocalBufferContext + # since they may need to be restored. Refer to issue: + # https://github.com/pytorch/pytorch/issues/144186 + self.removed_buffers.add(global_buffer_name) + V.graph.removed_buffers.add(global_buffer_name) + + def localize_function( + self, + fn: Callable[..., Any], + rewrite_index: Callable[ + ["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr + ] = rewrite_index_for_function, + ): + def inner(*args, **kwargs): + with V.set_ops_handler( + LocalizeBufferHandler( + V.get_ops_handler(), + global_to_local=self.global_to_local, + rewrite_index=rewrite_index, + ) + ): + return fn(*args, **kwargs) + + return inner + + def localize_nodes( + self, + nodes: list[ir.IRNode], + rewrite_index: Callable[ + ["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr + ] = rewrite_index_for_nodes, + ) -> list[ir.IRNode]: + """ + Given `local_buf` and `global_buf` registered in current `LocalBufferContext` + though the method of `add_local_buffer`, localizes the `global_buf` to `local_buf` + for the given `nodes` and returns a new list of IR nodes that work on `local_buf` + instead of `global_buf`, i.e., all the loads and stores are redirected to + `local_buf`. This helps the fused loops to work on smaller-sized local buffers + for better data locality. + + The data access of `local_buf` is assumed to be contiguous with the + same order as the `global_buf`. + """ + if len(nodes) <= 0: + raise AssertionError(f"expected non-empty nodes, got {len(nodes)}") + + def wrap_inner_fn_for_node(node: ir.IRNode): + loops = node.data if isinstance(node, ir.ComputedBuffer) else node + if not isinstance(loops, ir.Loops): + raise AssertionError(f"expected ir.Loops, got {type(loops)}") + new_inner_fn = self.localize_function( + loops.inner_fn, + rewrite_index, + ) + + new_loops = dataclasses.replace(loops, inner_fn=new_inner_fn) + if isinstance(node, ir.ComputedBuffer): + new_node = ir.ComputedBuffer( + name=node.get_name(), layout=node.get_layout(), data=new_loops + ) + else: + new_node = new_loops # type: ignore[assignment] + + return new_node + + return [wrap_inner_fn_for_node(node) for node in nodes] + + +def unify_mask_base_type( + buffer: IndentedBuffer, + vars: tuple[CSEVariable, ...], + dtype=torch.float, +): + """ + Given list of cse variables, + Cast each to new mask base dtype and return casted cse variable. + """ + new_vars = ( + V.kernel.cse.generate( + buffer, + f"{V.kernel._get_mask_cast(var, dtype)}", + ) + for var in vars + ) + return new_vars + + +def may_unify_binary_op_mask_type(a, b): + """ + Given two cse variables, when dtype is bool, unify them to the same mask dtype and return casted cse variable. + """ + if a.dtype == torch.bool: + if b.dtype != torch.bool: + raise AssertionError(f"expected b.dtype == torch.bool, got {b.dtype}") + mask_dtype = torch.int32 + return unify_mask_base_type(V.kernel.compute, (a, b), mask_dtype) + return a, b + + +def codegen_rand(offset, code, rand_function, dst_dtype=torch.float32): + if not is_integer_dtype(offset.dtype): + raise AssertionError(f"expected integer dtype, got {offset.dtype}") + code.writeline("[&]()") + with code.indent(): + code.writeline( + f"{DTYPE_TO_CPP[offset.dtype]} offset[{V.kernel.tiling_factor}];" + ) + code.writeline(f"{DTYPE_TO_CPP[dst_dtype]} result[{V.kernel.tiling_factor}];") + code.writeline(f"{offset}.store(offset);") + code.writeline( + f"for( {DTYPE_TO_CPP[offset.dtype]} offset_idx = 0; offset_idx < {V.kernel.tiling_factor}; offset_idx++ )" + ) + with code.indent(): + code.writeline(rand_function) + num_vectors = V.kernel._get_num_vectors(dtype=dst_dtype) + if num_vectors == 1: + code.writeline( + f"return at::vec::Vectorized<{DTYPE_TO_CPP[dst_dtype]}>::loadu(result);" + ) + else: + code.writeline( + f"return at::vec::VectorizedN<{DTYPE_TO_CPP[dst_dtype]}, {num_vectors}>::loadu(result);" + ) + code.writeline("()") + return code + + +def get_gemm_template_output_and_compute_dtype(input_dtype): + if input_dtype in [torch.uint8, torch.int8]: + return (torch.int32, torch.int32) + else: + return (torch.float32, torch.float32) + + +def create_epilogue_with_attr(input_buffer, attr, **kwargs): + input_loader = input_buffer.make_loader() + dtype = input_buffer.get_dtype() + if attr == "relu": + + def inner_fn(index): + input = input_loader(index) + zero = ops.constant(0, dtype) + return ops.maximum(input, zero) + + elif attr == "gelu": + if "algorithm" not in kwargs: + raise AssertionError("expected 'algorithm' in kwargs") + if kwargs["algorithm"] == "none": + + def inner_fn(index): + input = input_loader(index) + if dtype != torch.float: + input = ops.to_dtype(input, torch.float) + half = ops.constant(0.5, torch.float) + one = ops.constant(1.0, torch.float) + const = ops.constant(0.7071067811865476, torch.float) + result = input * half * (ops.erf(input * const) + one) + if dtype != torch.float: + result = ops.to_dtype(result, dtype) + return result + + else: + if kwargs["algorithm"] != "tanh": + raise AssertionError( + f"expected algorithm == 'tanh', got {kwargs['algorithm']}" + ) + + def inner_fn(index): + input = input_loader(index) + if dtype != torch.float: + input = ops.to_dtype(input, torch.float) + half = ops.constant(0.5, torch.float) + one = ops.constant(1.0, torch.float) + const1 = ops.constant(0.7978845608028654, torch.float) + const2 = ops.constant(0.044715, torch.float) + result = ( + half + * input + * ( + one + + ops.tanh(const1 * (input + const2 * input * input * input)) + ) + ) + if dtype != torch.float: + result = ops.to_dtype(result, dtype) + return result + + elif attr == "swish": + + def inner_fn(index): + input = input_loader(index) + result = input * ops.sigmoid(input) + return result + + elif attr == "sigmoid": + + def inner_fn(index): + return ops.sigmoid(input_loader(index)) + + elif attr == "tanh": + + def inner_fn(index): + return ops.tanh(input_loader(index)) + + elif attr == "hardswish" or attr == "hardsigmoid": + + def hardsigmoid_float(input): + zero = ops.constant(0, torch.float) + six = ops.constant(6, torch.float) + three = ops.constant(3, torch.float) + one_over_six = ops.constant(0.16666666666666666, torch.float) + max = ops.maximum(input + three, zero) + min = ops.minimum(max, six) + return min * one_over_six + + def inner_fn(index): + input = input_loader(index) + if dtype != torch.float: + input = ops.to_dtype(input, torch.float) + result = hardsigmoid_float(input) + if attr == "hardswish": + result = input * result + if dtype != torch.float: + result = ops.to_dtype(result, dtype) + return result + + elif attr == "leaky_relu": + if "scalars" not in kwargs: + raise AssertionError("expected 'scalars' in kwargs") + if len(kwargs["scalars"]) != 1: + raise AssertionError(f"expected 1 scalar, got {len(kwargs['scalars'])}") + negative_slope = kwargs["scalars"][0] + + def inner_fn(index): + input = input_loader(index) + if dtype != torch.float: + input = ops.to_dtype(input, torch.float) + zero = ops.constant(0, torch.float) + result = ops.where( + input > zero, input, input * ops.constant(negative_slope, torch.float) + ) + if dtype != torch.float: + result = ops.to_dtype(result, dtype) + return result + + elif attr == "hardtanh": + if "scalars" not in kwargs: + raise AssertionError("expected 'scalars' in kwargs") + if len(kwargs["scalars"]) != 2: + raise AssertionError(f"expected 2 scalars, got {len(kwargs['scalars'])}") + min_value = kwargs["scalars"][0] + max_value = kwargs["scalars"][1] + + def inner_fn(index): + input = input_loader(index) + if dtype != torch.float: + input = ops.to_dtype(input, torch.float) + result = ops.minimum( + ops.maximum(input, ops.constant(min_value, torch.float)), + ops.constant(max_value, torch.float), + ) + if dtype != torch.float: + result = ops.to_dtype(result, dtype) + return result + + elif attr in ["add", "sub", "mul"]: + if "other" not in kwargs: + raise AssertionError("expected 'other' in kwargs") + other = kwargs["other"] + num_input_dims = len(input_buffer.get_size()) + num_other_dims = len(other.get_size()) + dims_diff = num_input_dims - num_other_dims + other_loader = other.make_loader() + + def inner_fn(index): + op = getattr(ops, attr) + if dims_diff != 0: + return op(input_loader(index), other_loader(index[dims_diff:])) + else: + return op(input_loader(index), other_loader(index)) + + elif attr == "bias_add": + if "other" not in kwargs: + raise AssertionError("expected 'other' in kwargs") + if "beta" not in kwargs: + raise AssertionError("expected 'beta' in kwargs") + if "dtype" not in kwargs: + raise AssertionError("expected 'dtype' in kwargs") + beta = kwargs["beta"] + other = kwargs["other"] + dtype = kwargs["dtype"] + bias_loader = other.make_loader() + + def inner_fn(index): + bias = bias_loader(index) + input = input_loader(index) + if beta != 1: + result = ops.constant(beta, torch.float) * bias + input + else: + result = bias + input + return result + + else: + raise ValueError(f"Unsupported epilogue attribute: {attr}") + return ir.Pointwise( + device=input_buffer.get_device(), + dtype=dtype, + inner_fn=inner_fn, + ranges=input_buffer.get_size(), + ) + + +def _get_loop_body(fn_list): + if all(isinstance(fn, LoopBody) for fn in fn_list): + loop_bodies = fn_list + else: + if hasattr(fn_list[0], "original_fn"): + # For the case of local buffer, we wrap the fn with localize_function + if not all(hasattr(fn, "original_fn") for fn in fn_list): + raise AssertionError("expected all fns to have 'original_fn'") + if not all( + isinstance(fn.original_fn.args[0]._body, LoopBody) for fn in fn_list + ): + raise AssertionError("expected all original_fn bodies to be LoopBody") + loop_bodies = [fn.original_fn.args[0]._body for fn in fn_list] + else: + if not all(isinstance(fn, functools.partial) for fn in fn_list): + raise AssertionError("expected all fns to be functools.partial") + if not all(isinstance(fn.args[0]._body, LoopBody) for fn in fn_list): + raise AssertionError("expected all fn bodies to be LoopBody") + loop_bodies = [fn.args[0]._body for fn in fn_list] + if loop_bodies is None: + raise AssertionError("expected loop_bodies to be set, got None") + return loop_bodies + + +def _get_dtype_from_loopbodies(loop_bodies): + dtypes = OrderedSet[torch.dtype]() + for loop_body in loop_bodies: + graphs = [loop_body.root_block.graph] + [ + body.graph for body in list(loop_body.subblocks.values()) + ] + for graph in graphs: + for node in graph.nodes: + if node.op != "call_method": + continue + dtypes.add(node.meta[OptimizationContext.key].dtype) + return dtypes + + +def template_fusion_with_epilogues_supported( + template: BaseSchedulerNode, epilogues: list[BaseSchedulerNode] +) -> tuple[bool, bool]: + def _get_indexes_of_template_buf_read( + epilogue_node: ir.Operation, template_buf_names: list[str] + ) -> list[sympy.Expr]: + return [ + read.index + for read in epilogue_node.get_reads() + if read.name in template_buf_names + ] + + def _check_supported_and_same_indexes( + index_of_template_buf_read: Sequence[sympy.Expr], + epilogue_writes: OrderedSet[Dep], + ) -> tuple[bool, bool]: + num_indexes = len(OrderedSet(index_of_template_buf_read)) + + if num_indexes > 1: + same_index = False + supported = False # Different read indexes not supported + elif num_indexes == 0: + same_index = True + supported = True # No reads, automatically supported + elif num_indexes == 1: + iotbr = index_of_template_buf_read[0] + same_index = all(write.index == iotbr for write in epilogue_writes) + # TODO: Add support of fusion when the read of template buffer and the write of epilogue output + # in the epilogue node don't have the same index and change supported to True + supported = same_index + else: + raise AssertionError("Should not reach here") + + return supported, same_index + + def _template_fusion_supported( + template_outputs: Sequence[SchedulerBuffer], epilogue_nodes: list[ir.Operation] + ) -> tuple[bool, bool]: + template_buf_names = [x.get_name() for x in template_outputs] + indexes_of_template_buf_reads = [ + _get_indexes_of_template_buf_read(epilogue_node, template_buf_names) + for epilogue_node in epilogue_nodes + ] + epilogue_nodes_writes = [ + epilogue_node.get_read_writes().writes for epilogue_node in epilogue_nodes + ] + + results = [ + _check_supported_and_same_indexes(reads, writes) + for reads, writes in zip( + indexes_of_template_buf_reads, epilogue_nodes_writes + ) + ] + supported, same_indexes = zip(*results) + return all(supported), all(same_indexes) + + if not template.is_template(): + raise AssertionError("expected template.is_template() to be True") + template_outputs = template.get_outputs() + + epilogue_nodes = [ + n.node + for epilogue in epilogues + for n in epilogue.get_nodes() + if n.node is not None + ] + return _template_fusion_supported(template_outputs, epilogue_nodes) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..37fbcbbbf4f81b07e2be29fb280a38f8b18712da --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu.py @@ -0,0 +1,4360 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import contextlib +import ctypes +import dataclasses +import functools +import math +import os +import sys +import textwrap +from itertools import chain, count +from typing import Any, Literal, TYPE_CHECKING + +import sympy + +import torch +import torch._higher_order_ops.torchbind +import torch._inductor.async_compile +import torch._ops +from torch import dtype as torch_dtype +from torch._inductor.runtime.runtime_utils import dynamo_timed +from torch.fx.experimental.symbolic_shapes import ConvertIntKey, DivideByKey, SymTypes +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import CleanDiv, FloorDiv, Mod, ModularIndexing +from torch.utils._sympy.symbol import symbol_is_type, SymT + +from .. import config, ir +from ..ir import ExternKernel +from ..utils import ( + _align, + AotOnlyBuffer, + DualIndentedBuffer, + make_codegen_buffer, + normalize_name, +) +from ..virtualized import V +from .aoti_hipify_utils import maybe_hipify_code_wrapper +from .common import get_device_op_overrides, IndentedBuffer, Kernel +from .cpp_utils import ( + cexpr, + DEVICE_TO_ATEN, + DEVICE_TO_INT, + DTYPE_TO_ATEN, + DTYPE_TO_CPP, + LAYOUT_TO_ATEN, +) +from .wrapper import ( + _rewrite_symbol_solution_for_int_codegen, + codegen_reinterpret_view_helper, + EnterSubgraphLine, + ExitSubgraphLine, + HasWriteLine, + PythonWrapperCodegen, + SymbolicCallArg, + WrapperLine, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from ..graph import GraphLowering + from ..runtime.hints import TritonMeta + + # At most, the list nesting can go one layer deep. + _OUTPUT_ARGS_TYPE = list[str | None | list[str | None]] + + from ..scheduler import BaseSchedulerNode + + +@dataclasses.dataclass +class DualWrapperCodeLine(WrapperLine): + jit_code: IndentedBuffer + aot_code: AotOnlyBuffer + + def codegen(self, code: DualIndentedBuffer) -> None: + # In dual-wrapper replay, these route each captured snippet to the + # matching side. If replayed on a plain IndentedBuffer, splice_jit writes + # normally and splice_aot is a no-op, preserving the same selection. + code.splice_jit(self.jit_code) + code.splice_aot(self.aot_code) + + +@dataclasses.dataclass +class DeferredCpuTritonCallWrapper: + """CPU counterpart of DeferredTritonCallWrapper in cpp_wrapper_gpu.py. + + Deferred so wrapper emission can read `CpuTritonKernelCache` entries + after the autotune block has populated them. + + NOTE: CPU doesn't actively use autotuning, but we mirror + the GPU flow for symmetry. + """ + + wrapper_name: str + kernel_name: str + arg_types: list[Any] + triton_meta: TritonMeta | None = None + inductor_meta: dict[str, Any] | None = None + + def _get_cpp_param_type(self, name: str, arg_type: Any) -> str: + if isinstance(arg_type, torch_dtype): + return f"const {name}_type_& {name}" + elif issubclass(arg_type, (SymbolicCallArg, sympy.Expr, int)): + return f"int64_t {name}" + elif arg_type is float: + return f"float {name}" + elif arg_type is bool: + return f"bool {name}" + else: + raise ValueError( + f"Unexpected arg type {arg_type} for CPU triton wrapper arg '{name}'" + ) + + def _resolve_arg_names( + self, + ) -> tuple[list[str], list[str], list[str]]: + """Return (wrapper_arg_names, kernel_arg_names, grid_arg_names). + + Wrapper args exclude *declared* constexpr (the call site doesn't pass + them); kernel args additionally exclude *value-specialized* constexpr + (baked into the binary). Grid args are appended for `run_from_nativert`. + """ + from torch._inductor.codecache import CpuTritonKernelCache + + info = CpuTritonKernelCache.get(self.kernel_name) + if info is None: + raise AssertionError( + f"CpuTritonKernelCache not populated for {self.kernel_name}" + ) + signature = info["signature"] + declared_constexpr_names = OrderedSet( + (self.inductor_meta or {}).get("declared_constexpr_names", []) + ) + wrapper_arg_names = [ + name for name in signature if name not in declared_constexpr_names + ] + kernel_arg_names = [name for name, ty in signature.items() if ty != "constexpr"] + grid_arg_names = list((self.inductor_meta or {}).get("extra_launcher_args", [])) + return wrapper_arg_names + grid_arg_names, kernel_arg_names, grid_arg_names + + def _write_wrapper_signature( + self, + prefix: IndentedBuffer, + wrapper_arg_names: list[str], + ) -> None: + # `cubin_dir_` name reused from GPU so the same AOTI runtime member feeds both. + if len(wrapper_arg_names) != len(self.arg_types): + raise AssertionError( + ( + wrapper_arg_names, + self.arg_types, + ) + ) + template_types = [ + f"typename {name}_type_" + for name, arg_type in zip(wrapper_arg_names, self.arg_types) + if isinstance(arg_type, torch_dtype) + ] + if V.graph.aot_mode: + template_types.append("typename kernels_type_") + if template_types: + prefix.writeline(f"template <{', '.join(template_types)}>") + + param_lines = [ + self._get_cpp_param_type(name, arg_type) + for name, arg_type in zip(wrapper_arg_names, self.arg_types) + ] + if V.graph.aot_mode: + param_lines.append("kernels_type_& kernels_") + param_lines.append( + "const std::optional& cubin_dir_ = std::nullopt" + ) + + prefix.writeline(f"static __attribute__((noinline)) void {self.wrapper_name}(") + with prefix.indent(): + for i, param in enumerate(param_lines): + comma = "," if i < len(param_lines) - 1 else "" + prefix.writeline(f"{param}{comma}") + prefix.writeline("){") + + def _generate_load_kernel( + self, + prefix: IndentedBuffer, + kernel_so: str, + launcher_so: str, + kernel_symbol: str, + ) -> None: + # `std::call_once` keeps init thread-safe under concurrent first calls. + kernel_member = f"kernels_.{self.kernel_name}_kernel_fn" + launcher_member = f"kernels_.{self.kernel_name}_launcher_fn" + prefix.splice(f""" + using namespace torch::aot_inductor; + static std::once_flag {self.kernel_name}_init_flag; + std::call_once({self.kernel_name}_init_flag, [&]() {{ + {kernel_member} = loadCpuTritonKernel( + "{kernel_so}", "{kernel_symbol}", cubin_dir_); + {launcher_member} = loadCpuTritonLauncher( + "{launcher_so}", cubin_dir_); + }}); + """) + + def _generate_launch( + self, + prefix: IndentedBuffer, + kernel_arg_names: list[str], + grid_arg_names: list[str], + signature: dict[str, Any], + ) -> None: + # The launcher uses literal `args[i]` indices over the *original* + # signature, so constexpr slots must be padded (nullptr) to keep + # non-constexpr args at the expected positions. + kernel_member = f"kernels_.{self.kernel_name}_kernel_fn" + launcher_member = f"kernels_.{self.kernel_name}_launcher_fn" + + args_array_entries: list[str] = [] + for name, ty in signature.items(): + if ty == "constexpr": + args_array_entries.append("nullptr") + elif isinstance(ty, str) and ty.startswith("*"): + args_array_entries.append(f"{name}.data_ptr()") + else: + args_array_entries.append(f"&{name}") + args_arr_str = ", ".join(args_array_entries) + + # Grid args are int64_t in the wrapper but the launcher ABI is uint32_t. + grid_x = grid_arg_names[0] if len(grid_arg_names) > 0 else "1" + grid_y = grid_arg_names[1] if len(grid_arg_names) > 1 else "1" + grid_z = grid_arg_names[2] if len(grid_arg_names) > 2 else "1" + + # TODO: thread `num_cpu_threads` from inductor_meta (autotune support). + prefix.splice(f""" + void* args_arr[] = {{ {args_arr_str} }}; + {launcher_member}( + static_cast({grid_x}), + static_cast({grid_y}), + static_cast({grid_z}), + /*num_cpu_threads=*/1, + args_arr, + {kernel_member}); + """) + + def generate(self, wrapper: CppWrapperCpu) -> None: + from torch._inductor.codecache import CpuTritonKernelCache + + info = CpuTritonKernelCache.get(self.kernel_name) + if info is None: + raise RuntimeError( + f"CpuTritonKernelCache not populated for '{self.kernel_name}': " + "the autotune block did not save this kernel. Check that " + "config.triton.autotune_at_compile_time is True and the Triton " + "CPU backend emits a launcher .so exporting `run_from_nativert`." + ) + + signature = info["signature"] + wrapper_arg_names, kernel_arg_names, grid_arg_names = self._resolve_arg_names() + + prefix = wrapper.prefix + self._write_wrapper_signature(prefix, wrapper_arg_names) + with prefix.indent(): + self._generate_load_kernel( + prefix, + info["kernel_so_path"], + info["launcher_so_path"], + info["kernel_symbol"], + ) + self._generate_launch(prefix, kernel_arg_names, grid_arg_names, signature) + prefix.writeline("}") + + # Register .so artifacts so the AOTI packager picks them up. + V.graph.wrapper_code.additional_files.append(info["kernel_so_path"]) + V.graph.wrapper_code.additional_files.append(info["launcher_so_path"]) + + +class CppWrapperCpu(PythonWrapperCodegen): + """ + Generates cpp wrapper for running on CPU and calls cpp kernels + """ + + def __init__(self): + if not hasattr(self, "device"): + self.device = "cpu" + # must be initialized prior to calling super().__init__() + self.included_devices: OrderedSet[str] = OrderedSet() + self.model_class_name_suffix = ( + "" + if config.aot_inductor.dynamic_linkage + else config.aot_inductor.model_name_for_generated_files + ) + self.aoti_model_class_name = f"AOTInductorModel{self.model_class_name_suffix}" + + super().__init__() + + self.declare = "auto " + self.declare_maybe_reference = "decltype(auto) " + self.ending = ";" + self.comment = "//" + self.none_str = "nullptr" + self.supports_intermediate_hooks = False + self.kernel_callsite_id = count() + self.int_array_id = count() # for int array local variable declarations + self.declared_int_array_vars: OrderedSet[str] = OrderedSet() + self.tmp_tensor_id = count() # for tmp tensor local variable declarations + self.arg_var_id = count() + self._aot_output: str | None = None + # Defined kernels drive member declarations; called kernels drive + # `call_` emission. A kernel may be defined without being called. + self._cpu_triton_kernel_names: OrderedSet[str] = OrderedSet() + self._cpu_triton_call_wrappers: dict[str, DeferredCpuTritonCallWrapper] = {} + self.used_cached_devices: OrderedSet[str] = OrderedSet() + self.used_cached_dtypes: OrderedSet[str] = OrderedSet() + self.used_cached_layouts: OrderedSet[str] = OrderedSet() + self.used_cached_memory_formats: OrderedSet[str] = OrderedSet() + self.used_switch_selector: OrderedSet[str] = OrderedSet() + self.cached_output_id = count() + self.scalar_to_tensor_id = count() + self.custom_op_wrapper_loaded = False + # For GEMM kernels that must be initialized and are resolved at linking. + self.initialized_kernels: dict[str, Kernel] = {} + self.device_codegen = get_device_op_overrides(self.device) + self._included_extra_headers: OrderedSet[str] = OrderedSet() + self.codegen_int_array_var_cache = {} + self.needs_vec_isa = self.device == "cpu" + + @contextlib.contextmanager + def _preserve_device_guard_state(self): + last_seen_device_guard_index = self.last_seen_device_guard_index + try: + yield + finally: + self.last_seen_device_guard_index = last_seen_device_guard_index + + @contextlib.contextmanager + def _preserve_codegen_state(self, graphs): + wrapper_state = ( + OrderedSet(self.allocated), + OrderedSet(self.freed), + dict(self.reuses), + dict(self.allocated_workspaces), + OrderedSet(self.declared_int_array_vars), + dict(self.codegen_int_array_var_cache), + OrderedSet(self.kernel_numel_expr), + OrderedSet(self.used_switch_selector), + ) + subgraph_state = [ + ( + graph, + OrderedSet(graph.removed_buffers), + OrderedSet(graph.inplaced_to_remove), + ) + for graph in graphs + ] + try: + yield + finally: + ( + self.allocated, + self.freed, + self.reuses, + self.allocated_workspaces, + self.declared_int_array_vars, + self.codegen_int_array_var_cache, + self.kernel_numel_expr, + self.used_switch_selector, + ) = wrapper_state + for graph, removed_buffers, inplaced_to_remove in subgraph_state: + graph.removed_buffers = removed_buffers + graph.inplaced_to_remove = inplaced_to_remove + + @staticmethod + def create( + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: ir.GraphPartitionSignature | None = None, + ): + # TODO - support subgraph codegen by lifting functions. Check the + # comment at CppWrapperCpu `codegen_subgraph` function. + return CppWrapperCpu() + + @contextlib.contextmanager + def _target_buf(self, attr: str, buf: IndentedBuffer): + """Temporarily redirect self. to a specific buffer.""" + saved = getattr(self, attr) + setattr(self, attr, buf) + try: + yield + finally: + setattr(self, attr, saved) + + @staticmethod + def _generate_temporary_array_pointer( + c_type: str, elements: Sequence[str], *, force_mutable: bool = False + ) -> str: + """Get a pointer to an array that only exists for the duration of the C++ + statement it's used in.""" + # If the c_type is already a pointer, return a mutable pointer to the array. + # Otherwise, return a const pointer. In the C-shim API, pointer types are only + # const-qualified with respect to the underlying value, not any nested pointers. + # e.g. const double** is possible, but not const double* const*. This means + # that an array containing pointers must _already_ be properly const-qualified + # by the c_type, and not add additional const-ness. + array_expr = f"std::array<{c_type}, {len(elements)}>{{{', '.join(elements)}}}" + if force_mutable or c_type.endswith("*"): + return f"{array_expr}.data()" + + return f"static_cast({array_expr}.data())" + + 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, + ): + """ + Generates kernel call code. + + triton: Defines whether the GPU backend uses Triton for codegen. + Otherwise it uses the CUDA language for codegen. + Only valid when cuda == True. + """ + if not (arg_types is not None and len(call_args) == len(arg_types)): + raise AssertionError( + "Mismatch call_args and arg_types in generate_kernel_call:\n" + f"call_args: {call_args}\n" + f"arg_types: {arg_types}" + ) + + # CPU Triton kernel: run the autotune block (populates + # `CpuTritonKernelCache`) and emit `call_(...)`; the body is + # defined later by `DeferredCpuTritonCallWrapper` in `finalize_prefix`. + if triton and kernel_name in self._cpu_triton_kernel_names: + if ( + config.triton.autotune_at_compile_time + and kernel_name not in self.kernel_autotune_names + ): + PythonWrapperCodegen._generate_kernel_call_helper( + self, + kernel_name, + call_args, + device=device, + triton=triton, + arg_types=arg_types, + raw_keys=raw_keys, + raw_args=raw_args, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + original_fxnode_name=original_fxnode_name, + ) + + wrapper_name = f"call_{kernel_name}" + if wrapper_name not in self._cpu_triton_call_wrappers: + self._cpu_triton_call_wrappers[wrapper_name] = ( + DeferredCpuTritonCallWrapper( + wrapper_name=wrapper_name, + kernel_name=kernel_name, + arg_types=list(arg_types), + triton_meta=triton_meta, + inductor_meta=inductor_meta, + ) + ) + + stringified_args = [ + self._stringify_cpu_triton_call_arg(a) for a in call_args + ] + if V.graph.aot_mode: + stringified_args.append("kernels") + stringified_args.append("this->cubin_dir_") + self.writeline(self.wrap_kernel_call(wrapper_name, stringified_args)) + return + + new_args = [] + for idx, arg in enumerate(call_args): + if isinstance(arg_types[idx], str) and "*" in arg_types[idx]: + new_args.append(f"({arg_types[idx]})({arg}.data_ptr())") + else: + # arg is a scalar - ensure it's a string for C++ codegen + # With Triton support, arg might be a SymPy expression or other type + new_args.append(str(arg) if not isinstance(arg, str) else arg) + # debug printer related logic for cpp kernel type. + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + call_args, + kernel_name, + None, + None, + "cpp", + ) + with debug_printer_manager: + self.writeline(self.wrap_kernel_call(kernel_name, new_args)) + + def write_constant(self, name, hashed): + # include a hash so our code cache gives different constants different files + self.header.writeline(f"// {name} {hashed}") + + @staticmethod + def get_device_include_path_jit(device: str) -> str: + return f"#include " + + @staticmethod + def get_device_include_path_aot(device: str) -> str: + return f"#include " + + def add_device_include(self, device: str) -> None: + if device in self.included_devices: + return + + self.included_devices.add(device) + + # Add the default header for this device, plus any C-shim extensions that are + # present. + self.header.splice_jit(self.get_device_include_path_jit(device)) + self.header.splice_aot(self.get_device_include_path_aot(device)) + extend_aoti_c_shim_include = ( + f"torch/csrc/inductor/aoti_torch/generated/extend/c_shim_{self.device}.h" + ) + extend_aoti_c_shim_path = os.path.join( + os.path.dirname(torch.__file__), + "include", + extend_aoti_c_shim_include, + ) + if os.path.exists(extend_aoti_c_shim_path): + self.header.splice(f"#include <{extend_aoti_c_shim_include}>") + + def _write_aoti_interface_header(self): + """Emit the AOTI runtime interface include or inline.""" + if config.aot_inductor.dynamic_linkage: + with open( + os.path.join(os.path.dirname(__file__), "aoti_runtime", "interface.cpp") + ) as f: + self.header.splice_aot(f.read()) + else: + # we produce a separate model header for each model in static linkage + self.header.splice_aot(f"""#include \"{self.model_class_name_suffix}.h\"""") + self.header.splice_aot("\n") + + def write_header(self): + if V.graph.is_const_graph: + # We do not write header for constant graph, it will be written by main module. + return + + if not V.graph.aot_mode: + self.header.splice(''' + import torch + from torch._inductor.codecache import CppWrapperCodeCache + + cpp_wrapper_src = ( + r""" + ''') + + for device in V.graph.device_types: + if device != "meta": + self.add_device_include(device) + if not self.included_devices: + # When only meta device is present, add_device_include is never + # called so we need to pull in the common header explicitly. + if V.graph.aot_mode: + self.header.writeline( + "#include " + ) + else: + self.header.writeline( + "#include " + ) + + if V.graph.aot_mode: + self._write_aoti_interface_header() + + if config.cpp.enable_kernel_profile and config.cpp.enable_kernel_context_guard: + self.header.splice( + "#include " + ) + self.header.splice(""" + namespace torch::aot_inductor { + thread_local KernelContext* tls_kernel_context = nullptr; + } + """) + + def include_extra_header(self, header: str): + # This is needed for cpp to python dtype conversion + if header in self._included_extra_headers: + return + self._included_extra_headers.add(header) + self.header.splice(f"#include <{header}>") + + def mark_output_type(self): + # mark output type to unwrap tensor back to python scalar + from ..ir import ShapeAsConstantBuffer + + output_is_tensor = {} + for idx, x in enumerate(V.graph.graph_outputs): + if isinstance(x, ShapeAsConstantBuffer): + output_is_tensor[idx] = False + else: + output_is_tensor[idx] = True + + self.output_is_tensor = output_is_tensor + + def write_prefix(self): + if V.graph.is_const_graph: + # We do not write prefix for constant graph, it will be written by main module. + return + if config.aot_inductor.custom_ops_to_c_shims: + # custom_ops_to_c_shims contains declaration of custom ops with C shim. + # TODO: this could be auto-generated from a passed-in custom op schema + custom_c_shims = list( + chain(*config.aot_inductor.custom_ops_to_c_shims.values()) + ) + declarations = "\n".join( + [f"extern {textwrap.dedent(shim)};" for shim in custom_c_shims] + ) + self.prefix.splice(f""" + extern "C" {{ + {declarations} + }} + """) + self.prefix.writeline_aot("namespace torch::aot_inductor {") + if not V.graph.is_const_graph: + self.codegen_input_size_and_nan_asserts() + + def write_input_output_info( + self, + info_kind: str, + idx: int, + name: str, + ): + self.prefix.writeline(f"""{info_kind}[{idx}].name = "{name}";""") + + def codegen_input_symbol_assignment( # type: ignore[override] + self, + name: str, + value: ir.TensorBox, + bound_vars: OrderedSet[sympy.Symbol], + deferred_symbol_assignments=None, + ): + """Assign symbolic shapes to C++ locals, with replacement aliases.""" + code = self.prefix + + @functools.cache + def sizeof(name): + self.codegen_input_size_var_decl(code, name) + return f"{name}_size" + + @functools.cache + def strideof(name): + self.codegen_input_stride_var_decl(code, name) + return f"{name}_stride" + + def codegen_symbol( + sym_or_exp: sympy.Symbol | sympy.Expr, + base_name: str, + name_fn: Callable[[str], str], + dim: int, + deferred_symbol_assignments=None, + ) -> bool: + if isinstance(sym_or_exp, sympy.Symbol): + if sym_or_exp in bound_vars: + return False + code.writeline(f"int64_t {sym_or_exp} = {name_fn(base_name)}[{dim}];") + bound_vars.add(sym_or_exp) + if symbol_is_type(sym_or_exp, (SymT.UNBACKED_INT, SymT.UNBACKED_FLOAT)): + self.unbacked_symbol_decls.add(str(sym_or_exp)) + self.maybe_emit_replacement_aliases(sym_or_exp, bound_vars) + return True + elif isinstance(sym_or_exp, sympy.Expr): + undefined_symbols = [ + sym for sym in sym_or_exp.free_symbols if sym not in bound_vars + ] + if len(undefined_symbols) != 1: + # Skip if expression contains no symbols or if multiple + # symbols exists since we assume each base symbol is defined + # by other codegen_symbol calls. + if ( + len(undefined_symbols) > 1 + and deferred_symbol_assignments is not None + ): + + def retry(deferred_symbol_assignments): + return codegen_symbol( + sym_or_exp, + base_name, + name_fn, + 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(base_name) + # Use a size symbol to solve the free symbol + size_symbol = sympy.Symbol(f"{base_name}_{dim}", integer=True) + solution = try_solve(sympy.Eq(sym_or_exp, size_symbol), free_symbol) + if solution is not None: + code.writeline(f"int64_t {size_symbol} = {base_name}[{dim}];") + expr = _rewrite_symbol_solution_for_int_codegen(solution[1]) + code.writeline(f"int64_t {free_symbol} = {cexpr(expr)};") + bound_vars.add(free_symbol) + if symbol_is_type( + free_symbol, (SymT.UNBACKED_INT, SymT.UNBACKED_FLOAT) + ): + self.unbacked_symbol_decls.add(str(free_symbol)) + self.maybe_emit_replacement_aliases(free_symbol, bound_vars) + return True + return False + return False + + if isinstance(value, sympy.Expr): + if not isinstance(value, sympy.Symbol) or value in bound_vars: + return + if symbol_is_type(value, (SymT.FLOAT, SymT.UNBACKED_FLOAT)): + decl = "double" + else: + decl = "int64_t" + code.writeline(f"{decl} {value} = {name};") + bound_vars.add(value) + if symbol_is_type(value, (SymT.UNBACKED_INT, SymT.UNBACKED_FLOAT)): + self.unbacked_symbol_decls.add(str(value)) + self.maybe_emit_replacement_aliases(value, bound_vars) + elif isinstance(value, ir.TensorBox): + for dim, size in enumerate(value.get_size()): + codegen_symbol(size, name, sizeof, dim, deferred_symbol_assignments) + for dim, stride in enumerate(value.get_stride()): + codegen_symbol(stride, name, strideof, dim, deferred_symbol_assignments) + elif isinstance( + value, (ir.TorchBindObject, ir.GeneratorState, ir.OpaqueObjectState) + ): + # Python-only inputs do not define C++ shape symbols. + pass + else: + raise AssertionError(f"Unknown value type: {type(value)}") + + def maybe_emit_replacement_aliases( # type: ignore[override] + self, + sym: sympy.Symbol, + bound_vars: OrderedSet[sympy.Symbol], + ) -> None: + 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)) + + def decl_type(s: sympy.Symbol) -> str: + if symbol_is_type(s, (SymT.FLOAT, SymT.UNBACKED_FLOAT)): + return "double" + return "int64_t" + + 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"{decl_type(src)} {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"{decl_type(tgt)} {tgt} = {sym};") + bound_vars.add(tgt) + + 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 + accessor = "sizes" if kind == "size" else "strides" + self.prefix.writeline(f"int64_t {sym} = {input_name}.{accessor}()[{dim}];") + bound_vars.add(sym) + self.maybe_emit_replacement_aliases(sym, bound_vars) + + def generate_input_output_runtime_checks(self): + """ + In debug_compile mode, we generate checks to ensure the dtype/shape/stride/device of each + real input/output tensor match ones provided at compile time via sample + input/output. + """ + + def gen_check(handle_kind, idx, name, tensor): + # Wrap AtenTensorHandle with ConstantHandle for cleaner utility function access + self.prefix.writeline_aot( + f"ConstantHandle {name} = ConstantHandle({handle_kind}[{idx}]);" + ) + self.prefix.writeline_aot(f"int32_t {name}_dtype;") + self.prefix.writeline_aot( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_dtype({name}, &{name}_dtype));" + ) + expected_dtype_name = DTYPE_TO_ATEN[tensor.dtype] + dtype_str = str(tensor.dtype).split(".")[-1] + self.prefix.splice_aot(f""" + int32_t {name}_expected_dtype = aoti_torch_dtype_{dtype_str}(); + if ({name}_expected_dtype != {name}_dtype) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: unmatched dtype, " + << "expected: " << {name}_expected_dtype << "({expected_dtype_name}), " + << "but got: " << {name}_dtype << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + self.prefix.writeline_aot(f"auto {name}_size = {name}.sizes();") + for dim_idx, d in enumerate(tensor.get_size()): + if isinstance(d, (int, sympy.Integer)): + self.prefix.splice_aot(f""" + if ({d} != {name}_size[{dim_idx}]) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: unmatched dim value at {dim_idx}, " + << "expected: {d}, " << "but got: " << {name}_size[{dim_idx}] + << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + else: + from torch.utils._sympy.value_ranges import bound_sympy + + sym_range = bound_sympy(d, V.graph.sizevars.shape_env.var_to_range) + if config.aot_inductor.check_lowerbound and not math.isinf( + sym_range.lower + ): + self.prefix.splice_aot(f""" + if ({name}_size[{dim_idx}] < {sym_range.lower}) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: dim value is too small at {dim_idx}, " + << "expected it to be >= {sym_range.lower}, " << "but got: " + << {name}_size[{dim_idx}] << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + if not math.isinf(sym_range.upper): + # Limit upper bound to max C long long value (2^63 - 1) + max_long_long = ctypes.c_longlong(2**63 - 1).value + upper_bound = min(sym_range.upper, max_long_long) + self.prefix.splice_aot(f""" + if ({name}_size[{dim_idx}] > {upper_bound}) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: dim value is too large at {dim_idx}, " + << "expected to be <= {upper_bound}, " << "but got: " + << {name}_size[{dim_idx}] << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + + self.prefix.writeline_aot(f"auto {name}_stride = {name}.strides();") + for stride_idx, s in enumerate(tensor.get_stride()): + if not isinstance(s, (int, sympy.Integer)): + continue + self.prefix.splice_aot(f""" + if ({s} != {name}_stride[{stride_idx}]) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: unmatched stride value at {stride_idx}, " + << "expected: {s}, " << "but got: " << {name}_stride[{stride_idx}] + << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + + # check input device type + if isinstance(tensor, ir.TensorBox): + tensor_device = tensor.get_device() + if tensor_device is not None: + expected_device_type = DEVICE_TO_INT.get(tensor_device.type) + if expected_device_type is not None: + self.prefix.writeline_aot(f"int32_t {name}_device_type;") + self.prefix.writeline_aot( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_device_type({name}, &{name}_device_type));" + ) + device_type_str = tensor_device.type + self.prefix.splice_aot(f""" + int32_t {name}_expected_device_type = {expected_device_type}; + if ({name}_expected_device_type != {name}_device_type) {{ + std::stringstream ss; + ss << "{handle_kind}[{idx}]: unmatched device type, " + << "expected: " << {name}_expected_device_type << "{expected_device_type}({device_type_str}), " + << "but got: " << {name}_device_type << "\\n"; + throw std::runtime_error(std::move(ss).str()); + }} + """) + + # Create a separate function for each input check to avoid "too big to optimize" error + for idx, (name, tensor) in enumerate(V.graph.graph_inputs.items()): + self.prefix.splice_aot(f""" + AOTI_NOINLINE static void check_input_{idx}( + AtenTensorHandle* input_handles + ) {{ + """) + with self.prefix.indent(): + gen_check("input_handles", idx, name, tensor) + self.prefix.writeline_aot("}") + + # force noinline to avoid any potential compilation slowdown due to aggressive + # inline done by the host compiler + self.prefix.splice_aot(""" + static bool _check_aoti_runtime_check_inputs_env() { + const static char* env_var_value = getenv("AOTI_RUNTIME_CHECK_INPUTS"); + const static bool result = env_var_value != nullptr && env_var_value[0] != '0'; + return result; + } + + AOTI_NOINLINE static void __check_inputs_outputs( + AtenTensorHandle* input_handles, + AtenTensorHandle* output_handles) { + if (!_check_aoti_runtime_check_inputs_env()){ + return; + } + """) + with self.prefix.indent(): + for idx in range(len(V.graph.graph_inputs)): + self.prefix.writeline_aot(f"check_input_{idx}(input_handles);") + self.prefix.writeline_aot("}") + + def _write_aoti_entry_point_signature(self): + """Emit the AOTI entry point: run_impl method and _const_run_impl.""" + self.codegen_additional_funcs() + + if V.graph.const_module: + # In dual-wrapper-mode, the const graph's JIT output is emitted separately, + # while its AOTI body is spliced below into the main AOTI source. + # Keep the const graph header out of the main output to avoid + # duplicate standalone header content. + if not V.graph.is_dual_wrapper_mode: + self.header.splice(V.graph.const_module.wrapper_code.header) + if V.graph.const_wrapper_code is None: + raise AssertionError("expected const_wrapper_code to be set") + self.prefix.splice_aot(V.graph.const_wrapper_code) + if V.graph.const_kernel_code is None: + raise AssertionError("expected const_kernel_code to be set") + self.kernel_declarations.splice(V.graph.const_kernel_code) + + if V.graph.is_const_graph: + self.prefix.splice_aot(f""" + void {self.aoti_model_class_name}::_const_run_impl( + std::vector& output_handles, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) {{ + """) + else: + if not config.aot_inductor.use_runtime_constant_folding: + # If we do not split the constant graph, we'll just create + # an empty implementation when wrapping the main module. + self.prefix.splice_aot(f""" + void {self.aoti_model_class_name}::_const_run_impl( + std::vector& output_handles, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) {{}} + + """) + + run_impl_proto = f""" + void {self.aoti_model_class_name}::run_impl( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) {{ + __check_inputs_outputs(input_handles, output_handles); + """ + + self.generate_input_output_runtime_checks() + self.prefix.splice_aot(run_impl_proto) + + def _write_jit_entry_point_signature(self): + """Emit the JIT entry point: inductor_entry_impl free function.""" + self.prefix.splice_jit(""" + void inductor_entry_impl( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed) + ) { + """) + + def _write_entry_point_signature(self): + """Emit the entry point function/method signature. + + AOTI: AOTInductorModel::run_impl with stream and proxy_executor params. + JIT: inductor_entry_impl free function. + Dual-wrapper-mode: both signatures, to their respective buffers. + """ + if V.graph.aot_mode: + self._write_aoti_entry_point_signature() + self._write_jit_entry_point_signature() + + def _write_input_preamble(self): + """Emit input stealing and (in JIT mode) GIL release.""" + # Weights are promoted in the JIT mode + jit_num_args = len(V.graph.graph_inputs) + len(V.graph.constants) + # AOTI const graphs enter through _const_run_impl and have no + # input_handles. Their JIT entry point still receives constants as + # appended input handles. + if not V.graph.is_const_graph: + aoti_num_args = len(V.graph.graph_inputs) + self.prefix.splice_aot( + f"auto inputs = steal_from_raw_handles_to_raii_handles(input_handles, {aoti_num_args});" + ) + # release GIL to support multiple instances inference (in different threads of the same process) + self.prefix.splice_jit("py::gil_scoped_release_simple release;") + self.prefix.splice_jit( + f"auto inputs = steal_from_raw_handles_to_raii_handles(input_handles, {jit_num_args});" + ) + + def _write_input_unpacking(self): + """Emit code to unpack graph inputs from the handles array.""" + inputs_len = len(V.graph.graph_inputs.keys()) + if inputs_len == 0: + return + for idx, input_key in enumerate(V.graph.graph_inputs.keys()): + # unwrap input tensor back to scalar + if isinstance(V.graph.graph_inputs[input_key], sympy.Expr): + from ..graph import may_get_constant_buffer_dtype + + dtype = may_get_constant_buffer_dtype( + V.graph.graph_inputs[input_key] # type: ignore[arg-type] + ) + if dtype is None: + raise AssertionError("Fails to get the dtype of the sympy.Expr") + self.codegen_tensor_item( + dtype, f"inputs[{idx}]", input_key, self.prefix + ) + else: + self.prefix.writeline(f"auto {input_key} = std::move(inputs[{idx}]);") + # debug printing for all input args to AOTI model + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.codegen_model_inputs_value_print( + input_args_to_print=[ + input_key + for input_key in V.graph.graph_inputs + if input_key.startswith("arg") + ] + ) + + def _write_constants_unpacking(self): + """Emit code to unpack constants — from constants_ (AOTI) or inputs (JIT).""" + inputs_len = len(V.graph.graph_inputs.keys()) + if not all( + isinstance(v, torch.Tensor) for v in list(V.graph.constants.values()) + ): + raise AssertionError("Expect all constants to be Tensor") + for idx, constants_key in enumerate(V.graph.constants.keys()): + # AOTI: weights live in constants_ owned by ConstantHandle; never std::move. + # JIT: weights are appended as inputs to the graph. + constants_idx = inputs_len + idx + self.prefix.writeline_aot( + f"[[maybe_unused]] auto& {constants_key} = constants_->at({idx});" + ) + self.prefix.writeline_jit( + f"[[maybe_unused]] auto {constants_key} = std::move(inputs[{constants_idx}]);" + ) + + def _write_entry_point_postamble(self): + """Emit AOTI-specific post-input setup (inputs.clear, kernels ref).""" + if not V.graph.is_const_graph: + self.prefix.writeline_aot("inputs.clear();") + self.prefix.writeline_aot( + "[[maybe_unused]] auto& kernels = static_cast(*this->kernels_.get());" + ) + + def write_wrapper_decl(self): + self._write_entry_point_signature() + with self.prefix.indent(): + self._codegen_entry_impl_prologue() + self._write_input_preamble() + self._write_input_unpacking() + self._write_constants_unpacking() + self.codegen_inputs() + self._write_entry_point_postamble() + + def codegen_tensor_dtype_var_decl(self, code: IndentedBuffer, name): + code.writeline(f"int32_t {name}_dtype;") + code.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_dtype({name}, &{name}_dtype));" + ) + + def codegen_input_size_var_decl(self, code: IndentedBuffer, name): + code.writeline(f"auto {name}_size = {name}.sizes();") + + def codegen_input_stride_var_decl(self, code: IndentedBuffer, name): + code.writeline(f"auto {name}_stride = {name}.strides();") + + def codegen_input_device_type_var_decl(self, code: IndentedBuffer, name): + code.writeline(f"int32_t {name}_device_type;") + code.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_get_device_type({name}, &{name}_device_type));" + ) + + def codegen_additional_funcs(self): + pass + + def codegen_initialized_kernel_decls(self): + # Tell compiler we need to link with the non-mangled symbols + for kernel in self.initialized_kernels.values(): + if not hasattr(kernel, "get_signature"): + raise AssertionError(f"{kernel} must have get_signature implemented") + signature = kernel.get_signature() + self.prefix.writeline(f'extern "C" {signature};') + + def codegen_model_kernels(self): + self.prefix.writeline("namespace {") + self.codegen_initialized_kernel_decls() + self.prefix.writeline( + "class AOTInductorModelKernels : public AOTInductorModelKernelsBase {" + ) + self.prefix.writeline(" public:") + declare_kernel = OrderedSet(self.src_to_kernel.values()) - OrderedSet( + self.initialized_kernels.keys() + ) + declare_kernel.update( + entry[0] for entry in self.user_defined_kernel_cache.values() + ) + if V.graph.const_module: + declare_kernel.update( + V.graph.const_module.wrapper_code.src_to_kernel.values() + ) + # CPU Triton kernels need a (kernel_fn, launcher_fn) pair, declared + # separately below; skip them in the default single-`void*` loop. + cpu_triton_names = self._cpu_triton_kernel_names + for kernel in sorted(declare_kernel): + if kernel in cpu_triton_names: + continue + self.prefix.writeline( + maybe_hipify_code_wrapper( + f" {self.device_codegen.cpp_kernel_type()} {kernel}{{nullptr}};" + ) + ) + for kernel in sorted(cpu_triton_names): + self.prefix.writeline(f" void* {kernel}_kernel_fn{{nullptr}};") + self.prefix.writeline( + f" torch::aot_inductor::CpuTritonLauncherFn " + f"{kernel}_launcher_fn{{nullptr}};" + ) + for name, kernel in self.initialized_kernels.items(): + if not hasattr(kernel, "get_signature"): + raise AssertionError(f"{kernel} must have get_signature implemented") + kernel_ptr = f"(*{name})" + signature = kernel.get_signature().replace(name, kernel_ptr) + self.prefix.writeline(f" {signature} = torch::aot_inductor::{name};") + self.prefix.writeline("};") + self.prefix.writeline("} // namespace\n\n") + + if config.aot_inductor.embed_kernel_binary: + self.prefix.writeline('extern "C" {') + for name in sorted(declare_kernel): + self.prefix.writeline( + f" extern const unsigned char __{name}_start[];" + ) + if torch.xpu.is_available(): + self.prefix.writeline( + f" extern const unsigned char __{name}_end[];" + ) + self.prefix.writeline("}") + + # MSVC string was longer than the limit of 16380 single-byte characters. + # https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2026 + MSVC_C2026_MAX_STRING_LENGTH = 16000 + + def codegen_write_arg_with_large_length_string( + self, + arg_name: str, + arg_str_val: str, + max_truncate_length: int = MSVC_C2026_MAX_STRING_LENGTH, + ): + def truncate_string(s: str, length: int) -> list[str]: + return [s[i : i + length] for i in range(0, len(s), length)] + + if len(arg_str_val) > max_truncate_length: + truncated_strs = truncate_string(arg_str_val, max_truncate_length) + self.prefix.writeline(f"{arg_name} =") + for truncate_str in truncated_strs: + self.prefix.writeline(f'R"({truncate_str})"') + self.prefix.writeline(";") + else: + self.prefix.writeline(f'{arg_name} = R"({arg_str_val})";') + + def codegen_model_constructor(self): + """ + // Generated code example + AOTInductorModel::AOTInductorModel() + : AOTInductorModelBase(4, 1) { + inputs_info_[0].name = "input0"; + inputs_info_[0].dtype = "torch.float16"; + ... + constants_info_[0].name = "L__self___weight"; + constants_info_[0].dtype = at::kFloat; + constants_info_[0].offset = 0; + constants_info_[0].data_size = 8192; + constants_info_[0].shape = {64, 32}; + constants_info_[0].stride = {32, 1}; + ... + outputs_info_[0].name = "output0"; + outputs_info_[0].dtype = "torch.float16"; + } + """ + + num_inputs = len(V.graph.graph_inputs) + num_outputs = len(V.graph.graph_outputs) + num_constants = len(V.graph.constants) + include_weights = ( + "true" + if config.aot_inductor.package_constants_in_so + and config.aot_inductor.package_constants_on_disk_format != "binary_blob" + else "false" + ) + self.prefix.splice(f""" + {self.aoti_model_class_name}::{self.aoti_model_class_name}(std::shared_ptr constants_map, + std::shared_ptr> constants_array, + const std::string& device_str, + std::optional cubin_dir) + : AOTInductorModelBase({num_inputs}, + {num_outputs}, + {num_constants}, + device_str, + std::move(cubin_dir), + {include_weights}) {{ + """) + + with self.prefix.indent(): + for idx, (name, inp) in enumerate(V.graph.graph_inputs.items()): + if isinstance(inp, sympy.Expr): + raise AssertionError(f"input {name=} cannot be symbolic") + self.write_input_output_info("inputs_info_", idx, name) + + all_cuda = all( + V.graph.get_original_value_of_constant(name).is_cuda + for name in V.graph.constants + if name not in V.graph.folded_constants + ) + for idx, name in enumerate(V.graph.constants.keys()): + tensor = V.graph.get_original_value_of_constant(name) + if not isinstance(tensor, torch.Tensor): + raise AssertionError( + f"expected constant {name} to be a Tensor, got {type(tensor)}" + ) + self.prefix.writeline(f"""constants_info_[{idx}].name = "{name}";""") + self.prefix.writeline( + f"constants_info_[{idx}].dtype = {self.codegen_dtype(tensor.dtype)};" + ) + # Mixed-device constants are only supported when the secondary device is CPU + if tensor.device.type != self.device and tensor.device.type != "cpu": + raise AssertionError( + f"Mixed-device constants are only supported when the secondary " + f"device is CPU. Model device is '{self.device}', but constant " + f"'{name}' is on device '{tensor.device}'." + ) + # device_index is not needed because it can be set at runtime + device_type, _ = self.codegen_device(tensor.device).split(", ") + self.prefix.writeline( + f"constants_info_[{idx}].device_type = {device_type};" + ) + self.prefix.writeline( + f"constants_info_[{idx}].offset = {tensor.storage_offset()};" + ) + + # If constants to serialize contain cpu tensors, we always align data_size it to 64. + # When loading the constants, the valid data will depends on the size + # not the data_size so there won't be correctness issue. + data_size = ( + torch.ops.mkldnn._nbytes(tensor) + if tensor.is_mkldnn + else tensor.untyped_storage().nbytes() + ) + self.prefix.writeline( + f"constants_info_[{idx}].data_size = {data_size if all_cuda else _align(data_size)};" + ) + + from_folded = "true" if name in V.graph.folded_constants else "false" + self.prefix.writeline( + f"constants_info_[{idx}].from_folded = {from_folded};" + ) + + if name in V.graph.folded_constants: + constant_type_str = "FoldedConstant" + elif name.startswith("_tensor_constant"): + constant_type_str = "TensorConstant" + elif any( + name == normalize_name(parameter_name) + for parameter_name in V.graph.named_parameters + ): + constant_type_str = "Parameter" + elif any( + name == normalize_name(buffer_name) + for buffer_name in V.graph.named_buffers + ): + constant_type_str = "Buffer" + else: + constant_type_str = "Unknown" + self.prefix.writeline( + f"constants_info_[{idx}].type = static_cast(torch::aot_inductor::ConstantType::{constant_type_str});" + ) + + size_str = ", ".join([str(s) for s in tensor.size()]) + self.prefix.writeline(f"constants_info_[{idx}].shape = {{{size_str}}};") + + stride_str = ", ".join([str(s) for s in tensor.stride()]) + self.prefix.writeline( + f"constants_info_[{idx}].stride = {{{stride_str}}};" + ) + self.prefix.writeline( + f"constants_info_[{idx}].layout = static_cast({self.codegen_layout(tensor.layout)});" + ) + + if tensor.is_mkldnn: + opaque_metadata_tensor = torch.ops.mkldnn._get_mkldnn_serialized_md( + tensor + ) + if opaque_metadata_tensor.dim() != 1: + raise AssertionError("Expect opaque_metadata_tensor to be 1-D") + + opaque_metadata_list = opaque_metadata_tensor.tolist() + opaque_metadata_str = self.codegen_shape_tuple(opaque_metadata_list) + self.prefix.writeline( + f"constants_info_[{idx}].opaque_metadata = {opaque_metadata_str};" + ) + if name in V.graph.dynamo_flat_name_to_original_fqn: + original_fqn = V.graph.dynamo_flat_name_to_original_fqn.get( + name, name + ) + elif name in V.graph.allocated_constant_name: + original_fqn = V.graph.allocated_constant_name[name] + else: + raise AssertionError("original_fqn must be set for constant") + self.prefix.writeline( + f"""constants_info_[{idx}].original_fqn = "{original_fqn}";""" + ) + self.prefix.writeline("update_constants_map(std::move(constants_map));") + self.prefix.writeline("update_constants_array(std::move(constants_array));") + + def escape_string(x): + return ( + x.replace("\\", "\\\\") + .replace('"', '\\"') + .replace("\n", "\\n") + .replace("\t", "\\t") + ) + + # Origin code: self.prefix.writeline(f'in_spec_ = R"({config.aot_inductor.serialized_in_spec})";') + # Fix msvc C2026 error via codegen_write_arg_with_large_length_string + self.codegen_write_arg_with_large_length_string( + arg_name="in_spec_", arg_str_val=config.aot_inductor.serialized_in_spec + ) + # Origin code: self.prefix.writeline(f'out_spec_ = R"({config.aot_inductor.serialized_out_spec})";') + # Fix msvc C2026 error via codegen_write_arg_with_large_length_string + self.codegen_write_arg_with_large_length_string( + arg_name="out_spec_", + arg_str_val=config.aot_inductor.serialized_out_spec, + ) + + for idx, output in enumerate(V.graph.graph_outputs): + if isinstance(output, sympy.Expr): + raise AssertionError(f"output {name=} cannot be symbolic") + name = f"output{idx}" + self.write_input_output_info("outputs_info_", idx, name) + + self.prefix.writeline( + "this->kernels_ = std::make_unique();" + ) + + self.prefix.writeline("}") + + def codegen_const_run_driver(self): + """ + // Generated code example + std::unordered_map AOTInductorModel::const_run_impl( + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor, + bool initialization + ) { + std::unordered_map folded_constants_map; + std::vector output_handles; + // build up output_handles over here. + _const_run_impl(output_handles, stream, proxy_executor); + // build up folded_constants_map + return folded_constants_map; + } + """ + + self.prefix.splice(f""" + std::unordered_map {self.aoti_model_class_name}::const_run_impl( + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor, + bool initialization + ) {{ + """) + if not config.aot_inductor.use_runtime_constant_folding: + self.prefix.splice(""" + if (!initialization) { + std::cerr << "[WARNING] Calling constant_folding in model, but compiled with config: " + << "aot_inductor.use_runtime_constant_folding=False\\n"; + } + return {}; + } + """) + return + + with self.prefix.indent(): + # This is a mapping to the index of constant folding graph's output + const_index_mapping: list[tuple[int, str] | None] = [None] * len( + V.graph.const_output_index + ) + for idx, (name, _) in enumerate(V.graph.constants.items()): + if name in V.graph.const_output_index: + const_index_mapping[V.graph.const_output_index[name]] = (idx, name) # type: ignore[call-overload] + if None in const_index_mapping: + raise AssertionError( + "Not all constant gets mapped for constant folding graph." + ) + + self.prefix.writeline(f""" + std::unordered_map folded_constants_map; + folded_constants_map.reserve({len(const_index_mapping)}); + std::vector output_handles({len(const_index_mapping)}); + """) + + self.prefix.splice(""" + // The below assignment of output_handles to constants is not used directly. + // It's only used to memo the correspondence of handle and constants. + """) + + for output_idx, (const_idx, _) in enumerate(const_index_mapping): # type: ignore[misc] + self.prefix.writeline( + f"output_handles[{output_idx}] = constants_->at({const_idx});" + ) + + self.prefix.writeline( + "_const_run_impl(output_handles, stream, proxy_executor);" + ) + + for output_idx, (_, const_name) in enumerate(const_index_mapping): # type: ignore[misc] + self.prefix.writeline( + f'folded_constants_map["{const_name}"] = output_handles[{output_idx}];' + ) + self.prefix.writeline("return folded_constants_map;") + + self.prefix.writeline("}") + + def generate(self, is_inference): + with dynamo_timed("CppWrapperCpu.generate", log_pt2_compile_event=True): + self.write_wrapper_decl() + return super().generate(is_inference) + + def _codegen_aoti_model_class(self): + """Emit AOTI model class, constructor, and const_run driver into self.prefix.""" + self.prefix.writeline("namespace torch::aot_inductor {") + self.codegen_model_kernels() + self.codegen_model_constructor() + self.codegen_const_run_driver() + self.prefix.writeline("} // namespace torch::aot_inductor") + self.prefix.writeline("using namespace torch::aot_inductor;") + + def finalize_prefix(self): + prior = self.prefix + + # Build AOTI model class into a temporary buffer (AOTI-only content). + # _codegen_aoti_model_class calls methods that write to self.prefix, + # so redirect self.prefix to the temporary buffer during the call. + aot_mode_decls = IndentedBuffer() + if V.graph.aot_mode and not V.graph.is_const_graph: + with self._target_buf("prefix", aot_mode_decls): + self._codegen_aoti_model_class() + elif not V.graph.is_const_graph and self.initialized_kernels: + # JIT cpp_wrapper: emit extern "C" decls for kernels (CUTLASS, + # ROCm CK) whose precompiled .so files are linked into the + # wrapper via extra_flags. + self.codegen_initialized_kernel_decls() + + # Reset self.prefix and write shared cache decls + CPU triton content. + self.prefix = make_codegen_buffer() + for dtype in self.used_cached_dtypes: + self.prefix.writeline(f"CACHE_TORCH_DTYPE({dtype});") + for device in self.used_cached_devices: + self.prefix.writeline(f"CACHE_TORCH_DEVICE({device});") + for layout in self.used_cached_layouts: + self.prefix.writeline(f"CACHE_TORCH_LAYOUT({layout});") + for memory_format in self.used_cached_memory_formats: + self.prefix.writeline(f"CACHE_TORCH_MEMORY_FORMAT({memory_format});") + + # Includes are needed whenever a kernel was *defined* (the model + # kernels class references `CpuTritonLauncherFn`); `call_` bodies + # only for kernels that were actually *called*. + if self._cpu_triton_kernel_names: + self._write_cpu_triton_runtime_includes(self.prefix) + if self._cpu_triton_call_wrappers: + for wrapper in self._cpu_triton_call_wrappers.values(): + self.prefix.writeline("\n") + wrapper.generate(self) + + # aot_mode_decls is AOTI-only; splice_aot routes correctly across + # all three modes (no-op on plain IndentedBuffer in pure-JIT). + self.prefix.splice_aot(aot_mode_decls) + self.prefix.splice(prior) + + @staticmethod + def _write_cpu_triton_runtime_includes(prefix: IndentedBuffer) -> None: + """One-time includes/guards needed by emitted CPU Triton wrappers.""" + prefix.writeline("// CPU AOTI Triton kernel wrappers") + prefix.writeline("#ifdef _WIN32") + prefix.writeline( + '#error "CPU AOTI Triton kernels are not supported on Windows"' + ) + prefix.writeline("#endif") + prefix.writeline("#include ") + prefix.writeline( + "#include " + ) + + @staticmethod + def _stringify_cpu_triton_call_arg(arg: Any) -> str: + """Render a Triton kernel call argument as a C++ expression.""" + if isinstance(arg, str): + return arg + if isinstance(arg, bool): + return "true" if arg else "false" + if isinstance(arg, (int, float, SymbolicCallArg)): + return str(arg) + return cexpr(V.graph.sizevars.simplify(arg)) + + def _define_kernel_helper( + self, + kernel_name: str, + kernel_body: str, + metadata: str | None = None, + gpu: bool = False, + cpp_definition: str | None = None, + ): + # Misnomer: `gpu` actually means "is this a Triton kernel?" + if gpu: + # Register as a CPU Triton kernel and let the autotune block + # compile it; the C++ wrapper is emitted later in finalize_prefix. + self._cpu_triton_kernel_names.add(kernel_name) + if config.triton.autotune_at_compile_time: + PythonWrapperCodegen._define_kernel_helper( + self, kernel_name, kernel_body, metadata, gpu, cpp_definition + ) + return + if cpp_definition is not None: + self.needs_vec_isa = True + self.header.splice(cpp_definition) + self.kernel_declarations.splice(f"\n{kernel_body}\n") + else: + self.header.splice(f"\n{kernel_body}\n") + + def codegen_scalar_to_tensor(self, output: str): + name = f"scalar_to_tensor_{next(self.scalar_to_tensor_id)}" + self.wrapper_call.writeline( + f"RAIIAtenTensorHandle {name} = scalar_to_tensor_handle({output});" + ) + return name + + def codegen_tensor_item( + self, dtype: torch.dtype, tensor: str, scalar: str, indented_buffer=None + ): + dtype_str = str(dtype).split(".")[-1] + writer = indented_buffer or self + + if dtype == torch.float16 or dtype == torch.bfloat16: + scalar_tmp = f"{scalar}_tmp" + writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar_tmp};") + writer.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar_tmp}));" + ) + writer.writeline(f"float {scalar} = float({scalar_tmp});") + else: + writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar};") + writer.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar}));" + ) + + def generate_return(self, output_refs: list[str]): + cst_names = V.graph.constants.keys() + output2idx: dict[str, int] = {} + + # If any output ref represents an rvalue tensor, materialize it to an lvalue + # RAIIAtenTensorHandle first. This prevents situations where the code for the + # rvalue tensor references tensor handles whose contents are modified below. + output_refs = [ + self.create_tmp_raii_handle_var_if_needed(o, self.wrapper_call) + for o in output_refs + ] + + for idx, output in enumerate(output_refs): + if output == "nullptr": + continue + + is_constant_buffer = output in cst_names + output_buffer = V.graph.graph_outputs[idx] + if isinstance(output_buffer, ir.BaseView): + output_storage = output_buffer.unwrap_view() + if not isinstance(output_storage, (ir.BaseView, ir.MutableBox)): + raise AssertionError( + f"expected output_storage to be BaseView or MutableBox, " + f"got {type(output_storage)}" + ) + if isinstance(output_storage.data, ir.ConstantBuffer): + is_constant_buffer = True + + if isinstance(output_buffer, ir.ShapeAsConstantBuffer): + # Need to wrap scalar into tensor as the main function returns a vector of tensors + output_tensor = self.codegen_scalar_to_tensor(output) + self.wrapper_call.writeline( + f"output_handles[{idx}] = {output_tensor}.release();" + ) + continue + + if is_constant_buffer: + # See NOTE(return_constant) above. + self.wrapper_call.writeline( + "AOTI_TORCH_ERROR_CODE_CHECK(" + f"aoti_torch_clone({output}, &output_handles[{idx}]));" + ) + else: + if output in output2idx: + src_idx = output2idx[output] + self.wrapper_call.writeline( + f"output_handles[{idx}] = output_handles[{src_idx}];" + ) + else: + self.wrapper_call.writeline( + f"output_handles[{idx}] = {output}.release();" + ) + + if output not in output2idx: + output2idx[output] = idx + + def _codegen_entry_impl_prologue(self): + """Hook for subclasses to emit code at the top of inductor_entry_impl, + before the GIL is released. Default no-op.""" + if config.triton.debug_sync_graph: + self.generate_debug_sync(self.prefix) + + def generate_before_suffix(self, result): + # Close the entry function. In dual-wrapper-mode `result` is the JIT side; + # the AOTI side close is emitted by _generate_end_aoti. + if V.graph.aot_mode and not V.graph.is_dual_wrapper_mode: + entry = "_const_run_impl" if V.graph.is_const_graph else "run_impl" + result.writeline(f"}} // {self.aoti_model_class_name}::{entry}") + else: + result.writeline("} // inductor_entry_impl") + + def _generate_end_aoti(self, result): + """Close AOTI namespace. In dual-wrapper-mode, also assemble the + AOTI source string from `.aot` buffers into self._aot_output; the + input `result` is the JIT side and is left untouched in that case. + """ + if V.graph.is_dual_wrapper_mode: + if not isinstance(self.header, DualIndentedBuffer): + raise AssertionError( + f"expected DualIndentedBuffer, got {type(self.header)}" + ) + if not isinstance(self.prefix, DualIndentedBuffer): + raise AssertionError( + f"expected DualIndentedBuffer, got {type(self.prefix)}" + ) + if not isinstance(self.wrapper_call, DualIndentedBuffer): + raise AssertionError( + f"expected DualIndentedBuffer, got {type(self.wrapper_call)}" + ) + aot_result = IndentedBuffer() + aot_result.splice(self.header.aot) + aot_result.splice(self.prefix.aot) + with aot_result.indent(): + aot_result.splice(self.wrapper_call.aot) + entry = "_const_run_impl" if V.graph.is_const_graph else "run_impl" + aot_result.writeline(f"}} // {self.aoti_model_class_name}::{entry}") + aot_result.splice(self.suffix) + if not V.graph.is_const_graph: + aot_result.writeline("} // namespace torch::aot_inductor\n\n\n") + self._aot_output = aot_result.getvalue() + elif not V.graph.is_const_graph: + result.writeline("} // namespace torch::aot_inductor\n\n\n") + + def _generate_end_jit(self, result): + """Close JIT C++ block and emit Python wrapper for loading/calling.""" + if config.cpp_wrapper_build_separate: + # Close the wrapper code block, then write any kernel definitions. + result.splice('"""\n)') + if self.kernel_declarations: + result.splice('\nkernel_src = (\nr"""') + result.splice(self.kernel_declarations.getvalue()) + result.splice('"""\n)') + else: + result.splice(""" + kernel_src = '' + """) + else: + # Merge main code and kernel code + result.splice(self.kernel_declarations.getvalue()) + self.kernel_declarations.clear() + # Close the wrapper code block + result.splice('"""\n)') + + if config.cpp_wrapper_build_separate: + kernel_code = "kernel_src" + needs_vec_isa = "False" + kernel_needs_vec_isa = str(self.needs_vec_isa) + else: + kernel_code = "None" + needs_vec_isa = str(self.needs_vec_isa) + kernel_needs_vec_isa = "None" + # Link any precompiled kernel .so files (CUTLASS, ROCm CK) into the + # wrapper. The .so files are built without -Wl,-soname, so passing + # their absolute paths positionally to the linker encodes them as + # absolute DT_NEEDED entries that resolve at module load (same + # mechanism HalideCodeCache uses for its standalone runtime). + extra_flags_repr = repr(tuple(self.external_kernel_libs)) + # Cpp entry function for JIT with cpp wrapper + result.splice(f""" + inductor_entry = CppWrapperCodeCache.load_pybinding( + argtypes=["std::vector"], + main_code=cpp_wrapper_src, + device_type="{self.device}", + needs_vec_isa={needs_vec_isa}, + kernel_needs_vec_isa={kernel_needs_vec_isa}, + num_outputs={len(V.graph.graph_outputs)}, + kernel_code={kernel_code}, + extra_flags={extra_flags_repr}, + ) + """) + + input_python_indices = [ + idx + for idx, value in enumerate(V.graph.graph_inputs.values()) + if isinstance( + value, + (ir.TorchBindObject, ir.GeneratorState, ir.OpaqueObjectState), + ) + ] + python_only_input_indices = ( + "set()" + if not input_python_indices + else "{" + ", ".join(map(str, input_python_indices)) + "}" + ) + wrapper_body = f""" + python_only_input_indices = {python_only_input_indices} + input_tensors = [] + input_handle_positions = [] + # Preserve graph input slots: Python-only inputs stay None + # and are unpacked as nullptrs by the JIT cpp wrapper. + input_handles = [None] * len(args) + for idx, arg in enumerate(args): + if idx in python_only_input_indices: + continue + input_handle_positions.append(idx) + input_tensors.append( + arg if isinstance(arg, torch.Tensor) else torch.tensor(arg, device='cpu') + ) + """ + if V.graph.constants: + # Append constants to the input args for cpp wrapper. + # Python wrapper directly gets the value inside the wrapper call + # as a global variable passed when calling exec(code, mod.__dict__, mod.__dict__). + # For cpp wrapper, we need to pass this python value to the inductor_entry_impl function explicitly. + if not all( + isinstance(v, torch.Tensor) for v in list(V.graph.constants.values()) + ): + raise AssertionError("Expect all constants to be Tensor") + constants_str = f"[{', '.join(V.graph.constants.keys())}]" + wrapper_body += f""" + constants_tensor = {constants_str} + constants_start_idx = len(input_handles) + input_handles.extend([None] * len(constants_tensor)) + input_handle_positions.extend( + range(constants_start_idx, constants_start_idx + len(constants_tensor)) + ) + input_tensors.extend(constants_tensor) + """ + # Convert vector of at::Tensor to vector of AtenTensorHandle. + # If we pass at::Tensor, the compilation will be too slow. + wrapper_body += """ + packed_input_handles = torch._C._aoti.unsafe_alloc_void_ptrs_from_tensors(input_tensors) + for idx, handle in zip(input_handle_positions, packed_input_handles): + input_handles[idx] = handle + """ + # Release the inputs for memory reuse. + wrapper_body += """ + args.clear() + del input_handle_positions + del packed_input_handles + del input_tensors + """ + + # unwrap output tensor back to python scalar + if all(x for x in self.output_is_tensor.values()): + # If no ShapeAsConstantBuffer in the output, directly return the output as tensors + outputs_str = "output_tensors" + else: + outputs = [ + ( + f"output_tensors[{i}]" + if self.output_is_tensor[i] + else f"output_tensors[{i}].item()" + ) + for i in range(len(V.graph.graph_outputs)) + ] + outputs_str = f"[{', '.join(outputs)}]" + wrapper_body += f""" + output_handles = f(input_handles) + output_tensors = torch._C._aoti.alloc_tensors_by_stealing_from_void_ptrs(output_handles) + return {outputs_str} + """ + + # Wrap the func to support setting result._boxed_call = True + result.splice(f""" + def _wrap_func(f): + def g(args): + {wrapper_body} + return g + + call = _wrap_func(inductor_entry) + """) + + def generate_end(self, result): + """Generates the end of the code block, and any code needed to call it.""" + if V.graph.aot_mode: + self._generate_end_aoti(result) + else: + self._generate_end_jit(result) + + @staticmethod + def get_c_shim_func_name(kernel: str, device: str) -> str: + if kernel.startswith("aoti_torch_"): + return kernel + + if "::" not in kernel: + raise AssertionError( + "Cpp kernel name: " + kernel + " does not contain '::'" + ) + kernel_tokens = kernel.split("::") + kernel_suffix = kernel_tokens[-1] + if kernel_suffix == "call": + kernel_suffix = kernel_tokens[-2] + + shim_fn = f"aoti_torch_{device}_{kernel_suffix}" + return shim_fn + + def generate_c_shim_extern_kernel_call( + self, + kernel: str, + args: list[str], + device: str, + *, + debug_args: list[str] | None = None, + stack_traces: OrderedSet[str] | None = None, + ) -> None: + """debug_args kwarg allows CppWrapperCpuArrayRef to pass in wrapped arguments in + place of args while preserving debug printer output.""" + # We can do this unconditionally, since we cache this call. + self.add_device_include(device) + + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + debug_args if debug_args is not None else args, kernel, None, None, "extern" + ) + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + enable_kernel_context_guard = ( + enable_kernel_profile and config.cpp.enable_kernel_context_guard + ) + with debug_printer_manager: + shim_fn = self.get_c_shim_func_name(kernel, device) + shim_fn_codes = [ + f"AOTI_TORCH_ERROR_CODE_CHECK({shim_fn}({', '.join(args)}));" + ] + if enable_kernel_profile: + call_code = shim_fn_codes[0] + shim_fn_codes = ["{"] + if enable_kernel_context_guard: + stack_trace_str = 'R"(' + if stack_traces: + for stack_trace in stack_traces: + for line in stack_trace.split("\n"): + stack_trace_str += f"\n{line}" + stack_trace_str += "\n" + stack_trace_str += ')"' + shim_fn_codes.append( + f"""KernelContextGuard _ctx("{shim_fn}", {stack_trace_str});""" + ) + shim_fn_codes.extend( + [ + f"""RAIIAtenRecordFunctionHandle record_{shim_fn}_("{shim_fn}", nullptr);""", + call_code, + "}", + ] + ) + self.writelines(shim_fn_codes) + + def generate_c_shim_extern_kernel_alloc( + self, extern_kernel: ir.ExternKernelAlloc, args: list[str] + ) -> None: + # registered output buffer name + name = extern_kernel.name + output_handle_name = f"{name}_handle" + is_inplace = ( + isinstance(extern_kernel.op_overload, torch._ops.OpOverload) + and torch.Tag.inplace_view in extern_kernel.op_overload.tags + ) + + if not is_inplace: + self.writeline(f"AtenTensorHandle {output_handle_name};") + args = [*args, f"&{output_handle_name}"] + + device = d.type if (d := extern_kernel.get_device()) else self.device + + self.generate_c_shim_extern_kernel_call( + extern_kernel.get_kernel_name(), args, device + ) + + if extern_kernel.python_kernel_name in ( + "torch.ops._c10d_functional.all_reduce_.default", + "torch.ops._c10d_functional.wait_tensor.default", + ): + # all_reduce_ is an inplace op and its returned tensor is not used anywhere. + # wait_tensor returns its input without any modification and the returned tensor is not used anywhere. + # In both cases, we can immediately delete the returned AtenTensorHandle to reduce its lifetime. + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_delete_tensor_object({output_handle_name}));" + ) + elif not is_inplace: + self.writeline(f"RAIIAtenTensorHandle {name}({output_handle_name});") + + def _generate_extern_kernel_alloc_helper(self, extern_kernel, args): + if getattr(extern_kernel, "outputs", None): + # ir.ExternKernelAlloc may have outputs if it returns a tuple + self.generate_c_shim_fallback_kernel(extern_kernel, args) + else: + self.generate_c_shim_extern_kernel_alloc(extern_kernel, args) + + def generate_c_shim_fallback_kernel( + self, fallback_kernel: ir.FallbackKernel, args: list[str] + ) -> None: + output_args = [] + output_raii_handles = [] + output_name_base = fallback_kernel.get_name() + for idx, output in enumerate(fallback_kernel.outputs): + if isinstance(output, ir.MultiOutput): + # TODO: handle integer output (e.g., as in attention) + name = f"{output.get_name()}" + output_handle_name = f"{name}_handle" + if output.indices: + if output.indices[0][1] != idx: + raise AssertionError( + f"expected {output.indices[0][1]=} == {idx=} for {output_name_base=}" + ) + self.writeline(f"AtenTensorHandle {output_handle_name};") + output_args.append(f"&{output_handle_name}") + output_raii_handles.append( + f"RAIIAtenTensorHandle {name}({output_handle_name});" + ) + elif isinstance(output, int): + output_name = f"{output_name_base}_{idx}" + self.writeline(f"int64_t {output_name} = {output};") + output_args.append(f"&{output_name}") + elif isinstance(output, sympy.Expr): + output_name = f"{output_name_base}_{idx}" + self.writeline(f"auto {output_name} = {cexpr(output)};") + output_args.append(f"&{output_name}") + elif output is None: + output_args.append("nullptr") + else: + raise NotImplementedError(f"unsupported type of {output=}") + args = args + output_args + device = d.type if (d := fallback_kernel.get_device()) else self.device + + self.generate_c_shim_extern_kernel_call( + fallback_kernel.cpp_kernel_name, # type: ignore[arg-type] + args, + device, + ) + for raii_handle in output_raii_handles: + self.writeline(raii_handle) + + 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: + if out_view: + out_name = f"{out}_as_strided" + self.writeline(f"auto {out_name} = {out_view};") + args.insert(0, out_name) + else: + args.insert(0, out) + + self.generate_c_shim_extern_kernel_call( + kernel, args, device, stack_traces=stack_traces + ) + + def _get_scatter_reduce_enum(self, reduce): + # Follow aten/src/ATen/native/ReductionType.h:get_operator_enum + get_operator_enum = {"add": "sum", "multiply": "prod"} + if reduce in get_operator_enum: + reduce = get_operator_enum[reduce] + + return reduce + + def _generate_scatter_fallback_args(self, inputs: Sequence[Any]) -> list[str]: + return [str(x) for x in inputs] + + def _generate_scatter_fallback( + self, + output, + inputs, + cpp_kernel_name, + python_kernel_name, + src_is_tensor, + reduce, + kwargs, + device, + ): + reduce = self._get_scatter_reduce_enum(reduce) + + # call the ABI shim function instead of the ATen one + self.add_device_include(device) + cpp_kernel_name = self.get_c_shim_func_name(cpp_kernel_name, device) + # TODO: consider remove "_out" and add missing inplace variants to fallback_ops.py + cpp_kernel_name = cpp_kernel_name.replace("__", "_") + "_out" + # str(output) ensures that CppWrapperCpuArrayRef borrows the output tensor + args_wrapped = self._generate_scatter_fallback_args((str(output), *inputs)) + # Wrap in AOTI_TORCH_ERROR_CODE_CHECK so a shim failure + # surfaces instead of being silently swallowed. + line = f"{cpp_kernel_name}({','.join(args_wrapped)}" + + if python_kernel_name.startswith("aten.scatter_reduce"): + line += f", {','.join(kwargs)}" + elif src_is_tensor: + if reduce: + line += f", {V.graph.wrapper_code.val_to_arg_str(reduce)}" + elif reduce is not None: + raise AssertionError( + "Expect reduce to be None for aten.scatter_ with scalar src" + ) + line += ")" + self.writeline(f"AOTI_TORCH_ERROR_CODE_CHECK({line});") + + def _generate_index_put_fallback(self, kernel, x, indices, values, accumulate): + # TODO: update aoti_torch_index_put_out in ir.py to use autogen out version + # See the comment in codegen_reinterpret_view about why having something like + # RAIIAtenTensorHandle(tmp_tensor_handle_2) in a tmp array can cause the corresponding + # tensor prematurely deallocated, thus the temporary array trick here. + indices_str = self._generate_temporary_array_pointer( + "AtenTensorHandle", indices + ) + args = [ + x, + indices_str, + str(len(indices)), + values, + accumulate, + ] + args.insert(0, x) # set x as the output tensor, this fallback mutates x. + # Wrap in AOTI_TORCH_ERROR_CODE_CHECK so a shim failure surfaces instead + # of being silently swallowed. + self.writeline(f"AOTI_TORCH_ERROR_CODE_CHECK({kernel}({', '.join(args)}));") + + def add_benchmark_harness(self, output): + if V.graph.aot_mode: + return + super().add_benchmark_harness(output) + + def _extract_divisors_from_expr( + self, expr: sympy.Expr + ) -> list[tuple[sympy.Expr, str]]: + """ + Walk the sympy expression and extract all divisors/modulos from + FloorDiv, CleanDiv, Mod, and ModularIndexing nodes. + + Returns a list of (divisor_expr, operation_name) tuples for divisors + that are not constant positive integers (which cannot be zero). + """ + divisors: list[tuple[sympy.Expr, str]] = [] + seen: OrderedSet[str] = OrderedSet() + + def is_constant_nonzero(e: sympy.Expr) -> bool: + """Check if expression is a constant that cannot be zero.""" + if isinstance(e, sympy.Integer): + return int(e) != 0 + if isinstance(e, sympy.Number): + return float(e) != 0 + return False + + def maybe_add_divisor(divisor: sympy.Expr, op_name: str) -> None: + """Add divisor to list if it could potentially be zero.""" + if not is_constant_nonzero(divisor): + key = str(divisor) + if key not in seen: + seen.add(key) + divisors.append((divisor, op_name)) + + def walk(e: sympy.Expr) -> None: + if isinstance(e, (FloorDiv, CleanDiv)): + _, div = e.args + maybe_add_divisor(div, "floor division") + elif isinstance(e, Mod): + _, mod = e.args + maybe_add_divisor(mod, "modulo") + elif isinstance(e, ModularIndexing): + _, div, mod = e.args + maybe_add_divisor(div, "modular indexing division") + maybe_add_divisor(mod, "modular indexing modulo") + + # Recurse into arguments + if hasattr(e, "args"): + for arg in e.args: + if isinstance(arg, sympy.Expr): + walk(arg) + + walk(expr) + return divisors + + def codegen_cpp_sizevar(self, x: sympy.Expr, *, simplify: bool = True) -> str: + maybe_simplified_x = V.graph.sizevars.simplify(x) if simplify else x + # In AOT mode, emit runtime checks for potential division/modulo by zero + # to prevent SIGFPE crashes when symbolic tensor shapes can be 0. + if V.graph.aot_mode: + for divisor, op_name in self._extract_divisors_from_expr( + maybe_simplified_x + ): + self.write_assert_div_by_zero(cexpr(divisor), op_name) + return cexpr(maybe_simplified_x) + + 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). + + Uses writeline_aot so the check is routed to the AOTI side only in + dual-wrapper mode; on plain buffers writeline_aot has the expected + single-stream behavior (AotOnlyBuffer delegates to writeline, plain + IndentedBuffer is a no-op). + """ + code.writeline_aot( + f'AOTI_TORCH_CHECK({divisor_str} != 0, "Integer {op_name} by zero");' + ) + + def codegen_sizevar(self, x: sympy.Expr) -> str: + return self.codegen_cpp_sizevar(x) + + def codegen_tuple_access(self, basename: str, name: str, index: str) -> str: + # in the abi_compatible mode, outputs are returned via arguments + return name + + def codegen_shape_tuple(self, shape: Sequence[sympy.Expr]) -> str: + parts = [*map(self.codegen_sizevar, shape)] + if len(parts) == 0: + return "{}" + if len(parts) == 1: + return f"{{{parts[0]}, }}" + return f"{{{', '.join(parts)}}}" + + 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] + self.writeline(f"int64_t {sym} = {cexpr(expr)};") + + def _generate_symbolic_call_arg_helper( + self, arg: SymbolicCallArg, graph: GraphLowering + ) -> None: + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + if enable_kernel_profile or (arg.inner, graph) not in self.kernel_numel_expr: + # When enable_kernel_profile is on, each kernel call is wrapped in + # its own {} scope block, so we must redeclare the variable each + # time since prior declarations are no longer visible. + self.kernel_numel_expr.add((arg.inner, graph)) + self.writeline(f"int64_t {arg.inner} = {cexpr(arg.inner_expr)};") + else: + self.writeline(f"{arg.inner} = {cexpr(arg.inner_expr)};") + + def _codegen_dynamic_scalar(self, node): + (data,) = (t.codegen_reference() for t in node.inputs) + self.codegen_tensor_item(node.inputs[0].get_dtype(), data, f"{node.sym}_raw") + + if len(node.keypath) == 0: + self.writeline(f"auto {node.sym} = {node.sym}_raw;") + elif len(node.keypath) == 1 and isinstance(node.keypath[0], ConvertIntKey): + self.writeline(f"int64_t {node.sym} = {node.sym}_raw ? 1 : 0;") + elif len(node.keypath) == 1 and isinstance(node.keypath[0], DivideByKey): + # TODO: assert divisibility here + self.writeline( + f"int64_t {node.sym} = {node.sym}_raw / {node.keypath[0].divisor};" + ) + else: + raise AssertionError(f"unrecognized keypath {node.keypath}") + + # record in unbacked_symbol_decls so we won't generate a declaration of the symbol again + self.unbacked_symbol_decls.add(str(node.sym)) + + def codegen_dynamic_select_index(self, node, clamp): + index_cpp_str = self.val_to_arg_str_for_prim_type(node.index, int) + size_cpp_str = self.val_to_arg_str_for_prim_type(node.size, int) + + # codegen index + sym = node.unbacked_offset_symbol + index_str = ( + f"{index_cpp_str} < 0 ? {index_cpp_str} + " + f"{self.val_to_arg_str_for_prim_type(node.size, int)}: {index_cpp_str}" + ) + self.writeline(f"auto {sym}_index = {index_str};") + index_str_clamped = ( + f"{sym}_index < 0 ? 0 : ({sym}_index > {size_cpp_str} ? {size_cpp_str} : {sym}_index)" + if clamp + else f"{sym}_index" + ) + self.writeline(f"auto {sym}_index_clamped = {index_str_clamped};") + self.writeline( + f"auto {sym} = {self.val_to_arg_str_for_prim_type(node.base_offset, int)} + " + f"{self.val_to_arg_str_for_prim_type(node.base_dim_stride, int)} * {sym}_index_clamped;" + ) + # record in unbacked_symbol_decls so we won't generate a declaration of the symbol again + self.unbacked_symbol_decls.add(str(sym)) + + def codegen_dynamic_slice_size(self, node): + start_cpp_str = self.val_to_arg_str_for_prim_type(node.start, int) + end_cpp_str = self.val_to_arg_str_for_prim_type(node.end, int) + size_cpp_str = self.val_to_arg_str_for_prim_type(node.size, int) + step_cpp_str = self.val_to_arg_str_for_prim_type(node.step, int) + sym = node.unbacked_size_symbol + + def codegen_clamp(index_str, start=True): + suf = "st" if start else "en" + index_ = f"{sym}_{suf}_index" + self.writeline( + f"int64_t {index_} = {index_str} < 0 ? {index_str} + {size_cpp_str} : {index_str};" + ) + self.writeline( + f"int64_t {sym}_{suf}_cl = {index_} < 0 ? 0 : ({index_} > {size_cpp_str} ? {size_cpp_str} : {index_});" + ) + + codegen_clamp(start_cpp_str, start=True) + codegen_clamp(end_cpp_str, start=False) + if node.step == 1: + step_str = f"{sym}_en_cl - {sym}_st_cl" + else: + step_str = ( + f"({sym}_en_cl - {sym}_st_cl + {step_cpp_str} - 1) / {step_cpp_str}" + ) + self.writeline(f"int64_t {sym}_with_step = {step_str};") + self.writeline(f"int64_t {sym} = {sym}_with_step < 0 ? 0 : {sym}_with_step;") + self.unbacked_symbol_decls.add(str(sym)) + + def make_buffer_free(self, buffer): + return ( + "" + if isinstance(buffer.get_output_spec(), ir.MultiOutputLayout) + or isinstance(buffer, ir.TMADescriptor) + else f"{buffer.get_name()}.reset();" + ) + + def make_free_by_names(self, names_to_del: list[str]): + return " ".join(f"{name}.reset();" for name in names_to_del) + + def codegen_exact_buffer_reuse(self, old_name: str, new_name: str, del_line: str): + return f"auto {new_name} = std::move({old_name}); // reuse" + + def generate_debug_sync(self, buffer): + pass + + def generate_profiler_mark_wrapper_call(self, stack): + self.wrapper_call.writeline( + 'RAIIAtenRecordFunctionHandle record_inductor_wrapper_call_("inductor_wrapper_call", nullptr);' + ) + + def generate_start_graph(self): + pass + + def generate_end_graph(self): + pass + + def generate_inf_and_nan_checker(self, nodes): + for buf in nodes.get_names(): + # TODO: Add buf name directly into check_inf_and_nan. + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_check_inf_and_nan({buf}));" + ) + + def codegen_input_nan_asserts(self) -> None: + self.wrapper_call.writeline("// make sure graph inputs are not nan/inf") + for name, buf in self.get_graph_inputs().items(): + if isinstance(buf, (sympy.Expr, ir.TorchBindObject)): + continue + self.wrapper_call.writeline( + f'AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_check_inf_and_nan("{name}", {name}));' + ) + + def _codegen_assert_size_stride( + self, + code: IndentedBuffer, + name: str, + size: str, + stride: str, + op_name: str, + dtype: torch.dtype | None = None, + ) -> None: + if V.graph.aot_mode and V.graph.is_const_graph: + return + dtype_args = ( + f', {self.codegen_dtype(dtype)}, "{dtype}"' if dtype is not None else "" + ) + stmt = f'assert_size_stride({name}, {size}, {stride}, "{op_name}"{dtype_args});' + if V.graph.aot_mode: + guarded = f"if (_check_aoti_runtime_check_inputs_env()) {{ {stmt} }}" + if V.graph.is_dual_wrapper_mode: + # _check_aoti_runtime_check_inputs_env() is AOTI-only; the JIT + # side gets the plain assert. + code.writeline_jit(stmt) + code.writeline_aot(guarded) + else: + code.writeline(guarded) + else: + code.writeline(stmt) + + def _codegen_assert_size_stride_grouped( + self, code: IndentedBuffer, asserts: list[tuple[str, str, str]], op_name: str + ) -> None: + for name, size, stride in asserts: + self._codegen_assert_size_stride(code, name, size, stride, op_name) + + def codegen_device(self, device): + if device.type not in DEVICE_TO_ATEN: + raise AssertionError(device.type + " not found in DEVICE_TO_ATEN") + device_str = DEVICE_TO_ATEN[device.type][5:].lower() # remove "at::k" + self.used_cached_devices.add(device_str) + return f"cached_torch_device_type_{device_str}, {device.index or 0}" + + def codegen_device_idx(self, device, device_id): + device_id = device_id.strip() + if not V.graph.aot_mode: + return device_id + + if device.type == V.graph.device_type and device.index is not None: + # The primary compile-time device is relocatable via device_index at load. + # Other explicit device indices must stay intact for cross-device copies. + primary_device_idx = next(iter(V.graph.device_idxs), None) + if primary_device_idx is not None and device.index != primary_device_idx: + return device_id + + return "this->device_idx_" + + def codegen_dtype(self, dtype): + dtype_str = str(dtype).split(".")[-1] + self.used_cached_dtypes.add(dtype_str) + return f"cached_torch_dtype_{dtype_str}" + + def codegen_layout(self, layout): + layout_str = str(layout).split(".")[-1] + self.used_cached_layouts.add(layout_str) + return f"cached_torch_layout_{layout_str}" + + def codegen_memory_format(self, memory_format): + memory_format_str = str(memory_format).split(".")[-1] + self.used_cached_memory_formats.add(memory_format_str) + return f"cached_torch_memory_format_{memory_format_str}" + + def codegen_int_array_var( + self, + int_array: str, + writeline: Callable[..., None], + known_statically=False, + graph=None, # for per-graph caching + ) -> str: + # Use id(graph) for caching to avoid circular references + # Bound methods have transient IDs, so we use the ID of the bound object instead. + writeline_id = ( + id(writeline.__self__) if hasattr(writeline, "__self__") else id(writeline) + ) + cache_key = ( + int_array, + writeline_id, + known_statically, + id(graph) if graph else None, + ) + if cache_key not in self.codegen_int_array_var_cache: + self.codegen_int_array_var_cache[cache_key] = ( + self._codegen_int_array_var_impl(int_array, writeline, known_statically) + ) + + return self.codegen_int_array_var_cache[cache_key] + + def _codegen_int_array_var_impl( + self, + int_array: str, + writeline: Callable[..., None], + known_statically: bool, + ) -> str: + # Used for size/stride declaration + # + # Because the memory planning is done in two passes (see the implementation + # of self.generate), the writeline behavior is different in the two passes. + # As a result, the emitted int array declarations may appear in a later + # position of the generated code, so the second pass codegen should not + # reuse int array declarations generated in the first pass. + # This is why writeline needs to explicitly passed in as a parameter. + var = f"int_array_{next(self.int_array_id)}" + ctype = "int64_t" + if int_array == "{}": + # An array of unknown bound cannot be initialized with {}. + if known_statically: + if config.cpp.use_constexpr_for_int_array: + writeline(f"static constexpr {ctype} *{var}=nullptr;") + else: + writeline(f"static const {ctype} *{var}=nullptr;") + else: + writeline(f"const {ctype} *{var}=nullptr;") + else: + if var not in self.declared_int_array_vars: + self.declared_int_array_vars.add(var) + if known_statically: + if config.cpp.use_constexpr_for_int_array: + writeline(f"static constexpr {ctype} {var}[] = {int_array};") + else: + writeline(f"static const {ctype} {var}[] = {int_array};") + else: + writeline(f"const {ctype} {var}[] = {int_array};") + return var + + def make_buffer_allocation(self, buffer): + return self.make_allocation( + buffer.get_name(), + buffer.get_device(), + buffer.get_dtype(), + buffer.get_size(), + buffer.get_stride(), + V.graph.get_allocation_size(buffer), + buffer.get_is_pinned(), + ) + + def make_allocation( + self, name, device, dtype, shape, stride, allocation_shape=None, is_pinned=False + ): + """Emit C++ to allocate a tensor handle via aoti_torch_empty_strided. + + Returns the RAIIAtenTensorHandle binding string; if the allocation + shape differs from the logical shape, a follow-up aoti_torch_as_strided + is emitted to reinterpret the handle. + """ + if allocation_shape is None: + allocation_shape = shape + + orig_stride = stride + device_str = self.codegen_device(device) + dtype_code = self.codegen_dtype(dtype) + size = self.codegen_shape_tuple(shape) + allocation_size = self.codegen_shape_tuple(allocation_shape) + stride = self.codegen_shape_tuple(orig_stride) + + size_array_var = self.codegen_int_array_var( + size, + self.wrapper_call.writeline, + known_statically=self.is_statically_known_list_of_ints(shape), + graph=self.get_codegened_graph(), + ) + + if allocation_size != size: + allocation_size_array_var = self.codegen_int_array_var( + allocation_size, + self.wrapper_call.writeline, + known_statically=self.is_statically_known_list_of_ints( + allocation_shape + ), + graph=self.get_codegened_graph(), + ) + else: + allocation_size_array_var = size_array_var + + stride_array_var = self.codegen_int_array_var( + stride, + self.wrapper_call.writeline, + known_statically=self.is_statically_known_list_of_ints(orig_stride), + graph=self.get_codegened_graph(), + ) + device_type, device_id = device_str.split(",") + handle_name = f"{name}_handle" + self.wrapper_call.writeline(f"AtenTensorHandle {handle_name};") + pinned_str = "_pinned" if is_pinned else "" + + def _alloc_line(device_idx: str) -> str: + args = ", ".join( + [ + str(len(shape)), + allocation_size_array_var, + stride_array_var, + dtype_code, + device_type, + device_idx, + f"&{handle_name}", + ] + ) + return f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided{pinned_str}({args}));" + + # AOTI side: codegen_device_idx returns this->device_idx_ for the + # primary device so the model honors runtime device assignment, but + # keeps concrete indices for non-primary (cross-device) allocations. + # JIT side (pure or dual mode's JIT) has no this->device_idx_ in scope, + # so use the concrete graph device id. + self.wrapper_call.writeline_aot( + _alloc_line(self.codegen_device_idx(device, device_id)) + ) + self.wrapper_call.writeline_jit(_alloc_line(device_id)) + + if allocation_size != size: + old_handle_name, handle_name = handle_name, f"{name}_handle_restrided" + self.wrapper_call.writeline(f"AtenTensorHandle {handle_name};") + args = [ + old_handle_name, + size_array_var, + stride_array_var, + f"&{handle_name}", + ] + self.wrapper_call.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_as_strided({', '.join(args)}));" + ) + self.wrapper_call.writeline( + f"wrap_with_raii_handle_if_needed({old_handle_name});" + ) + + return f"RAIIAtenTensorHandle {name}({handle_name});" + + def codegen_alloc_from_pool( + self, name, offset, dtype, shape, stride + ) -> tuple[str, list[str]]: + size = self.codegen_shape_tuple(shape) + stride = self.codegen_shape_tuple(stride) + tmp_name = f"tmp_tensor_handle_{next(self.tmp_tensor_id)}" + args = [ + name, + cexpr(offset), # bytes not numel + self.codegen_dtype(dtype), + str(len(shape)), + self.codegen_int_array_var( + size, self.wrapper_call.writeline, graph=self.get_codegened_graph() + ), + self.codegen_int_array_var( + stride, self.wrapper_call.writeline, graph=self.get_codegened_graph() + ), + f"&{tmp_name}", + ] + # We return the lines instead of writing here because writing here is bug prone. + # If you write aoti_torch__alloc_from_pool lines, you must write the RAIIAtenTensorHandle + # as well, otherwise you get memory leaks + allocations_to_write = [ + f"AtenTensorHandle {tmp_name};", + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch__alloc_from_pool({', '.join(args)}));", + ] + return f"RAIIAtenTensorHandle({tmp_name})", allocations_to_write + + def codegen_reinterpret_view( + self, + data, + size, + stride, + offset, + writeline: Callable[..., None], + dtype=None, + ) -> str: + """Returns a newly-created, temporary RAII tensor handle containing the + reinterpreted tensor data. Callers of this function are responsible for saving + the handle if persistent access is needed.""" + + d_size, d_stride, d_offset, d_dtype, collapsible = ( + codegen_reinterpret_view_helper(data) + ) + + dim = str(len(size)) + original_offset = offset + offset = self.codegen_sizevar(offset) + call_strs = [] + final_tensor_str = None + + def create_reinterpret_call() -> str: + args = [ + f"{data.get_name()}", + dim, + self.codegen_int_array_var( + self.codegen_shape_tuple(size), + writeline, + known_statically=self.is_statically_known_list_of_ints(size), + graph=self.get_codegened_graph(), + ), + self.codegen_int_array_var( + self.codegen_shape_tuple(stride), + writeline, + known_statically=self.is_statically_known_list_of_ints(stride), + graph=self.get_codegened_graph(), + ), + offset, + ] + return f"wrap_with_raii_handle_if_needed(reinterpret_tensor_wrapper({', '.join(args)}))" + + def create_dtypeview_call(reinterpret_call: str) -> tuple[str, list[str]]: + tmp_AtenTensorHandle = f"tmp_{data.get_name()}_{next(self.tmp_tensor_id)}" + tmp_call_strs = [f"AtenTensorHandle {tmp_AtenTensorHandle};"] + device_name = data.layout.device.type + dtypeview_function = f"aoti_torch_{device_name}_view_dtype" + tmp_call_strs.append( + f"AOTI_TORCH_ERROR_CODE_CHECK({dtypeview_function}" + f"({reinterpret_call}, {self.codegen_dtype(dtype)}, &{tmp_AtenTensorHandle}));" + ) + return f"RAIIAtenTensorHandle({tmp_AtenTensorHandle})", tmp_call_strs + + def create_new_tensor_handle() -> tuple[str, list[str]]: + tmp_AtenTensorHandle = f"tmp_{data.get_name()}_{next(self.tmp_tensor_id)}" + tmp_call_strs = [ + f"AtenTensorHandle {tmp_AtenTensorHandle};", + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_tensor_handle({data.get_name()}, &{tmp_AtenTensorHandle}));", + ] + return f"RAIIAtenTensorHandle({tmp_AtenTensorHandle})", tmp_call_strs + + collapsed = collapsible and original_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 original_offset == data.layout.offset + ) + base_dtype = data.dtype + + if same_layout: + # pure dtypeview + if dtype is not None and dtype != base_dtype: + final_tensor_str, tmp_call_strs = create_dtypeview_call(data.get_name()) + else: + final_tensor_str, tmp_call_strs = create_new_tensor_handle() + call_strs.extend(tmp_call_strs) + else: + # firstly create reinterpretview + final_tensor_str = create_reinterpret_call() + if dtype is not None and dtype != base_dtype: + # wrap it with dtypeview + final_tensor_str, tmp_call_strs = create_dtypeview_call( + final_tensor_str + ) + call_strs.extend(tmp_call_strs) + + for line in call_strs: + writeline(line) + + # NB, the return handle here represents a temporary tensor, which will be automatically + # released. + # Here's a sample usage in the cpp wrapper code: + # ``` + # aoti_torch_addmm_out( + # buf1, + # arg1_1, + # RAIIAtenTensorHandle(tmp_tensor_handle_0), + # buf0, + # 1L, + # 1L)); + # ``` + # RAIIAtenTensorHandle(tmp_tensor_handle_0) will be released after the call to addmm_out. + # This could be problematic when it's used in a different pattern, for example: + # ```` + # AtenTensorHandle tensor_args[] = {RAIIAtenTensorHandle(tmp_tensor_handle_2), buf5, buf6}; + # aoti_torch_proxy_executor_call_function(..., tensor_args); + # ```` + # RAIIAtenTensorHandle(tmp_tensor_handle_2) will be invalid when it's used in the latter + # kernel call. + # + # This is solved by updating the proxy_executor invocation to + # ``` + # aoti_torch_proxy_executor_call_function(..., + # std::array{ + # RAIIAtenTensorHandle(tmp_tensor_handle_2), buf5, buf6 + # }.cbegin() + # ); + # ``` + return final_tensor_str + + def codegen_device_copy(self, src, dst, non_blocking: bool | str): + """This function is overridden by cpp_wrapper_cpu_array_ref, so we don't need to + handle cases where dst is not an AtenTensorHandle.""" + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_copy_({dst}, {src}, {non_blocking}));" + ) + + def sync_d2h_copy(self, buffer_name: str) -> None: + # TODO: add AOTI C API for event-based D2H copy synchronization + pass + + def codegen_multi_output(self, node: ir.MultiOutput): + # in the abi_compatible mode, outputs are retrieved by passing + # output pointers, so we skip its codegen here. + pass + + def codegen_subgraph_prefix(self, subgraph, outer_inputs, outer_outputs): + if len(subgraph.graph.graph_inputs) != len(outer_inputs): + raise AssertionError( + f"expected len(subgraph.graph.graph_inputs) == len(outer_inputs), " + f"got {len(subgraph.graph.graph_inputs)} and {len(outer_inputs)}" + ) + + for (inner_input, inner_input_val), outer_input in zip( + subgraph.graph.graph_inputs.items(), outer_inputs + ): + if not isinstance(inner_input_val, ir.TensorBox): + continue + + # in ABI-compatible mode, we copy the underlying at::Tensor of the conditional + # input (outer_input) into another at::Tensor to be used as a subgraph input + # (inner_input) in the nested scope. we can't std::move here, as the codegened + # outer input may be an expression / rvalue (e.g., reinterpret_view(x)), so we + # can't necessarily std::move it back to the origin (x). + self.writeline(f"AtenTensorHandle {inner_input}_handle;") + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors_out({outer_input}, &{inner_input}_handle));" + ) + self.writeline(f"RAIIAtenTensorHandle {inner_input}({inner_input}_handle);") + + def codegen_subgraph_suffix(self, subgraph, outer_inputs, outer_outputs): + for inner_output, outer_output in zip( + subgraph.graph.graph_outputs, outer_outputs + ): + src = inner_output.codegen_reference() + if not isinstance(inner_output, ir.ShapeAsConstantBuffer): + # in ABI-compatible mode, we need to std::move subgraph output (inner_output) + # to the conditional output (outer_output), as RAIIAtenTensorHandle's copy + # constructor is deleted. + src = f"std::move({src})" + # in case the outer_output carried a value + # before (e.g., in the while_loop codegen) + self.writeline(f"{outer_output}.reset();") + self.writeline(f"{outer_output} = {src};") + + @staticmethod + def _get_while_loop_carried_output_names(while_loop): + mutation_output_names = { + mutation_name: mutation_output.get_name() + for mutation_output in while_loop.mutation_outputs + for mutation_name in mutation_output.get_mutation_names() + } + + def resolve_mutation_output_name(name): + seen = OrderedSet() + while name in mutation_output_names: + if name in seen: + raise AssertionError("while_loop mutation outputs contain a cycle") + seen.add(name) + name = mutation_output_names[name] + return name + + output_names = [] + output_idx = 0 + for carried_input in while_loop.carried_inputs: + carried_input_name = carried_input.get_name() + mutation_output_name = resolve_mutation_output_name(carried_input_name) + if mutation_output_name != carried_input_name: + output_names.append(mutation_output_name) + continue + + if output_idx >= len(while_loop.outputs): + raise AssertionError( + "while_loop has fewer non-mutated outputs than carried inputs" + ) + output_names.append(while_loop.outputs[output_idx].get_name()) + output_idx += 1 + + if output_idx != len(while_loop.outputs): + raise AssertionError("while_loop has unused non-mutated outputs") + + return output_names + + def codegen_invoke_subgraph(self, invoke_subgraph): + raise NotImplementedError( + "codegen invoke_subgraph is not implemented for cpp wrapper" + ) + + def codegen_switch(self, node) -> None: + """Emit ABI-compatible C++ for a higher-order cond/switch.""" + outer_inputs = [f"{buf.codegen_reference()}" for buf in node.operands] + outer_outputs = [] + for out in node.outputs: + # in ABI-compatible mode, ir.MultiOutput is not codegened, + # hence pre-declare output variables directly and separately + self.writeline(f"RAIIAtenTensorHandle {out.get_name()};") + outer_outputs.append(out.get_name()) + + if not isinstance(node.selector, ir.ShapeAsConstantBuffer): + # use the ABI shim to extract the scalar selector value from the Tensor; + # always as int64 so the branch loop can use uniform index comparisons + # (cond: True==1, False==0) + selector_var = f"{node.selector.get_name()}_scalar" + if selector_var not in self.used_switch_selector: + self.codegen_tensor_item( + torch.int64, + node.selector.codegen_reference(), + selector_var, + ) + self.used_switch_selector.add(selector_var) + else: + # ShapeAsConstantBuffer yields a C++ bool/int expression; Cast to int64_t. + selector_var = f"static_cast({node.selector.codegen_reference()})" + + def _emit_branch(header: str, branch) -> None: + self.writeline(header) + with self._preserve_device_guard_state(): + self.writeline(EnterSubgraphLine(self, branch.graph)) + self.codegen_subgraph(branch, outer_inputs, outer_outputs) + self.writeline(ExitSubgraphLine(self)) + + def emit_switch_body() -> None: + num_branches = len(node.branches) + for b_idx, branch in enumerate(node.branches): + if b_idx == 0: + header = f"if ({selector_var} == 0) {{" + elif b_idx < num_branches - 1: + header = f"}} else if ({selector_var} == {b_idx}) {{" + else: + header = "} else {" + _emit_branch(header, branch) + self.writeline("}") + + if not V.graph.is_dual_wrapper_mode: + return emit_switch_body() + + graphs = tuple(branch.graph for branch in node.branches) + jit_code = IndentedBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._preserve_codegen_state(graphs), + self._target_buf("wrapper_call", jit_code), + self.set_writeline(jit_code, jit_code.writeline_jit), + ): + # JIT pass: visit each branch once for lazy kernel autotune + for branch in node.branches: + self.writeline("{") + with self._preserve_device_guard_state(): + self.writeline(EnterSubgraphLine(self, branch.graph)) + self.codegen_subgraph(branch, outer_inputs, outer_outputs) + self.writeline(ExitSubgraphLine(self)) + self.writeline("}") + + aot_code = AotOnlyBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._target_buf("wrapper_call", aot_code), + self.set_writeline(aot_code, aot_code.writeline_aot), + ): + emit_switch_body() + + self.writeline(DualWrapperCodeLine(jit_code, aot_code)) + + def codegen_subgraph(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 + # PythonWrapperCode `codegen_subgraph` function. We should perhaps + # support lifting of subgraphs as functions for cpp wrapper as well. + try: + self.push_codegened_graph(subgraph.graph) + self.writeline(f"// subgraph: {subgraph.name}") + self.codegen_subgraph_prefix(subgraph, outer_inputs, outer_outputs) + parent_graph = V.graph + with V.set_graph_handler(subgraph.graph): + subgraph.graph.codegen_subgraph( + parent_graph=parent_graph, + ) + self.codegen_subgraph_suffix(subgraph, outer_inputs, outer_outputs) + finally: + self.pop_codegened_graph() + + def codegen_while_loop(self, while_loop, stack_output=False): + """Emit ABI-compatible C++ for a higher-order while_loop. + + In dual-wrapper mode, keep the real loop on the AOTI side while making + the JIT first pass visit the condition and body once for lazy autotune. + """ + if stack_output: + raise NotImplementedError("NYI cpp wrapper for while_loop_stack_output") + is_bool_pred = isinstance( + while_loop.cond_subgraph.graph.graph_outputs[0], ir.ShapeAsConstantBuffer + ) + 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 + ] + carried_output_names = self._get_while_loop_carried_output_names(while_loop) + cond_result_name = f"{name}_cond_result" + if is_bool_pred: + self.writeline(f"bool {cond_result_name};") + else: + self.writeline(f"RAIIAtenTensorHandle {cond_result_name};") + + cond_outer_inputs = [] + for inp, out_name in zip(outer_carried_inputs, carried_output_names): + # in ABI-compatible mode, the carried inputs are codegened + # as buffers outside the while loop and set to the initial + # values. at the end of each while_loop iteration, they + # will be assigned the carried values. + self.writeline(f"AtenTensorHandle {out_name}_handle;") + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors_out({inp}, &{out_name}_handle));" + ) + self.writeline(f"RAIIAtenTensorHandle {out_name}({out_name}_handle);") + cond_outer_inputs.append(out_name) + + # additional inputs will be assigned within the while_loop + # iteration directly from the corresponding outer graph buffers + cond_outer_inputs.extend(outer_additional_inputs) + + cond_outer_outputs = [cond_result_name] + body_outer_inputs = list(cond_outer_inputs) + body_outer_outputs = body_outer_inputs[: len(outer_carried_inputs)] + + def codegen_original_while_loop() -> None: + self.writeline("while (1) {") + with self._preserve_device_guard_state(): + self.writeline(EnterSubgraphLine(self, while_loop.cond_subgraph.graph)) + self.codegen_subgraph( + while_loop.cond_subgraph, cond_outer_inputs, cond_outer_outputs + ) + + if is_bool_pred: + cond_result = f"{cond_result_name}" + else: + cond_result = f"{cond_result_name}_scalar" + self.codegen_tensor_item(torch.bool, cond_result_name, cond_result) + self.writeline(f"if (!{cond_result}) break;") + + self.writeline(ExitSubgraphLine(self)) + self.writeline(EnterSubgraphLine(self, while_loop.body_subgraph.graph)) + self.codegen_subgraph( + while_loop.body_subgraph, body_outer_inputs, body_outer_outputs + ) + self.writeline(ExitSubgraphLine(self)) + self.writeline("}") + + if not V.graph.is_dual_wrapper_mode: + return codegen_original_while_loop() + + graphs = ( + while_loop.cond_subgraph.graph, + while_loop.body_subgraph.graph, + ) + jit_code = IndentedBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._preserve_codegen_state(graphs), + self._target_buf("wrapper_call", jit_code), + self.set_writeline(jit_code, jit_code.writeline_jit), + ): + self.writeline("{") + with self._preserve_device_guard_state(): + self.writeline(EnterSubgraphLine(self, while_loop.cond_subgraph.graph)) + self.codegen_subgraph( + while_loop.cond_subgraph, cond_outer_inputs, cond_outer_outputs + ) + self.writeline(ExitSubgraphLine(self)) + self.writeline(EnterSubgraphLine(self, while_loop.body_subgraph.graph)) + self.codegen_subgraph( + while_loop.body_subgraph, body_outer_inputs, body_outer_outputs + ) + self.writeline(ExitSubgraphLine(self)) + self.writeline("}") + + aot_code = AotOnlyBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._target_buf("wrapper_call", aot_code), + self.set_writeline(aot_code, aot_code.writeline_aot), + ): + codegen_original_while_loop() + + self.writeline(DualWrapperCodeLine(jit_code, aot_code)) + + def generate_extern_kernel_args_decl_if_needed( + self, + op_overload: torch._ops.OpOverload | torch._ops.HigherOrderOperator, + raw_args: Sequence[Any], + output_args: _OUTPUT_ARGS_TYPE, + raw_outputs: Sequence[ir.Buffer], + ): + """ + Generates declarations for external kernel arguments if needed, based on the provided + operator and its arguments. It processes both input and output arguments, categorizing + them into tensor and integer arguments for further code generation. + """ + schema = None + if isinstance(op_overload, torch._higher_order_ops.torchbind.CallTorchBind): + obj = raw_args[0] + method = raw_args[1] + schema = op_overload.schema(obj, method) + else: + if not isinstance(op_overload, torch._ops.OpOverload): + raise AssertionError(type(op_overload)) + schema = op_overload._schema + if schema is None: + raise AssertionError("expected schema to be set") + arg_types = [x.real_type for x in schema.arguments] + return_types = [x.type for x in schema.returns] + + new_tensor_args = [] + new_int_args = [] + + def fill_args(arg, arg_type): + static_arg_types = ( + torch.FloatType, + torch.BoolType, + torch.StringType, + torch.Type, + torch.DeviceObjType, + ) + inductor_tensor_buffers = ( + ir.Buffer, + ir.ReinterpretView, + ) + + if isinstance(arg_type, torch.TensorType): + if not isinstance(arg, inductor_tensor_buffers): + raise AssertionError(f"got {type(arg)}") + new_tensor_args.append(f"{arg.codegen_reference()}") + elif isinstance(arg_type, torch.IntType): + # int + new_int_args.append(str(arg)) + elif isinstance(arg_type, torch.SymIntType): + # SymInt + expr = arg.node.expr if isinstance(arg, torch.SymInt) else arg + new_int_args.append(cexpr(expr)) + elif isinstance(arg_type, torch.NumberType): + # Scalar of type int + if not isinstance(arg, (int, float, bool)): + raise AssertionError( + f"expected arg to be int, float, or bool, got {type(arg)}" + ) + # Only treat int Scalar as dynamic + if isinstance(arg, int): + new_int_args.append(str(arg)) + elif isinstance(arg, ir.TorchBindObject): + # torchbind objects are loaded in proxy executor + pass + elif isinstance(arg_type, torch.ListType): + if not isinstance(arg, (list, tuple)): + raise AssertionError( + f"expected arg to be list or tuple, got {type(arg)}" + ) + + # List[Tensor] + if isinstance(arg_type.getElementType(), torch.TensorType): + new_tensor_args.extend([f"{a.codegen_reference()}" for a in arg]) + # List[Optional[Tensor]] + elif isinstance( + arg_type.getElementType(), torch.OptionalType + ) and isinstance( + arg_type.getElementType().getElementType(), torch.TensorType + ): + new_tensor_args.extend( + [f"{a.codegen_reference()}" for a in arg if a is not None] + ) + # List[int] + elif isinstance(arg_type.getElementType(), torch.IntType): + new_int_args.extend([str(a) for a in arg]) + # List[SymInt] + elif isinstance(arg_type.getElementType(), torch.SymIntType): + expressions = [ + a.node.expr if isinstance(a, torch.SymInt) else a for a in arg + ] + new_int_args.extend([cexpr(expr) for expr in expressions]) + # List[Scalar] + elif isinstance(arg_type.getElementType(), torch.NumberType): + # Only treat int Scalar as dynamic + is_int_type = [isinstance(a, int) for a in arg] + if any(is_int_type): + if not all(is_int_type): + raise AssertionError( + "AOTInductor only supports int scalars of the same type" + ) + new_int_args.extend([str(a) for a in arg]) + else: + if not isinstance( + arg_type.getElementType(), + static_arg_types, # type: ignore[arg-type] + ): + raise AssertionError( + f"Fall through arguments must be one of static_arg_types, got {type(arg_type)}" + ) + else: + if not isinstance( + arg_type, + static_arg_types, # type: ignore[arg-type] + ): + raise AssertionError( + f"Fall through arguments must be one of static_arg_types, got {type(arg_type)}" + ) + + for arg, arg_type in zip(raw_args, arg_types): + if arg is not None: + if isinstance(arg_type, torch.OptionalType): + fill_args(arg, arg_type.getElementType()) + else: + fill_args(arg, arg_type) + + def fill_output_arg( + arg: str, return_type: torch.JitType, is_mutated_output: bool + ) -> None: + if isinstance(return_type, torch.TensorType): + if not is_mutated_output: + self.writeline(f"AtenTensorHandle {arg}_handle; // output buffer") + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_uninitialized_tensor(&{arg}_handle));" + ) + self.writeline(f"RAIIAtenTensorHandle {arg}({arg}_handle);") + new_tensor_args.append(f"{arg}") + elif isinstance(return_type, torch.SymIntType): + raise NotImplementedError("NYI support for return type: SymInt") + elif isinstance(return_type, torch.ListType) and isinstance( + return_type.getElementType(), torch.SymIntType + ): + raise NotImplementedError("NYI support for return type: List[SymInt]") + else: + raise AssertionError(f"Unsupported return type found: {return_type}") + + # TODO: Only support None and tensor(s) returns for now, SymInt is not implemented yet + for return_type in return_types: + if isinstance( + return_type, (torch.TensorType, torch.NoneType, torch.IntType) + ): + pass + elif isinstance(return_type, torch.OptionalType): + if not isinstance(return_type.getElementType(), torch.TensorType): + raise AssertionError( + f"expected Optional element type to be TensorType, " + f"got {return_type.getElementType()}" + ) + elif isinstance(return_type, torch.ListType): + if not isinstance(return_type.getElementType(), torch.TensorType): + raise AssertionError( + f"expected List element type to be TensorType, " + f"got {return_type.getElementType()}" + ) + else: + raise NotImplementedError( + f"return type {return_type} is not yet supported." + ) + + for output_arg, raw_output_arg in zip(output_args, raw_outputs): # type: ignore[arg-type] + # None output is supported, but Optional return types are not yet supported + if output_arg is None: + continue + elif isinstance(raw_output_arg, int): + new_int_args.append(str(raw_output_arg)) + elif isinstance(output_arg, list): + for out in output_arg: + if out is None: + raise AssertionError(out) + fill_output_arg( + out, + torch.TensorType.get(), + isinstance(raw_output_arg, ir.MutationOutput), + ) + else: + fill_output_arg( + output_arg, + torch.TensorType.get(), + isinstance(raw_output_arg, ir.MutationOutput), + ) + + return new_tensor_args, new_int_args + + @staticmethod + def _compatible_with_stableivalue(op: torch._ops.OpOverload) -> bool: + """Returns true if op_overload._schema only utilizes types supported by the AOT + C-shim *internal* function to_ivalue. to_ivalue is an implementation detail, so + these types are not guaranteed to be supported long-term. When generating code + for cpp_wrapper mode, we don't have to be forward-compatible, so changing this + function's implementation in future is fine.""" + supported_types = ( + torch.BoolType, + torch.DeviceObjType, + torch.FloatType, + # ScalarTypeType, LayoutType, and MemoryFormatType are seen as IntType + # when queried via torch.JitType.type. + torch.IntType, + torch.TensorType, + ) + + def type_supported(t: torch.JitType) -> bool: + if isinstance(t, torch.OptionalType): + return type_supported(t.getElementType()) + return isinstance(t, supported_types) + + def uses_symint(t: torch.JitType) -> bool: + # SymInt/SymBool/SymFloat are reported as Int/Bool/Float by + # JitType.type, so they pass type_supported above. But the + # StableIValue codegen below emits no symbolic-int-aware conversion, + # so route such ops to the boxed dispatch path, which handles + # c10::SymInt correctly. real_type preserves the symbolic types. + if isinstance(t, (torch.OptionalType, torch.ListType)): + return uses_symint(t.getElementType()) + return ( + isinstance(t, (torch.SymIntType, torch.SymBoolType)) + or repr(t) == "SymFloat" + ) + + return all( + type_supported(a.type) and not uses_symint(a.real_type) + for a in chain(op._schema.arguments, op._schema.returns) + ) + + @staticmethod + def _compatible_with_cpp_boxed_dispatch(op: torch._ops.OpOverload) -> bool: + """Returns true if cpp_wrapper JIT can directly codegen c10::IValue boxing + for this schema and can unpack the returned values into tensor handles. + + Unlike the StableIValue path, this is only used for JIT cpp_wrapper, where + we can include ATen/c10 headers and call the dispatcher directly. + """ + + def arg_supported(t: torch.JitType) -> bool: + if isinstance(t, torch.OptionalType): + return arg_supported(t.getElementType()) + if isinstance(t, torch.ListType): + return arg_supported(t.getElementType()) + if isinstance(t, torch.TupleType): + return all(arg_supported(e) for e in t.elements()) + return isinstance( + t, + ( + torch.BoolType, + torch.DeviceObjType, + torch.FloatType, + torch.IntType, + torch.NumberType, + torch.StringType, + torch.SymBoolType, + torch.SymIntType, + torch.TensorType, + ), + ) or repr(t) in ("Layout", "MemoryFormat", "ScalarType", "SymFloat") + + def return_supported(t: torch.JitType) -> bool: + if isinstance(t, torch.OptionalType): + return isinstance(t.getElementType(), torch.TensorType) + return isinstance(t, (torch.NoneType, torch.TensorType)) + + return all(arg_supported(a.real_type) for a in op._schema.arguments) and all( + return_supported(r.real_type) for r in op._schema.returns + ) + + 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: + """Generate a call to a kernel not contained in the C-shim. This results in + different code paths for AOT Inductor vs cpp_wrapper Inductor mode.""" + + def extract_output_name( + out: ir.Buffer | Sequence[ir.Buffer] | None, + ) -> str | None | _OUTPUT_ARGS_TYPE: + if out is None: + return None + if isinstance( + out, (ir.MultiOutput, ir._CollectiveKernel, ir.FallbackKernel) + ): + return out.get_name() + if isinstance(out, ir.MutationOutput): + mutated_buf_names = out.get_mutation_names() + if not ( + isinstance(mutated_buf_names, list) and len(mutated_buf_names) == 1 + ): + raise AssertionError( + "Expect only one mutated buffer in MutationOutput" + ) + return mutated_buf_names[0] + if isinstance(out, (list, tuple)): + return [extract_output_name(o) for o in out] # type: ignore[misc] + if isinstance(out, int): + return str(out) + raise AssertionError(f"Unexpected output: {type(out)}") + + if isinstance(op_overload, torch._ops.HigherOrderOperator): + if not isinstance( + op_overload, torch._higher_order_ops.torchbind.CallTorchBind + ): + raise AssertionError(type(op_overload)) + if len(raw_args) <= 1: + raise AssertionError(f"expected len(raw_args) > 1, got {len(raw_args)}") + obj = raw_args[0] + method = raw_args[1] + return_schema = op_overload.schema(obj, method).returns + else: + return_schema = op_overload._schema.returns + + # output_args has the same pytree structure as outputs + if not return_schema: + # kernel does not return a value + output_args: _OUTPUT_ARGS_TYPE = [] + elif isinstance(output_name := extract_output_name(outputs), str): + output_args = [output_name] + else: + # If the schema indicates a return value, we should have a non-None value by + # this point. + if not isinstance(output_name, list): + raise AssertionError(type(output_name)) + output_args = output_name + + # In AOT mode, we use a ProxyExecutor to run fallback kernels. + if V.graph.aot_mode and V.graph.is_dual_wrapper_mode: + jit_code = IndentedBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._target_buf("wrapper_call", jit_code), + self.set_writeline(jit_code, jit_code.writeline_jit), + ): + self._generate_fallback_kernel_jit( + buf_name, + python_kernel_name, + get_args, + op_overload, + raw_args, + output_args, + outputs, + ) + + aot_code = AotOnlyBuffer(initial_indent=self.wrapper_call._indent) + with ( + self._target_buf("wrapper_call", aot_code), + self.set_writeline(aot_code, aot_code.writeline_aot), + ): + self.generate_fallback_kernel_with_runtime_lookup_aot( + op_overload, + raw_args, + output_args, + outputs, + ) + + self.writeline(DualWrapperCodeLine(jit_code, aot_code)) + return + + if V.graph.aot_mode: + self.generate_fallback_kernel_with_runtime_lookup_aot( + op_overload, + raw_args, + output_args, + outputs, + ) + + if not V.graph.aot_mode: + self._generate_fallback_kernel_jit( + buf_name, + python_kernel_name, + get_args, + op_overload, + raw_args, + output_args, + outputs, + ) + + def _generate_fallback_kernel_jit( + self, + buf_name, + python_kernel_name, + get_args, + op_overload, + raw_args, + output_args, + outputs, + ): + """Emit JIT-mode fallback kernel code (no-Python dispatcher or Python callback).""" + if not isinstance(op_overload, torch._ops.OpOverload): + raise AssertionError(type(op_overload)) + for output in output_args: + if not (output is None or isinstance(output, str)): + raise AssertionError( + "fallback kernels with runtime lookup currently only support tensor " + "returns, not more complicated types (such as list-of-list-of-tensor)" + ) + + # In non-AOT mode, we use aoti_torch_call_dispatcher if all the inputs and + # outputs of the op can be represented with StableIValue. This avoids the + # overhead of calling back into Python, and covers most remaining fallback ops. + if self._compatible_with_stableivalue(op_overload): + self.generate_fallback_kernel_with_runtime_lookup_nopython( + get_args, + op_overload, + output_args, # type: ignore[arg-type] + outputs, + ) + return + + # For cpp_wrapper JIT, fall back to direct boxed dispatcher calls for + # schemas the StableIValue bridge cannot represent, such as Tensor[]. + if self._compatible_with_cpp_boxed_dispatch(op_overload): + self.generate_fallback_kernel_with_runtime_lookup_boxed( + op_overload, + raw_args, + output_args, # type: ignore[arg-type] + outputs, + ) + return + + # Otherwise, we call back into Python, which has some extra runtime overhead, + # but handles situations like list[Tensor] (currently unrepresentable via + # StableIValue). + self.generate_fallback_kernel_with_runtime_lookup_python( + buf_name, + python_kernel_name, + op_overload, + raw_args, + output_args, # type: ignore[arg-type] + outputs, + ) + + def generate_scoped_gil_acquire(self, declarations_before_scope, lines_in_scope): + scoped_lines = IndentedBuffer() + for declaration in declarations_before_scope: + scoped_lines.writeline(declaration) + + scoped_lines.writeline("{") + with scoped_lines.indent(): + scoped_lines.writeline("py::gil_scoped_acquire_simple acquire;") + scoped_lines.writelines(lines_in_scope.split("\n")) + scoped_lines.writelines("}") + return scoped_lines._lines + + def load_custom_op_wrapper(self): + # TODO: need to support control flow + if self.custom_op_wrapper_loaded: + return + + lines = """ +RAIIPyObject codecache_module(PyImport_ImportModule("torch._inductor.codecache")); +if (!codecache_module) { + throw std::runtime_error("Failed to load torch._inductor.codecache"); +} +custom_op_wrapper = PyObject_GetAttrString(codecache_module, "custom_op_wrapper"); +if (!custom_op_wrapper) { + throw std::runtime_error("Failed to load torch._inductor.codecache.custom_op_wrapper"); +}""" + + declarations_before_scope = ["RAIIPyObject custom_op_wrapper;"] + scope_gil_acquire = self.generate_scoped_gil_acquire( + declarations_before_scope, lines + ) + self.writelines(scope_gil_acquire) + + self.custom_op_wrapper_loaded = True + + def generate_float_value(self, val): + if not isinstance(val, float): + raise AssertionError(f"expected val to be float, got {type(val)}") + if val == float("inf"): + return "std::numeric_limits::infinity()" + elif val == float("-inf"): + return "-std::numeric_limits::infinity()" + elif math.isnan(val): + return "std::numeric_limits::quiet_NaN()" + else: + return f"{val}" + + def generate_py_arg(self, py_args_var, idx, raw_arg, arg_type): + """Generate C++ code that converts a single operator argument into a Python + object and inserts it into a PyTuple at the given index.""" + + def generate_py_arg_inner(lines, raw_arg, arg_type): + def handle_scalar(scalar): + if isinstance(scalar, bool): + return f"PyBool_FromLong({1 if scalar else 0})" + if isinstance(scalar, int): + return f"PyLong_FromLongLong({scalar})" + if isinstance(scalar, float): + return f"PyFloat_FromDouble({self.generate_float_value(scalar)})" + if isinstance(scalar, complex): + real = self.generate_float_value(scalar.real) + imag = self.generate_float_value(scalar.imag) + return f"PyComplex_FromDoubles({real}, {imag})" + if isinstance(scalar, SymTypes): + scalar_var = cexpr(scalar.node.expr) + if isinstance(scalar, torch.SymBool): + return f"PyBool_FromLong({scalar_var})" + if isinstance(scalar, torch.SymFloat): + return f"PyFloat_FromDouble({scalar_var})" + return f"PyLong_FromLongLong({scalar_var})" + raise NotImplementedError( + f"scalar {scalar}, {type(scalar)} cannot be handled by handle_scalar" + ) + + is_any = isinstance(arg_type, torch.AnyType) + + def handle_any(types: type | tuple[type, ...]): + return is_any and isinstance(raw_arg, types) + + if raw_arg is None: + # Py_None is a singleton, so we have to explicitly incref it here + lines.append("Py_INCREF(Py_None);\n") + return "Py_None" + elif isinstance(arg_type, torch.TensorType) or handle_any(ir.IRNode): + # In some cases, scalar arguments may be passed in place of tensors. + if not hasattr(raw_arg, "codegen_reference"): + return handle_scalar(raw_arg) + + # Store AtenTensorHandle as void*. All Python args are constructed in a + # nested scope, so this handle will self-destruct after the function + # call. + base_handle = self.create_tmp_raii_handle_var_if_needed( + raw_arg.codegen_reference(), lines + ) + return f"PyCapsule_New(reinterpret_cast({base_handle}.get()), NULL, NULL)" + elif isinstance(arg_type, torch.OptionalType): + return generate_py_arg_inner(lines, raw_arg, arg_type.getElementType()) + elif isinstance(arg_type, torch.BoolType) or handle_any(bool): + return f"PyBool_FromLong({1 if raw_arg else 0})" + elif isinstance(arg_type, torch.IntType) or handle_any(int): + # int + return f"PyLong_FromLongLong({raw_arg})" + elif isinstance(arg_type, torch.SymIntType) or handle_any(torch.SymInt): + # SymInt + expr = ( + raw_arg.node.expr if isinstance(raw_arg, torch.SymInt) else raw_arg + ) + return f"PyLong_FromLongLong({cexpr(expr)})" + elif isinstance(arg_type, torch.FloatType) or handle_any(float): + return f"PyFloat_FromDouble({self.generate_float_value(raw_arg)})" + elif isinstance(arg_type, torch.StringType) or handle_any(str): + return f'PyUnicode_FromString("{raw_arg}")' + elif isinstance(arg_type, torch.NumberType) or handle_any( + (*SymTypes, torch.types.Number, complex) + ): + # Union[bool, int, float, complex] + # torch/_prims_common/__init__.py + return handle_scalar(raw_arg) + elif isinstance(raw_arg, torch.device): + device_str, device_index = self.codegen_device(raw_arg).split(", ") + return f"torch_python_thp_device_new({device_str}, {device_index})" + elif isinstance(raw_arg, torch.dtype): + return f"torch_python_get_thp_dtype({self.codegen_dtype(raw_arg)})" + elif isinstance(raw_arg, torch.layout): + return f"torch_python_get_thp_layout({self.codegen_layout(raw_arg)})" + elif isinstance(raw_arg, torch.memory_format): + return ( + "torch_python_get_thp_memory_format(" + f"{self.codegen_memory_format(raw_arg)})" + ) + else: + raise NotImplementedError( + f"arg type {arg_type} is not yet supported by custom_op_wrapper" + ) + + def handle_sequence_arg(raw_arg_, arg_type_, lines_): + if not isinstance(raw_arg_, (list, tuple)): + raise AssertionError(str(raw_arg) + " is not a list") + lines_.append( + f"PyObject* {py_args_var}_{idx} = PyList_New({len(raw_arg)});\n" + ) + for i, elem in enumerate(raw_arg_): + lines_.append( + f"PyList_SetItem({py_args_var}_{idx}, {i}, {generate_py_arg_inner(lines, elem, arg_type_.getElementType())});\n" + ) + lines_.append( + f"PyTuple_SetItem({py_args_var}, {idx}, {py_args_var}_{idx});\n" + ) + + lines = [] + if isinstance(arg_type, torch.ListType): + handle_sequence_arg(raw_arg, arg_type, lines) + elif isinstance(arg_type, torch.OptionalType) and isinstance( + arg_type.getElementType(), torch.ListType + ): + if raw_arg is None: + lines.append( + f"PyTuple_SetItem({py_args_var}, {idx}, {generate_py_arg_inner(lines, raw_arg, arg_type)});\n" + ) + else: + handle_sequence_arg(raw_arg, arg_type.getElementType(), lines) + else: + lines.append( + f"PyTuple_SetItem({py_args_var}, {idx}, {generate_py_arg_inner(lines, raw_arg, arg_type)});\n" + ) + return "".join(lines) + + def generate_fallback_kernel_with_runtime_lookup_nopython( + self, + get_args: Callable[[], Sequence[str]], + op_overload: torch._ops.OpOverload, + output_args: Sequence[str | None], + raw_outputs: Sequence[ir.Buffer], + ) -> None: + """Generate fallback kernel calls with runtime (non-AOT) dispatch. This can + only be called in cpp_wrapper mode, and assumes that the input is a non-None + OpOverload. + + In the future, we may switch over to directly calling c10::Dispatcher if we need + to support more datatypes.""" + if raw_outputs: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg, raw_output_arg in zip(output_args, raw_outputs) # type: ignore[arg-type] + if output_arg is not None + and not isinstance(raw_output_arg, ir.MutationOutput) + ] + else: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg in output_args # type: ignore[arg-type] + if output_arg is not None + ] + + dispatch_lines = IndentedBuffer() + dispatch_lines.writelines(declarations_before_scope) + dispatch_lines.writeline("{") + + with dispatch_lines.indent(): + tmp_var_number = count() + + def parse_arg(arg_type: torch.JitType, codegen_arg: str) -> str: + # Strip off any temporary references; we're in an indented context, so + # any saved-off variables will be auto-destroyed. + new_codegen_arg = codegen_arg.removeprefix("&temporary_reference(") + if new_codegen_arg != codegen_arg: + # If we removed temporary_reference, there's a good chance the + # variable ends with get() (which would retrieve an ATenTensorHandle + # from a temporary RAII handle). Strip that off too, since we're + # going to save this in a temporary RAII handle. + if codegen_arg.endswith(".get())"): + codegen_arg = new_codegen_arg.removesuffix(".get())") + else: + codegen_arg = new_codegen_arg.removesuffix(")") + + if isinstance(arg_type, torch.OptionalType): + # If we have a pointer to a variable, strip it off and let + # from handle any internal pointers. + codegen_arg = codegen_arg.removeprefix("&") + + if codegen_arg == "nullptr": + return "torch::stable::detail::from(std::nullopt)" + + var_name = f"tmp_var_{next(tmp_var_number)}" + dispatch_lines.writeline( + f"std::optional {var_name}{{{parse_arg(arg_type.getElementType(), codegen_arg)}}};" + ) + return f"torch::stable::detail::from({var_name})" + + raii_var = self.create_tmp_raii_handle_var_if_needed( + codegen_arg, dispatch_lines + ) + temp_handle = raii_var != codegen_arg + + if isinstance(arg_type, torch.TensorType): + if not temp_handle: + # If the RAII tensor being referenced _isn't_ a temporary, + # scoped to this fallback call, then create a new handle + # referencing it which from can steal. + var_name = f"tmp_var_{next(tmp_var_number)}" + dispatch_lines.writeline(f"AtenTensorHandle {var_name};") + dispatch_lines.writeline( + "AOTI_TORCH_ERROR_CODE_CHECK(" + f"aoti_torch_new_tensor_handle({raii_var}, &{var_name}));" + ) + return f"torch::stable::detail::from({var_name})" + # If the RAII tensor _is_ a temporary scoped to this fallback call, + # simply release and steal the handle. + return f"torch::stable::detail::from({raii_var}.release())" + return f"torch::stable::detail::from({codegen_arg})" + + codegen_args = get_args() + ivalue_args = ( + parse_arg(a.type, c) + for a, c in zip(op_overload._schema.arguments, codegen_args) + ) + array_len = max(len(codegen_args), len(output_args)) + dispatch_lines.writeline( + f"std::array dispatch_vars{{{', '.join(ivalue_args)}}};" + ) + dispatch_lines.writeline("AOTI_TORCH_ERROR_CODE_CHECK(") + with dispatch_lines.indent(): + dispatch_lines.writeline( + f'aoti_torch_call_dispatcher("{op_overload._schema.name}", "{op_overload._schema.overload_name}", dispatch_vars.data())' + ) + dispatch_lines.writeline(");") + + # assign result(s), ignoring None + for idx, output_arg in enumerate(output_args): + if output_arg is None: + continue + dispatch_lines.writeline( + f"{output_arg} = torch::stable::detail::to(dispatch_vars[{idx}]);" + ) + + dispatch_lines.writeline("}") + self.writelines(dispatch_lines.getvalue().splitlines()) + + def generate_fallback_kernel_with_runtime_lookup_boxed( + self, + op_overload: torch._ops.OpOverload, + raw_args: Sequence[Any], + output_args: Sequence[str | None], + raw_outputs: Sequence[ir.Buffer], + ) -> None: + """Generate a JIT-only fallback call through c10::Dispatcher. + + This covers custom C++ ops whose schemas are outside StableIValue's + supported subset without routing through Python. + """ + self.include_extra_header("ATen/core/dispatch/Dispatcher.h") + self.include_extra_header("ATen/core/ivalue.h") + self.include_extra_header("ATen/core/jit_type.h") + self.include_extra_header("torch/csrc/inductor/aoti_torch/utils.h") + + if raw_outputs: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg, raw_output_arg in zip(output_args, raw_outputs) + if output_arg is not None + and not isinstance(raw_output_arg, ir.MutationOutput) + ] + else: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg in output_args + if output_arg is not None + ] + + dispatch_lines = IndentedBuffer() + dispatch_lines.writelines(declarations_before_scope) + dispatch_lines.writeline("{") + + with dispatch_lines.indent(): + tmp_var_number = count() + + def next_tmp(prefix: str) -> str: + return f"{prefix}_{next(tmp_var_number)}" + + def type_expr(t: torch.JitType) -> str: + if isinstance(t, torch.OptionalType): + return f"c10::OptionalType::create({type_expr(t.getElementType())})" + if isinstance(t, torch.ListType): + return f"c10::ListType::create({type_expr(t.getElementType())})" + if isinstance(t, torch.TupleType): + elems = ", ".join(type_expr(e) for e in t.elements()) + var_name = next_tmp("tmp_type") + dispatch_lines.writeline( + f"std::vector {var_name}{{{elems}}};" + ) + return f"c10::TupleType::create(std::move({var_name}))" + if isinstance(t, torch.BoolType): + return "c10::BoolType::get()" + if isinstance(t, torch.DeviceObjType): + return "c10::DeviceObjType::get()" + if isinstance(t, torch.FloatType): + return "c10::FloatType::get()" + if isinstance(t, torch.IntType): + return "c10::IntType::get()" + if isinstance(t, torch.NumberType): + return "c10::NumberType::get()" + if isinstance(t, torch.StringType): + return "c10::StringType::get()" + if isinstance(t, torch.SymBoolType): + return "c10::SymBoolType::get()" + if isinstance(t, torch.SymIntType): + return "c10::SymIntType::get()" + if isinstance(t, torch.TensorType): + return "c10::TensorType::get()" + type_repr = repr(t) + if type_repr == "Layout": + return "c10::LayoutType::get()" + if type_repr == "MemoryFormat": + return "c10::MemoryFormatType::get()" + if type_repr == "ScalarType": + return "c10::ScalarTypeType::get()" + if type_repr == "SymFloat": + return "c10::SymFloatType::get()" + raise AssertionError(f"Unsupported list element type: {t}") + + def codegen_memory_format(memory_format: torch.memory_format) -> str: + return { + torch.contiguous_format: "c10::MemoryFormat::Contiguous", + torch.channels_last: "c10::MemoryFormat::ChannelsLast", + torch.channels_last_3d: "c10::MemoryFormat::ChannelsLast3d", + torch.preserve_format: "c10::MemoryFormat::Preserve", + }[memory_format] + + def codegen_tensor_ivalue(raw_arg: Any, arg_type: torch.JitType) -> str: + if hasattr(raw_arg, "codegen_reference"): + codegen_arg = raw_arg.codegen_reference() + else: + codegen_arg = self.val_to_arg_str(raw_arg, arg_type) + + raii_var = self.create_tmp_raii_handle_var_if_needed( + codegen_arg, dispatch_lines + ) + return ( + "c10::IValue(*torch::aot_inductor::" + f"tensor_handle_to_tensor_pointer({raii_var}))" + ) + + def codegen_ivalue(raw_arg: Any, arg_type: torch.JitType) -> str: + if raw_arg is None: + # A None at a non-optional Tensor arg means an absent tensor. + # Box it as an undefined at::Tensor (ATen's absent-tensor + # sentinel, matching eager value_or(Tensor())); boxing None + # would fail to unbox as `const Tensor&`. Optionals stay None. + if isinstance(arg_type, torch.TensorType): + return "c10::IValue(at::Tensor())" + return "c10::IValue()" + + if isinstance(arg_type, torch.OptionalType): + return codegen_ivalue(raw_arg, arg_type.getElementType()) + + if isinstance(raw_arg, torch.device): + if raw_arg.type not in DEVICE_TO_ATEN: + raise AssertionError( + raw_arg.type + " not found in DEVICE_TO_ATEN" + ) + return ( + "c10::IValue(c10::Device(" + f"{DEVICE_TO_ATEN[raw_arg.type]}, " + f"{raw_arg.index if raw_arg.index is not None else 0}))" + ) + if isinstance(raw_arg, torch.dtype): + return f"c10::IValue({DTYPE_TO_ATEN[raw_arg]})" + if isinstance(raw_arg, torch.layout): + return f"c10::IValue({LAYOUT_TO_ATEN[raw_arg]})" + if isinstance(raw_arg, torch.memory_format): + return f"c10::IValue({codegen_memory_format(raw_arg)})" + + if isinstance(arg_type, torch.TensorType): + return codegen_tensor_ivalue(raw_arg, arg_type) + + if isinstance(arg_type, torch.ListType): + if not isinstance(raw_arg, (list, tuple)): + raise AssertionError(type(raw_arg)) + list_var = next_tmp("tmp_list") + elem_type = arg_type.getElementType() + dispatch_lines.writeline( + f"c10::impl::GenericList {list_var}({type_expr(elem_type)});" + ) + dispatch_lines.writeline(f"{list_var}.reserve({len(raw_arg)});") + for elem in raw_arg: + dispatch_lines.writeline( + f"{list_var}.emplace_back({codegen_ivalue(elem, elem_type)});" + ) + return f"c10::IValue(std::move({list_var}))" + + if isinstance(arg_type, torch.TupleType): + if not isinstance(raw_arg, (list, tuple)): + raise AssertionError(type(raw_arg)) + tuple_var = next_tmp("tmp_tuple") + dispatch_lines.writeline(f"std::vector {tuple_var};") + dispatch_lines.writeline(f"{tuple_var}.reserve({len(raw_arg)});") + for elem, elem_type in zip(raw_arg, arg_type.elements()): + dispatch_lines.writeline( + f"{tuple_var}.emplace_back({codegen_ivalue(elem, elem_type)});" + ) + return ( + "c10::IValue(c10::ivalue::Tuple::create(" + f"std::move({tuple_var})))" + ) + + if isinstance(arg_type, torch.BoolType): + return ( + "c10::IValue(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, bool)}))" + ) + if isinstance(arg_type, torch.IntType): + return ( + "c10::IValue(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, int)}))" + ) + if isinstance(arg_type, torch.FloatType): + return ( + "c10::IValue(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, float)}))" + ) + if isinstance(arg_type, torch.StringType): + return ( + "c10::IValue(std::string(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, str)}))" + ) + if isinstance(arg_type, torch.SymBoolType): + return ( + "c10::IValue(c10::SymBool(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, bool)})))" + ) + if isinstance(arg_type, torch.SymIntType): + return ( + "c10::IValue(c10::SymInt(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, int)})))" + ) + if isinstance(arg_type, torch.NumberType): + return f"c10::IValue({self.val_to_arg_str_for_prim_type(raw_arg, None)})" + + arg_type_repr = repr(arg_type) + if arg_type_repr == "Layout": + if not isinstance(raw_arg, torch.layout): + raise AssertionError(type(raw_arg)) + return f"c10::IValue({LAYOUT_TO_ATEN[raw_arg]})" + if arg_type_repr == "MemoryFormat": + if not isinstance(raw_arg, torch.memory_format): + raise AssertionError(type(raw_arg)) + return f"c10::IValue({codegen_memory_format(raw_arg)})" + if arg_type_repr == "ScalarType": + if not isinstance(raw_arg, torch.dtype): + raise AssertionError(type(raw_arg)) + return f"c10::IValue({DTYPE_TO_ATEN[raw_arg]})" + if arg_type_repr == "SymFloat": + return ( + "c10::IValue(c10::SymFloat(static_cast(" + f"{self.val_to_arg_str_for_prim_type(raw_arg, float)})))" + ) + + raise AssertionError(f"Unsupported boxed dispatcher arg: {arg_type}") + + stack_var = next_tmp("dispatch_stack") + dispatch_lines.writeline(f"std::vector {stack_var};") + dispatch_lines.writeline( + f"{stack_var}.reserve({len(op_overload._schema.arguments)});" + ) + for raw_arg, schema_arg in zip(raw_args, op_overload._schema.arguments): + dispatch_lines.writeline( + f"{stack_var}.emplace_back({codegen_ivalue(raw_arg, schema_arg.real_type)});" + ) + + dispatch_lines.writeline( + "static auto op = c10::Dispatcher::singleton().findSchemaOrThrow(" + f'"{op_overload._schema.name}", "{op_overload._schema.overload_name}");' + ) + dispatch_lines.writeline(f"op.callBoxed(&{stack_var});") + + stack_idx = 0 + for output_arg, raw_output_arg in zip(output_args, raw_outputs): + if isinstance(raw_output_arg, ir.MutationOutput): + continue + if output_arg is not None: + dispatch_lines.writeline( + f"{output_arg} = torch::aot_inductor::new_tensor_handle(" + f"std::move({stack_var}[{stack_idx}]).toTensor());" + ) + stack_idx += 1 + + dispatch_lines.writeline("}") + self.writelines(dispatch_lines.getvalue().splitlines()) + + def generate_fallback_kernel_with_runtime_lookup_python( + self, + buf_name: str, + python_kernel_name: str, + op_overload: torch._ops.OpOverload, + raw_args: Sequence[Any], + output_args: Sequence[str | None], + raw_outputs: Sequence[ir.Buffer], + ) -> None: + """Generate fallback kernel calls with runtime (non-AOT) dispatch. This can + only be called in cpp_wrapper mode, and assumes that the input is a non-None + OpOverload. + + This function calls into Python to dispatch, which allows it to handle datatypes + that cannot be contained in StableIValue, at the cost of some performance.""" + self.load_custom_op_wrapper() + + num_args = len(raw_args) + py_args_var = f"py_args_{next(self.arg_var_id)}" + # First arg is always the python op name + lines = textwrap.dedent(f""" + RAIIPyObject {py_args_var}(PyTuple_New({num_args + 1})); + if (!{py_args_var}) {{ + throw std::runtime_error("PyTuple_New {py_args_var} failed"); + }} + PyTuple_SetItem({py_args_var}, 0, PyUnicode_FromString("{python_kernel_name}")); + """) + + for idx, (raw_arg, schema_arg) in enumerate( + zip(raw_args, op_overload._schema.arguments) + ): + lines += self.generate_py_arg( + py_args_var, idx + 1, raw_arg, schema_arg.real_type + ) + + lines += textwrap.dedent(f""" + // Call the custom op in Python + RAIIPyObject py_{buf_name}(PyObject_CallObject(custom_op_wrapper, {py_args_var})); + if (!py_{buf_name}) {{ + if (PyErr_Occurred()) {{ + return; + }} + throw std::runtime_error("PyObject_CallObject {python_kernel_name} failed"); + }} + """) + + if raw_outputs: + num_returned_outputs = 0 + returned_output_slots = [] + for output_arg, raw_output_arg in zip(output_args, raw_outputs): + if isinstance(raw_output_arg, ir.MutationOutput): + continue + if output_arg is not None: + returned_output_slots.append((num_returned_outputs, output_arg)) + num_returned_outputs += 1 + else: + num_returned_outputs = len(output_args) + returned_output_slots = [ + (idx, output_arg) + for idx, output_arg in enumerate(output_args) + if output_arg is not None + ] + + # custom_op_wrapper returns a bare capsule only for a single, non-list + # Tensor return. A Tensor[] return (even of length 1) or multiple returns + # come back as a Python list that must be indexed with PyList_GET_ITEM. + schema_returns = op_overload._schema.returns + returns_python_list = len(schema_returns) != 1 or isinstance( + schema_returns[0].real_type, torch.ListType + ) + if ( + num_returned_outputs == 1 + and returned_output_slots + and not returns_python_list + ): + # result is a single tensor + _, output = returned_output_slots[0] + lines += f"{output} = reinterpret_cast(PyCapsule_GetPointer(py_{buf_name}.get(), NULL));\n" + else: + # result is a list of tensors (Tensor[] or multiple returns) + for idx, output_arg in returned_output_slots: + lines += f"{output_arg} = reinterpret_cast(PyCapsule_GetPointer(PyList_GET_ITEM(py_{buf_name}.get(), {idx}), NULL));\n" + + if raw_outputs: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg, raw_output_arg in zip(output_args, raw_outputs) # type: ignore[arg-type] + if output_arg is not None + and not isinstance(raw_output_arg, ir.MutationOutput) + ] + else: + declarations_before_scope = [ + f"RAIIAtenTensorHandle {output_arg};" + for output_arg in output_args # type: ignore[arg-type] + if output_arg is not None + ] + scope_gil_acquire = self.generate_scoped_gil_acquire( + declarations_before_scope, lines + ) + self.writelines(scope_gil_acquire) + + def generate_fallback_kernel_with_runtime_lookup_aot( + self, + op_overload: torch._ops.OpOverload | torch._ops.HigherOrderOperator, + raw_args: Sequence[Any], + output_args: _OUTPUT_ARGS_TYPE, + raw_outputs: Sequence[ir.Buffer], + ) -> None: + ( + tensor_call_args, + int_call_args, + ) = self.generate_extern_kernel_args_decl_if_needed( + op_overload, + raw_args, + output_args, + raw_outputs, + ) + # force both temporary arrays to generate mutable data pointers, since the proxy + # executor signature requires that datatype + int_call_str = self._generate_temporary_array_pointer( + "int64_t", int_call_args, force_mutable=True + ) + tensor_call_args = self.codegen_runtime_lookup_tensor_call_args( + tensor_call_args + ) + tensor_call_str = self._generate_temporary_array_pointer( + "AtenTensorHandle", tensor_call_args, force_mutable=True + ) + + extern_kernel_node_index = len(V.extern_kernel_nodes) - 1 + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_proxy_executor_call_function(proxy_executor, " + f"{extern_kernel_node_index}, " + f"{len(int_call_args)}, " + f"{int_call_str}, " + f"{len(tensor_call_args)}, " + f"{tensor_call_str}));" + ) + + def codegen_runtime_lookup_tensor_call_args( + self, tensor_call_args: Sequence[str] + ) -> Sequence[str]: + return tensor_call_args + + def generate_reset_kernel_saved_flags(self): + pass + + def generate_save_uncompiled_kernels(self): + pass + + def c_type_for_prim_type(self, val, type_) -> str: + if isinstance(type_, torch.OptionalType): + return f"{self.c_type_for_prim_type(val, type_.getElementType())}*" + elif isinstance(type_, torch.TensorType): + return "AtenTensorHandle" + elif isinstance(type_, (torch.IntType, torch.SymIntType)): + return "int64_t" + elif isinstance( + type_, (torch.BoolType, torch.SymBoolType, torch.EnumType) + ) or repr(type_) in ("Layout", "MemoryFormat", "ScalarType"): + return "int32_t" + elif isinstance(type_, torch.FloatType): + return "double" + elif isinstance(type_, torch.NumberType): + if isinstance(val, bool): + return "int32_t" + elif isinstance(val, (int, float)): + return "double" + elif val is None: + # This could happen when val is an optional value + return "double" + else: + raise AssertionError( + f"Unexpected type in c_type_for_prim_type: {type_=}" + ) + elif isinstance(type_, torch.StringType): + return "const char*" + else: + raise AssertionError(f"Unexpected type in c_type_for_prim_type: {type_=}") + + def val_to_arg_str_for_prim_type(self, val, type_) -> str: + # TODO: not using type_ as the first step of refactoring. Will update this later. + if isinstance(val, bool): + return "1" if val else "0" + elif isinstance(val, int): + # uint64_t is long on Linux, but long long on MacOS and Windows + return f"{val}LL" if sys.platform in ["darwin", "win32"] else f"{val}L" + elif isinstance(val, complex): + return f"c10::complex{{ {self.generate_float_value(val.real)}, {self.generate_float_value(val.imag)} }}" + elif isinstance(val, str): + return f'"{val}"' + elif isinstance( + val, (ir.Buffer, ir.ReinterpretView, ir.StorageBox, ir.TensorBox) + ): + return val.codegen_reference() + elif isinstance(val, torch.device): + return self.codegen_device(val) + elif isinstance(val, torch.dtype): + return self.codegen_dtype(val) + elif isinstance(val, torch.layout): + return self.codegen_layout(val) + elif isinstance(val, torch.memory_format): + return self.codegen_memory_format(val) + elif isinstance(val, float): + return self.generate_float_value(val) + elif isinstance(val, (list, tuple)): + # FIXME: This happens because type_ is not always properly set to torch.ListType + return f"{{{', '.join(self.val_to_arg_str(x, None) for x in val)}}}" + elif isinstance(val, SymTypes): + return cexpr(val.node.expr) + elif isinstance(val, sympy.Expr): + return cexpr(val) + else: + return repr(val) + + def val_to_arg_str(self, val, type_=None) -> str: + if val is None: + # None needs special care. It either represent nullopt or an empty tensor + if type_ is None or isinstance(type_, torch.OptionalType): + if type_ is not None and isinstance( + type_.getElementType(), + ( + torch.DeviceObjType, + torch.ListType, + torch.TupleType, + ), + ): + return "nullptr, 0" + return "nullptr" + + if isinstance(type_, torch.TensorType): + # create an empty tensor, the equivalent of at::Tensor() + var_name = f"var_{next(self.arg_var_id)}" + self.writeline(f"AtenTensorHandle {var_name}_handle;") + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_uninitialized_tensor(&{var_name}_handle));" + ) + self.writeline(f"RAIIAtenTensorHandle {var_name}({var_name}_handle);") + return var_name + + raise AssertionError("Can not map None to a known data type") + + if isinstance(type_, torch.OptionalType): + element_type = type_.getElementType() + arg_str = self.val_to_arg_str(val, element_type) + # Handle optional iterables as a special case. Utilize the + # temporary_reference function to avoid saving them off and increasing + # memory usage. + if isinstance(element_type, (torch.ListType, torch.TupleType)): + main_value, aux = arg_str.rsplit(", ", maxsplit=1) + return f"&temporary_reference({main_value}), {aux}" + + # Handle optional tensors as a special case, as above. + if isinstance(element_type, torch.TensorType): + base_handle = self.val_to_arg_str(val, element_type) + return f"&temporary_reference({base_handle}.get())" + + var_name = f"var_{next(self.arg_var_id)}" + if isinstance(element_type, torch.DeviceObjType): + main_value, aux = arg_str.rsplit(", ", maxsplit=1) + self.writeline(f"auto {var_name} = {main_value};") + return f"&{var_name}, {aux}" + + self.writeline( + f"{self.c_type_for_prim_type(val, element_type)} {var_name} = {arg_str};" + ) + return f"&{var_name}" + + if isinstance(type_, (torch.ListType, torch.TupleType)): + if not isinstance(val, (list, tuple)): + raise AssertionError(f"{val} does not match with arg type {type_}") + element_type = type_.getElementType() + + if len(val) == 0: + # Zero-size array is not supported in the C or C++ standard, so return a + # nullptr. + return "nullptr, 0" + + result = [self.val_to_arg_str(x, element_type) for x in val] + if isinstance(element_type, torch.TensorType): + result = [f"{t}.get()" for t in result] + + c_type = self.c_type_for_prim_type(val[0], element_type) + # see the comment in self._generate_temporary_array_pointer for an + # explanation of why this c_type gets modified + if isinstance(element_type, torch.OptionalType) and not c_type.startswith( + "const" + ): + c_type = f"const {c_type}" + + # need to pass the array length, because we can't use the std::array member + # function + return ( + f"{self._generate_temporary_array_pointer(c_type, result)}, {len(val)}" + ) + + val_is_scalar = isinstance(val, (bool, complex, float, int, *SymTypes)) + if isinstance(type_, torch.TensorType) and val_is_scalar: + val_str = self.val_to_arg_str_for_prim_type(val, None) + return self.codegen_scalar_to_tensor(val_str) + + return self.val_to_arg_str_for_prim_type(val, type_) + + def create_tmp_raii_handle_var_if_needed( + self, handle: str, writer: HasWriteLine | list[str] | None = None + ) -> str: + """If the input handle is an rvalue RAII tensor, creates an lvalue variable for + it in writer. Returns a variable name that can be used to access handle.""" + if not handle.startswith( + ( + "borrow_arrayref_tensor_as_tensor(", + "copy_arrayref_tensor_to_tensor(", + "wrap_with_raii_handle_if_needed(", + "RAIIAtenTensorHandle(", + ) + ): + return handle + + tmp_var_name = f"var_{next(self.arg_var_id)}" + call_str = f"auto {tmp_var_name} = {handle};" + + if writer is None: + self.writeline(call_str) + elif isinstance(writer, list): + writer.append(call_str) + else: + writer.writeline(call_str) + + return tmp_var_name + + def write_kernel_context_guard_begin( + self, + ): + # Beginning of a kernel context guarded block. + # The block looks like this: + # { + # KernelContextGuard _ctx("{kernel_name}", {stack_trace_str}); + # ... operations... + # } + self.writeline("{") + + def write_kernel_context_guard_end( + self, + ): + # End of a kernel context guarded block. + self.writeline("}") + + def write_kernel_context_guard( + self, + kernel_name: str, + node_schedule: Sequence[BaseSchedulerNode] | ExternKernel, + ): + def aggregate_stack_traces( + node_schedule: Sequence[BaseSchedulerNode] | ExternKernel, + ) -> OrderedSet[str]: + if isinstance(node_schedule, list): + return functools.reduce( + lambda a, b: a | b, + [ + # pyrefly: ignore [missing-attribute] + node.node.get_stack_traces() + for node in node_schedule + if hasattr(node, "node") and node.node + ], + OrderedSet(), + ) + elif isinstance(node_schedule, ExternKernel): + return node_schedule.get_stack_traces() + else: + return OrderedSet() + + stack_trace_str = 'R"(' + stack_traces = aggregate_stack_traces(node_schedule) + + for stack_trace in stack_traces: + for line in stack_trace.split("\n"): + stack_trace_str += f"\n{line}" + stack_trace_str += "\n" + stack_trace_str += ')"' + self.writeline(f'KernelContextGuard _ctx("{kernel_name}", {stack_trace_str});') diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu_array_ref.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu_array_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..270b9fee9544e6d75311bd99fce78aba1a0fca70 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu_array_ref.py @@ -0,0 +1,1254 @@ +# mypy: allow-untyped-defs +from collections.abc import Callable, Sequence +from typing import Any + +import sympy + +import torch +import torch._inductor.async_compile +import torch._ops +from torch.utils._ordered_set import OrderedSet + +from .. import config, ir +from ..utils import IndentedBuffer, sympy_product +from ..virtualized import V +from .cpp_utils import DTYPE_TO_CPP +from .cpp_wrapper_cpu import CppWrapperCpu +from .wrapper import ( + BufferLike, + EnterSubgraphLine, + ExitSubgraphLine, + MemoryPlanningLine, + MemoryPlanningState, + PythonWrapperCodegen, +) + + +BufferName = str + +# Default thread stack sizes vary by platform: +# - Linux: 8 MB +# - macOS: 512 KB +# - Windows: 1 MB +# Just pick something comfortably smaller than the smallest for now. +MAX_STACK_ALLOCATION_SIZE = 1024 * 100 + + +class CppWrapperCpuArrayRef(CppWrapperCpu): + """ + Generates cpp wrapper for running on CPU and calls cpp kernels + + This class is forked from CppWrapperCpu, with a difference that tensors may be + represented as ArrayRef, see torch/csrc/inductor/aoti_runtime/arrayref_tensor.h + """ + + def __init__(self): + super().__init__() + if self.device != "cpu": + raise AssertionError("ArrayRefTensor only supported on CPU!") + self.allow_stack_allocation = config.aot_inductor.allow_stack_allocation + self.stack_allocated_buffers: dict[BufferName, BufferLike] = {} + self.v2_raw_wrapper_body = IndentedBuffer() + self.v2_raw_output_refs: list[str] | None = None + + @staticmethod + def create( + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: ir.GraphPartitionSignature | None = None, + ): + # TODO - support subgraph codegen by lifting functions. Check the + # comment at CppWrapperCpu `codegen_subgraph` function. + return CppWrapperCpuArrayRef() + + @staticmethod + def get_input_cpp_type(input): + if not config.aot_inductor.use_minimal_arrayref_interface: + raise AssertionError( + "expected config.aot_inductor.use_minimal_arrayref_interface to be set" + ) + + if isinstance(input, sympy.Expr): + from ..graph import may_get_constant_buffer_dtype + + dtype = may_get_constant_buffer_dtype(input) + if dtype is None: + raise AssertionError(f"Failed to get the dtype of sympy.Expr: {input}") + return DTYPE_TO_CPP[dtype] + return f"ArrayRefTensor<{DTYPE_TO_CPP[input.get_dtype()]}>" + + @staticmethod + def get_input_element_cpp_type(input): + if isinstance(input, sympy.Expr): + from ..graph import may_get_constant_buffer_dtype + + dtype = may_get_constant_buffer_dtype(input) + if dtype is None: + raise AssertionError(f"Failed to get the dtype of sympy.Expr: {input}") + return DTYPE_TO_CPP[dtype] + return DTYPE_TO_CPP[input.get_dtype()] + + @staticmethod + def get_device_include_path_jit(device: str) -> str: + if device != "cpu": + raise AssertionError("ArrayRef only supported on CPU!") + return "#include " + + @staticmethod + def get_device_include_path_aot(device: str) -> str: + if device != "cpu": + raise AssertionError("ArrayRef only supported on CPU!") + return "#include " + + def codegen_input_numel_asserts(self, indented_buffer=None): + writer = indented_buffer or self.prefix + for name, buf in V.graph.graph_inputs.items(): + if isinstance(buf, sympy.Expr): + continue + + # comparing strides for 0 size tensor is tricky. Ignore them for now. + if sympy_product(buf.get_size()) == 0: + continue + numel = buf.get_numel() + writer.writeline(f"assert_numel({name}, {numel});") + + def _codegen_assert_size_stride( + self, + code: IndentedBuffer, + name: str, + size: str, + stride: str, + op_name: str, + dtype: torch.dtype | None = None, + ) -> None: + # Inputs/outputs are ArrayRefTensor, not AtenTensorHandle, so + # assert_size_stride would fail to compile. + return + + def _codegen_v2_raw_input_bindings(self, code: IndentedBuffer): + for idx, (input_key, input_value) in enumerate(V.graph.graph_inputs.items()): + input_cpp_type = CppWrapperCpuArrayRef.get_input_element_cpp_type( + input_value + ) + if isinstance(input_value, sympy.Expr): + # cond / symint wrappers can surface symbolic scalar inputs here. + from ..graph import may_get_constant_buffer_dtype + + dtype = may_get_constant_buffer_dtype(input_value) + if dtype is None: + raise AssertionError("Fails to get the dtype of the sympy.Expr") + input_tensor = f"{input_key}_arrayref_tensor" + code.writeline( + f"auto {input_tensor} = torch::aot_inductor::c_to_arrayref_tensor<{input_cpp_type}>(c_inputs[{idx}]);" + ) + self.codegen_tensor_item(dtype, input_tensor, input_key, code) + else: + code.writeline( + f"auto {input_key} = torch::aot_inductor::c_to_arrayref_tensor<{input_cpp_type}>(c_inputs[{idx}]);" + ) + + def _codegen_v2_raw_input_symbols(self, code: IndentedBuffer) -> None: + bound_vars = OrderedSet[sympy.Symbol]() + 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)] + + # Redirect self.prefix so the base class codegen_input_symbol_assignment + # writes into our buffer. + deferred_symbol_assignments = [] + with self._target_buf("prefix", code): + 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) + + for _, value in inputs: + if not isinstance(value, ir.TensorBox): + continue + for expr in [*value.get_size(), *value.get_stride()]: + if not isinstance(expr, sympy.Expr) or isinstance(expr, sympy.Symbol): + continue + undefined_symbols = [ + sym for sym in expr.free_symbols if sym not in bound_vars + ] + if len(undefined_symbols) > 0: + raise AssertionError( + f"For {expr}, expected {undefined_symbols} to have been codegen-ed." + ) + + def _codegen_v2_raw_prelude(self, code: IndentedBuffer): + self._codegen_v2_raw_input_bindings(code) + + if not all( + isinstance(v, torch.Tensor) for v in list(V.graph.constants.values()) + ): + raise AssertionError("Expect all constants to be Tensor") + for idx, constants_key in enumerate(V.graph.constants.keys()): + code.writeline(f"""auto {constants_key} = constants_->at({idx});""") + + self._codegen_v2_raw_input_symbols(code) + + self.codegen_input_numel_asserts(code) + code.writeline( + "[[maybe_unused]] auto& kernels = static_cast(*this->kernels_.get());" + ) + + def _codegen_v2_raw_outputs( + self, code: IndentedBuffer, output_refs: list[str] + ) -> None: + cst_names = V.graph.constants.keys() + + def write_output_to_c_array(idx: int, output: str) -> None: + output_arrayref_name = f"output_arrayref_{idx}" + code.splice( + f""" + std::tuple_element_t<{idx}, AOTInductorModelOutputs> {output_arrayref_name}; + convert_handle_to_arrayref_tensor({output}, {output_arrayref_name}); + torch::aot_inductor::arrayref_tensor_to_c({output_arrayref_name}, c_outputs[{idx}]); + """ + ) + + for idx, output in enumerate(output_refs): + if output == "nullptr": + continue + + is_constant_buffer = output in cst_names + output_buffer = V.graph.graph_outputs[idx] + if isinstance(output_buffer, ir.BaseView): + output_storage = output_buffer.unwrap_view() + if not isinstance(output_storage, (ir.BaseView, ir.MutableBox)): + raise AssertionError( + f"expected output_storage to be BaseView or MutableBox, got " + f"{type(output_storage).__name__}" + ) + if isinstance(output_storage.data, ir.ConstantBuffer): + is_constant_buffer = True + + if isinstance(output_buffer, ir.ShapeAsConstantBuffer): + output_tensor = f"scalar_to_tensor_{next(self.scalar_to_tensor_id)}" + code.writeline( + f"RAIIAtenTensorHandle {output_tensor} = scalar_to_tensor_handle({output});" + ) + write_output_to_c_array(idx, output_tensor) + continue + + output_is_tensor_handle_expr = ( + f"std::is_same_v," + "RAIIAtenTensorHandle> || " + f"std::is_same_v," + "AtenTensorHandle> || " + f"std::is_same_v," + "ConstantHandle>" + ) + code.writeline(f"if constexpr ({output_is_tensor_handle_expr}) {{") + with code.indent(): + cached_output_name = f"cached_output_{next(self.cached_output_id)}" + code.writeline( + f"thread_local RAIIAtenTensorHandle {cached_output_name};" + ) + if is_constant_buffer: + code.splice( + f""" + AtenTensorHandle {cached_output_name}_tmp; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_clone({output}, &{cached_output_name}_tmp)); + {cached_output_name} = {cached_output_name}_tmp; + """ + ) + else: + code.writeline(f"{cached_output_name} = {output}.release();") + write_output_to_c_array(idx, cached_output_name) + code.writeline("} else {") + with code.indent(): + cached_output_name = f"cached_output_{next(self.cached_output_id)}" + output_arrayref_type = f"output_arrayref_{idx}_type" + output_element_type = f"output_arrayref_{idx}_element_type" + output_arrayref_name = f"output_arrayref_{idx}" + code.splice( + f""" + thread_local ThreadLocalCachedOutputArray> + {cached_output_name}{{{output}}}; + {cached_output_name}.copy_data_from({output}); + using {output_arrayref_type} = std::tuple_element_t<{idx}, AOTInductorModelOutputs>; + using {output_element_type} = typename {output_arrayref_type}::value_type; + auto {output_arrayref_name} = {cached_output_name}.arrayref_tensor<{output_element_type}>(); + torch::aot_inductor::arrayref_tensor_to_c({output_arrayref_name}, c_outputs[{idx}]); + """ + ) + code.writeline("}") + + def generate_extern_kernel_alloc(self, *args, **kwargs): + # Disable stack allocation for extern kernels. + self.allow_stack_allocation = False + super().generate_extern_kernel_alloc(*args, **kwargs) + + def generate_extern_kernel_out(self, *args, **kwargs): + # Disable stack allocation for extern kernels. + self.allow_stack_allocation = False + super().generate_extern_kernel_out(*args, **kwargs) + + def generate_fallback_kernel(self, node: ir.FallbackKernel) -> None: + # Disable stack allocation for extern kernels. + self.allow_stack_allocation = False + super().generate_fallback_kernel(node) + + 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=None, + inductor_meta=None, + graph_name="", + original_fxnode_name=None, + current_stream_idx=None, + ): + """ + Generates kernel call code. + + triton: Defines whether the GPU backend uses Triton for codegen. + Otherwise it uses the CUDA language for codegen. + Only valid when cuda == True. + """ + if triton: + raise AssertionError( + "CppWrapperCpuArrayRef.generate_kernel_call does not support GPU" + ) + if not (arg_types is not None and len(call_args) == len(arg_types)): + raise AssertionError( + "Mismatch call_args and arg_types in generate_kernel_call" + ) + new_args = [] + for idx, arg in enumerate(call_args): + if "*" in arg_types[idx]: + var_name = f"var_{next(self.arg_var_id)}" + self.writeline(f"auto* {var_name} = get_data_ptr_wrapper({arg});") + new_args.append(f"({arg_types[idx]})({var_name})") + else: + # arg is a scalar + new_args.append(arg) + # debug printer related logic for cpp kernel type. + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + call_args, + kernel_name, + None, + None, + "cpp", + ) + with debug_printer_manager: + self.writeline(self.wrap_kernel_call(kernel_name, new_args)) + + def write_wrapper_decl(self): + """Declare the generated AOTI wrapper entry points.""" + inputs_len = len(V.graph.graph_inputs.keys()) + if V.graph.aot_mode: + if ( + config.aot_inductor.use_minimal_arrayref_interface + and not V.graph.is_const_graph + ): + input_cpp_types = ", ".join( + f"{CppWrapperCpuArrayRef.get_input_cpp_type(x)}" + for x in V.graph.graph_inputs.values() + ) + output_arrayref_types = ", ".join( + f"ArrayRefTensor<{DTYPE_TO_CPP[x.get_dtype()]}>" + for x in V.graph.graph_outputs + ) + + self.prefix.splice( + f""" + using AOTInductorModelInputs = std::tuple<{input_cpp_types}>; + using AOTInductorModelOutputs = std::tuple<{output_arrayref_types}>; + """ + ) + + if V.graph.const_module: + self.header.splice(V.graph.const_module.wrapper_code.header) + + if V.graph.const_wrapper_code is None: + raise AssertionError( + "expected V.graph.const_wrapper_code to be set" + ) + self.prefix.splice(V.graph.const_wrapper_code) + + if V.graph.const_kernel_code is None: + raise AssertionError("expected V.graph.const_kernel_code to be set") + self.kernel_declarations.splice(V.graph.const_kernel_code) + + if V.graph.is_const_graph: + self.prefix.splice( + """ + void AOTInductorModel::_const_run_impl( + std::vector& output_handles, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) { + """ + ) + else: + if not config.aot_inductor.use_runtime_constant_folding: + # If we do not split the constant graph, we'll just create + # an empty implementation when wrapping the main module. + self.prefix.splice( + """ + void AOTInductorModel::_const_run_impl( + std::vector& output_handles, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) {} + + """ + ) + + run_impl_proto = """ + void AOTInductorModel::run_impl( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles, // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) { + """ + + self.generate_input_output_runtime_checks() + run_impl_proto += """ + __check_inputs_outputs(input_handles, output_handles); + """ + + if config.aot_inductor.use_minimal_arrayref_interface: + self.prefix.splice( + """ + template <> + AOTInductorModelOutputs AOTInductorModel::run_impl_minimal_arrayref_interface< + AOTInductorModelInputs, AOTInductorModelOutputs>( + const AOTInductorModelInputs& inputs, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) { + """ + ) + self.suffix.splice(run_impl_proto) + self.suffix.splice( + """ + AOTInductorModelInputs inputs; + convert_handles_to_inputs(input_handles, inputs); + auto outputs = run_impl_minimal_arrayref_interface( + inputs, stream, proxy_executor); + // NOTE: outputs is full of ArrayRef to thread_local storage. If in the future we need this + // interface to perform well for a DSO using the minimal arrayref interface, all we need + // to do is provide ThreadLocalCachedTensor for each one! + convert_outputs_to_handles(outputs, output_handles); + } + """ + ) + + self.suffix.splice( + """ + extern "C" AOTIRuntimeError AOTInductorModelRunMinimalArrayrefInterface( + AOTInductorModelHandle model_handle, + const AOTInductorModelInputs& inputs, + AOTInductorModelOutputs& outputs) { + auto model = reinterpret_cast(model_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({ + outputs = model->run_impl_minimal_arrayref_interface( + inputs, + (torch::aot_inductor::DeviceStreamType)nullptr, + nullptr); + }) + } + """ + ) + + self.suffix.splice( + f""" + // C-ABI-safe variant: uses flat AOTInductorArrayRefTensor arrays + // instead of std::tuple across the DSO boundary, and + // runs directly on the descriptor arrays to avoid + // DSO-side tuple marshaling. + extern "C" AOTIRuntimeError AOTInductorModelRunMinimalArrayrefInterfaceV2( + AOTInductorModelHandle model_handle, + int32_t num_inputs, + const AOTInductorArrayRefTensor* c_inputs, + int32_t num_outputs, + AOTInductorArrayRefTensor* c_outputs) {{ + constexpr int32_t expected_num_inputs = {len(V.graph.graph_inputs)}; + constexpr int32_t expected_num_outputs = {len(V.graph.graph_outputs)}; + auto model = reinterpret_cast(model_handle); + CONVERT_EXCEPTION_TO_ERROR_CODE({{ + if (num_inputs != expected_num_inputs) {{ + throw std::runtime_error( + std::string("AOTInductorModelRunMinimalArrayrefInterfaceV2 expected ") + + std::to_string(expected_num_inputs) + + " inputs but got " + + std::to_string(num_inputs)); + }} + if (num_outputs != expected_num_outputs) {{ + throw std::runtime_error( + std::string("AOTInductorModelRunMinimalArrayrefInterfaceV2 expected ") + + std::to_string(expected_num_outputs) + + " outputs but got " + + std::to_string(num_outputs)); + }} + if (num_inputs > 0 && c_inputs == nullptr) {{ + throw std::runtime_error( + "AOTInductorModelRunMinimalArrayrefInterfaceV2 received null input descriptors"); + }} + if (num_outputs > 0 && c_outputs == nullptr) {{ + throw std::runtime_error( + "AOTInductorModelRunMinimalArrayrefInterfaceV2 received null output descriptors"); + }} + model->run_impl_minimal_arrayref_interface_v2_raw( + c_inputs, + c_outputs, + (torch::aot_inductor::DeviceStreamType)nullptr, + nullptr); + }}) + }} + """ + ) + else: + self.prefix.splice(run_impl_proto) + else: + # cpp entry function for JIT with cpp wrapper + self.prefix.splice( + """ + void inductor_entry_impl( + AtenTensorHandle* + input_handles, // array of input AtenTensorHandle; handles + // are stolen; the array itself is borrowed + AtenTensorHandle* + output_handles // array for writing output AtenTensorHandle; handles + // will be stolen by the caller; the array itself is + // borrowed) + ) { + """ + ) + with self.prefix.indent(): + # assign inputs and outputs in both cases so the later codegen can be simplified + if not config.aot_inductor.use_minimal_arrayref_interface: + if not V.graph.is_const_graph: + if V.graph.aot_mode: + num_args = len(V.graph.graph_inputs) + else: + # Weights are promoted in the JIT mode + num_args = len(V.graph.graph_inputs) + len(V.graph.constants) + # release GIL to support multiple instances inference (in different threads of the same process) + self.prefix.splice("py::gil_scoped_release_simple release;") + + self.prefix.splice( + f""" + auto inputs = steal_from_raw_handles_to_raii_handles(input_handles, {num_args}); + """ + ) + + if inputs_len != 0: + for idx, input_key in enumerate(V.graph.graph_inputs.keys()): + if config.aot_inductor.use_minimal_arrayref_interface: + self.prefix.writeline( + f"auto {input_key} = std::get<{idx}>(inputs);" + ) + continue + # unwrap input tensor back to scalar + if isinstance(V.graph.graph_inputs[input_key], sympy.Expr): + from ..graph import may_get_constant_buffer_dtype + + dtype = may_get_constant_buffer_dtype( + V.graph.graph_inputs[input_key] # type: ignore[arg-type] + ) + if dtype is None: + raise AssertionError( + "Fails to get the dtype of the sympy.Expr" + ) + self.codegen_tensor_item( + dtype, f"inputs[{idx}]", input_key, self.prefix + ) + else: + self.prefix.writeline( + f"auto {input_key} = std::move(inputs[{idx}]);" + ) + + if not all( + isinstance(v, torch.Tensor) for v in list(V.graph.constants.values()) + ): + raise AssertionError("Expect all constants to be Tensor") + for idx, constants_key in enumerate(V.graph.constants.keys()): + if V.graph.aot_mode: + # Weights are stored in constants_ and owned by RAIIAtenTensorHandle there. + # Don't call std::move here because it will cause constants_ to lose the ownership. + self.prefix.writeline( + f"""auto {constants_key} = constants_->at({idx});""" + ) + else: + # Append constants as inputs to the graph + constants_idx = inputs_len + idx + self.prefix.writeline( + f"auto {constants_key} = std::move(inputs[{constants_idx}]);" + ) + + self.codegen_inputs() + + if V.graph.aot_mode: + if not V.graph.is_const_graph: + if config.aot_inductor.use_minimal_arrayref_interface: + # TODO: input shape checking for regular tensor interface as well? + self.codegen_input_numel_asserts() + else: + self.prefix.writeline("inputs.clear();") + self.prefix.writeline( + "[[maybe_unused]] auto& kernels = static_cast(*this->kernels_.get());" + ) + + def generate_return(self, output_refs: list[str]): + cst_names = V.graph.constants.keys() + arr_iface = ( + not V.graph.is_const_graph + and config.aot_inductor.use_minimal_arrayref_interface + ) # For brevity. + + if arr_iface and V.graph.aot_mode: + self.v2_raw_wrapper_body.clear() + self.v2_raw_wrapper_body.splice(self.wrapper_call) + self.v2_raw_output_refs = list(output_refs) + + def use_thread_local_cached_output_tensor(idx, output): + cached_output_name = f"cached_output_{next(self.cached_output_id)}" + cache_type = "Array" if arr_iface else "Tensor" + self.wrapper_call.writeline( + f"thread_local ThreadLocalCachedOutput{cache_type}> " + f"{cached_output_name}{{{output}}};" + ) + if arr_iface: + self.wrapper_call.writeline( + f"{cached_output_name}.copy_data_from({output});" + ) + output_entry = f"std::get<{idx}>(output_arrayref_tensors)" + element_type = f"std::decay_t" + self.wrapper_call.writeline( + f"{output_entry} = {cached_output_name}.arrayref_tensor<{element_type}>();" + ) + else: + self.wrapper_call.writeline( + f"{cached_output_name}.copy_data_from({output});" + ) + self.wrapper_call.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_uninitialized_tensor(&output_handles[{idx}]));" + ) + self.wrapper_call.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors({cached_output_name}.tensor(), " + f"output_handles[{idx}]));" + ) + + if arr_iface: + self.wrapper_call.writeline( + "AOTInductorModelOutputs output_arrayref_tensors;" + ) + + output2idx: dict[str, int] = {} + for idx, output in enumerate(output_refs): + if output == "nullptr": + continue + + is_constant_buffer = output in cst_names + output_buffer = V.graph.graph_outputs[idx] + if isinstance(output_buffer, ir.BaseView): + output_storage = output_buffer.unwrap_view() + if not isinstance(output_storage, (ir.BaseView, ir.MutableBox)): + raise AssertionError( + f"expected output_storage to be BaseView or MutableBox, got " + f"{type(output_storage).__name__}" + ) + if isinstance(output_storage.data, ir.ConstantBuffer): + is_constant_buffer = True + + if isinstance(output_buffer, ir.ShapeAsConstantBuffer): + # Need to wrap scalar into tensor as the main function returns a vector of tensors + output_tensor = self.codegen_scalar_to_tensor(output) + self.wrapper_call.writeline( + f"output_handles[{idx}] = {output_tensor}.release();" + ) + continue + + output_is_tensor_handle_expr = ( + f"std::is_same_v," + "RAIIAtenTensorHandle> || " + f"std::is_same_v," + "AtenTensorHandle> || " + f"std::is_same_v," + "ConstantHandle>" + ) + self.wrapper_call.writeline( + f"if constexpr ({output_is_tensor_handle_expr}) {{" + ) + with self.wrapper_call.indent(): + if arr_iface: + cached_output_name = f"cached_output_{next(self.cached_output_id)}" + self.wrapper_call.writeline( + f"thread_local RAIIAtenTensorHandle {cached_output_name};" + ) + if is_constant_buffer: + # NOTE(return_constant): In some rare cases where we return + # a constant, we have to return a copy of this constant, + # because (1) constants are not owned by the Model instance + # (2) constants remain the same cross inference runs, + # assuming they are not updated at runtime Basically, we + # cannot release or transfer the ownership of any original + # constant to the user. + self.wrapper_call.writeline( + f"AtenTensorHandle {cached_output_name}_tmp;" + ) + self.wrapper_call.writeline( + "AOTI_TORCH_ERROR_CODE_CHECK(" + f"aoti_torch_clone({output}, &{cached_output_name}_tmp));" + ) + self.wrapper_call.writeline( + f"{cached_output_name} = {cached_output_name}_tmp;" + ) + else: + self.wrapper_call.writeline( + f"{cached_output_name} = {output}.release();" + ) + self.wrapper_call.writeline( + f"convert_handle_to_arrayref_tensor({cached_output_name}, " + f"std::get<{idx}>(output_arrayref_tensors));" + ) + else: + if is_constant_buffer: + # See NOTE(return_constant) above. + self.wrapper_call.writeline( + "AOTI_TORCH_ERROR_CODE_CHECK(" + f"aoti_torch_clone({output}, &output_handles[{idx}]));" + ) + else: + if output in output2idx: + src_idx = output2idx[output] + self.wrapper_call.writeline( + f"output_handles[{idx}] = output_handles[{src_idx}];" + ) + else: + self.wrapper_call.writeline( + f"output_handles[{idx}] = {output}.release();" + ) + self.wrapper_call.writeline("} else {") + with self.wrapper_call.indent(): + use_thread_local_cached_output_tensor(idx, output) + self.wrapper_call.writeline("}") + + if output not in output2idx: + output2idx[output] = idx + if arr_iface: + self.wrapper_call.writeline("return output_arrayref_tensors;") + + def generate_before_suffix(self, result): + super().generate_before_suffix(result) + if self.v2_raw_output_refs is None: + return + + raw_impl = IndentedBuffer() + raw_impl.splice( + """ + void AOTInductorModel::run_impl_minimal_arrayref_interface_v2_raw( + const AOTInductorArrayRefTensor* c_inputs, + AOTInductorArrayRefTensor* c_outputs, + DeviceStreamType stream, + AOTIProxyExecutorHandle proxy_executor + ) { + """ + ) + with raw_impl.indent(): + self._codegen_v2_raw_prelude(raw_impl) + raw_impl.splice(self.v2_raw_wrapper_body) + self._codegen_v2_raw_outputs(raw_impl, self.v2_raw_output_refs) + raw_impl.writeline( + "} // AOTInductorModel::run_impl_minimal_arrayref_interface_v2_raw" + ) + result.splice(raw_impl) + + def memory_plan(self): + from .memory_planning import MemoryPlanner + + self.lines = MemoryPlanner(self).plan(self.lines) + # TODO: integrate memory planning & stack allocation? + self.allow_stack_allocation = False + + def memory_plan_reuse(self): + out_names = V.graph.get_output_names() + + 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 = [] + 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()) + elif isinstance(line, ExitSubgraphLine): + past_planning_states.append(planning_states.pop()) + past_planning_states.append(planning_states.pop()) + if len(planning_states) != 0: + raise AssertionError( + f"expected planning_states to be empty, got {len(planning_states)}" + ) + + # conservatively use the sum of all allocated buffer sizes + # in potentially nested scopes as the total allocated size + total_allocated_buffer_size = sum( + s.total_allocated_buffer_size for s in past_planning_states + ) + + self.allow_stack_allocation = ( + self.allow_stack_allocation is not False + and config.aot_inductor.allow_stack_allocation + and total_allocated_buffer_size <= MAX_STACK_ALLOCATION_SIZE + ) + + def can_stack_allocate_buffer(self, buffer): + return ( + self.allow_stack_allocation + and buffer.get_device().type == "cpu" + and self.can_prove_buffer_has_static_shape(buffer) + and ir.is_contiguous_strides_for_shape( + buffer.get_stride(), buffer.get_size() + ) + ) + + def make_buffer_free(self, buffer): + return ( + "" + if isinstance(buffer.get_output_spec(), ir.MultiOutputLayout) + or (V.graph.aot_mode and buffer.get_name() in self.stack_allocated_buffers) + or ( + config.aot_inductor.use_minimal_arrayref_interface + and V.graph.aot_mode + and buffer.get_name() in V.graph.graph_inputs + ) + else f"{buffer.get_name()}.reset();" + ) + + def make_buffer_allocation(self, buffer): + return self.make_allocation( + buffer.get_name(), + buffer.get_device(), + buffer.get_dtype(), + buffer.get_size(), + buffer.get_stride(), + buffer if self.can_stack_allocate_buffer(buffer) else None, + buffer.get_is_pinned(), + ) + + def make_allocation( + self, + name, + device, + dtype, + shape, + stride, + buffer_if_can_stack_allocate=None, + is_pinned=False, + ): + orig_stride = stride + device_str = self.codegen_device(device) + dtype_code = self.codegen_dtype(dtype) + size = self.codegen_shape_tuple(shape) + stride = self.codegen_shape_tuple(orig_stride) + size_array_var = self.codegen_int_array_var( + size, + self.wrapper_call.writeline, + known_statically=self.is_statically_known_list_of_ints(shape), + graph=self.get_codegened_graph(), + ) + stride_array_var = self.codegen_int_array_var( + stride, + self.wrapper_call.writeline, + known_statically=self.is_statically_known_list_of_ints(orig_stride), + graph=self.get_codegened_graph(), + ) + device_type, device_id = device_str.split(",") + device_idx = self.codegen_device_idx(device, device_id) + if buffer_if_can_stack_allocate is not None: + self.stack_allocated_buffers[name] = buffer_if_can_stack_allocate + cpp_type = DTYPE_TO_CPP[dtype] + numel = buffer_if_can_stack_allocate.get_numel() + # Note: we don't zero storage because empty_strided doesn't zero either. + self.wrapper_call.writeline(f"{cpp_type} {name}_storage[{numel}];") + args = [ + f"{name}_storage", + size_array_var, + stride_array_var, + device_type, + device_idx, + ] + return f"ArrayRefTensor<{cpp_type}> {name}({', '.join(args)});" + + args = [ + str(len(shape)), + size_array_var, + stride_array_var, + dtype_code, + device_type, + device_idx, + f"&{name}_handle", + ] + + self.wrapper_call.writeline(f"AtenTensorHandle {name}_handle;") + pinned_str = "_pinned" if is_pinned else "" + self.wrapper_call.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided{pinned_str}({', '.join(args)}));" + ) + + return f"RAIIAtenTensorHandle {name}({name}_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(): + if old_name in self.stack_allocated_buffers: + self.stack_allocated_buffers[new_name] = new + 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 + ) + if reinterpret_view in self.stack_allocated_buffers: + self.stack_allocated_buffers[new_name] = new + # The only way to get into this case is via an exact buffer reuse, since all + # other options result in a new tensor handle. + return self.codegen_exact_buffer_reuse(old_name, new_name, del_line) + return f"{self.declare}{new_name} = {reinterpret_view}{del_line} // reuse" + + def _assert_safe_to_use_borrow_arrayref_tensor_as_tensor(self): + # Borrowing arguments to shim functions is only safe because we know + # that the arguments can't be stack-allocated. Otherwise, to be sure + # we can't return a dangling pointer, we need to either 1) be + # certain that the shim function cannot return an alias of a + # borrowed argument, or 2) be certain that the returned Tensor from + # the shim function cannot escape. + if not self.is_safe_to_use_borrow_arrayref_tensor_as_tensor(): + raise AssertionError( + "borrowing arguments to shim functions is unsafe with " + "stack allocation on! (see comment above this assertion)" + ) + + def is_safe_to_use_borrow_arrayref_tensor_as_tensor(self): + return not self.allow_stack_allocation and not self.stack_allocated_buffers + + def codegen_subgraph_prefix(self, subgraph, outer_inputs, outer_outputs): + if len(subgraph.graph.graph_inputs) != len(outer_inputs): + raise AssertionError( + f"expected {len(outer_inputs)} subgraph inputs, got " + f"{len(subgraph.graph.graph_inputs)}" + ) + + for (inner_input, inner_input_val), outer_input in zip( + subgraph.graph.graph_inputs.items(), outer_inputs + ): + if not isinstance(inner_input_val, ir.TensorBox): + continue + + # Wrap with a generic lambda so if constexpr can discard the + # ill-formed branch (if constexpr only discards in dependent + # contexts, i.e. templates / generic lambdas). + self.writeline(f"AtenTensorHandle {inner_input}_handle;") + self.writeline( + f"[&](auto&& _t) {{ " + f"if constexpr (::torch::aot_inductor::is_arrayref_tensor_type_v" + f">) {{ " + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors_out(" + f"borrow_arrayref_tensor_as_tensor(_t), &{inner_input}_handle)); " + f"}} else {{ " + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors_out(" + f"_t, &{inner_input}_handle)); " + f"}} }}({outer_input});" + ) + self.writeline(f"RAIIAtenTensorHandle {inner_input}({inner_input}_handle);") + + def codegen_while_loop(self, while_loop, stack_output=False): + if stack_output: + raise NotImplementedError("NYI cpp wrapper for while_loop_stack_output") + is_bool_pred = isinstance( + while_loop.cond_subgraph.graph.graph_outputs[0], ir.ShapeAsConstantBuffer + ) + 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 + ] + carried_output_names = self._get_while_loop_carried_output_names(while_loop) + cond_result_name = f"{name}_cond_result" + if is_bool_pred: + self.writeline(f"bool {cond_result_name};") + else: + self.writeline(f"RAIIAtenTensorHandle {cond_result_name};") + + cond_outer_inputs = [] + for inp, out_name in zip(outer_carried_inputs, carried_output_names): + self.writeline(f"AtenTensorHandle {out_name}_handle;") + self.writeline( + "AOTI_TORCH_ERROR_CODE_CHECK(" + f"aoti_torch_assign_tensors_out(borrow_arrayref_tensor_as_tensor({inp}), " + f"&{out_name}_handle));" + ) + self.writeline(f"RAIIAtenTensorHandle {out_name}({out_name}_handle);") + cond_outer_inputs.append(out_name) + + cond_outer_inputs.extend(outer_additional_inputs) + + cond_outer_outputs = [cond_result_name] + body_outer_inputs = list(cond_outer_inputs) + body_outer_outputs = body_outer_inputs[: len(outer_carried_inputs)] + + self.writeline("while (1) {") + self.writeline(EnterSubgraphLine(self, while_loop.cond_subgraph.graph)) + self.codegen_subgraph( + while_loop.cond_subgraph, cond_outer_inputs, cond_outer_outputs + ) + + if is_bool_pred: + cond_result = f"{cond_result_name}" + else: + cond_result = f"{cond_result_name}_scalar" + self.codegen_tensor_item(torch.bool, cond_result_name, cond_result) + self.writeline(f"if (!{cond_result}) break;") + + self.writeline(ExitSubgraphLine(self)) + self.writeline(EnterSubgraphLine(self, while_loop.body_subgraph.graph)) + self.codegen_subgraph( + while_loop.body_subgraph, body_outer_inputs, body_outer_outputs + ) + self.writeline(ExitSubgraphLine(self)) + self.writeline("}") + + def generate_c_shim_extern_kernel_call( + self, kernel: str, args: list[str], device: str, **_ + ) -> None: + # In the abi_compatible mode, we call fallback aten ops through a C shim layer + # Setting self.allow_stack_allocation to False because the exchange between + # ArrayRefTensor and at::Tensor is still fragile. + self.allow_stack_allocation = False + + wrapped_args = [] + for arg in args: + # We only really *need* borrow_arrayref_tensor_as_tensor for + # ArrayRefTensors. The code flowing into here uses `0` for nullptr, which + # borrow_arrayref_tensor_as_tensor would blindly coerce to int, so just + # avoid wrapping integers. Name matching is to find tensor is hacky, but + # fixing all the ArrayRefTensor issues is not a priority for now. + if isinstance(arg, str) and arg.startswith( + ("buf", "arg", "wrap_with_raii_handle_if_needed") + ): + self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor() + arg = f"borrow_arrayref_tensor_as_tensor({arg})" + wrapped_args.append(arg) + + super().generate_c_shim_extern_kernel_call( + kernel, wrapped_args, device, debug_args=args + ) + + def generate_scatter_fallback(self, node: ir.ScatterFallback): + # No stack allocation when there is a fallback op + self.allow_stack_allocation = False + super().generate_scatter_fallback(node) + + def _generate_scatter_fallback_args(self, inputs: Sequence[Any]) -> list[str]: + self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor() + return [ + f"borrow_arrayref_tensor_as_tensor({x})" if isinstance(x, str) else str(x) + for x in inputs + ] + + def generate_index_put_fallback(self, node: ir.IndexPutFallback) -> None: + # No stack allocation when there is a fallback op + self.allow_stack_allocation = False + super().generate_index_put_fallback(node) + + def _generate_index_put_fallback(self, kernel, x, indices, values, accumulate): + self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor() + # TODO: update aoti_torch_index_put_out in ir.py to use autogen out version + # See the comment in codegen_reinterpret_view about why having something like + # RAIIAtenTensorHandle(tmp_tensor_handle_2) in a tmp array can cause the corresponding + # tensor prematurely deallocated, thus the temporary array trick here. + indices_str = self._generate_temporary_array_pointer( + "AtenTensorHandle", + [f"borrow_arrayref_tensor_as_tensor({i})" for i in indices], + ) + args = [ + f"borrow_arrayref_tensor_as_tensor({x})", + indices_str, + str(len(indices)), + f"borrow_arrayref_tensor_as_tensor({values})", + accumulate, + ] + args.insert( + 0, f"borrow_arrayref_tensor_as_tensor({x})" + ) # set x as the output tensor, this fallback mutates x. + # Wrap in AOTI_TORCH_ERROR_CODE_CHECK so a shim failure surfaces instead + # of being silently swallowed. + self.writeline(f"AOTI_TORCH_ERROR_CODE_CHECK({kernel}({', '.join(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: + # No stack allocation when there is a fallback op + self.allow_stack_allocation = False + super().generate_fallback_kernel_with_runtime_lookup( + buf_name, python_kernel_name, get_args, op_overload, raw_args, outputs + ) + + def codegen_runtime_lookup_tensor_call_args( + self, tensor_call_args: Sequence[str] + ) -> Sequence[str]: + self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor() + return [f"borrow_arrayref_tensor_as_tensor({arg})" for arg in tensor_call_args] + + def codegen_device_copy(self, src, dst, non_blocking: bool | str): + # aoti_torch_tensor_copy_ takes AtenTensorHandle as input, + # while stack-allocation results in ArrayRefTensor + # so disable stack allocation here + self.allow_stack_allocation = False + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_copy_(expensive_copy_to_tensor_if_needed({dst}), {src}, {non_blocking}));" + ) + + def codegen_reinterpret_view( + self, + data, + size, + stride, + offset, + writeline: Callable[..., None], + dtype=None, + ) -> str: + """Returns a newly-created, temporary RAII tensor handle containing the + reinterpreted tensor data. Callers of this function are responsible for saving + the handle if persistent access is needed.""" + dim = str(len(size)) + + def create_reinterpret_call() -> str: + args = [ + f"{data.get_name()}", + dim, + self.codegen_int_array_var( + self.codegen_shape_tuple(size), + writeline, + known_statically=self.is_statically_known_list_of_ints(size), + graph=self.get_codegened_graph(), + ), + self.codegen_int_array_var( + self.codegen_shape_tuple(stride), + writeline, + known_statically=self.is_statically_known_list_of_ints(stride), + graph=self.get_codegened_graph(), + ), + offset, + ] + return f"wrap_with_raii_handle_if_needed(reinterpret_tensor_wrapper({', '.join(args)}))" + + def create_new_tensor_handle() -> tuple[str, list[str]]: + # Calling reset() on ArrayRefTensor does nothing, since the array is + # const-allocated on the stack. Thus, it's safe to return a reference to + # the original array. + if (name := data.get_name()) in self.stack_allocated_buffers: + return name, [] + + tmp_AtenTensorHandle = f"tmp_{name}_{next(self.tmp_tensor_id)}" + tmp_call_strs = [ + f"AtenTensorHandle {tmp_AtenTensorHandle};", + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_tensor_handle({data.get_name()}, &{tmp_AtenTensorHandle}));", + ] + return f"RAIIAtenTensorHandle({tmp_AtenTensorHandle})", tmp_call_strs + + if ( + size == data.layout.size + and stride == data.layout.stride + and offset == data.layout.offset + and (dtype is None or dtype == data.dtype) + ): + final_tensor_str, call_strs = create_new_tensor_handle() + for line in call_strs: + writeline(line) + return final_tensor_str + + return super().codegen_reinterpret_view( + data, size, stride, offset, writeline, dtype + ) + + def val_to_arg_str(self, val, type_=None) -> str: + if ( + val is not None + and isinstance(type_, torch.OptionalType) + and isinstance(type_.getElementType(), torch.TensorType) + ): + # Handle optional tensors as a special case, as in the parent class. + base_handle = self.val_to_arg_str(val, torch.TensorType) + if config.aot_inductor.use_minimal_arrayref_interface: + if self.is_safe_to_use_borrow_arrayref_tensor_as_tensor(): + base_handle = f"borrow_arrayref_tensor_as_tensor({base_handle})" + else: + base_handle = f"copy_arrayref_tensor_to_tensor({base_handle})" + return f"&temporary_reference({base_handle}.get())" + + return super().val_to_arg_str(val, type_) + + def codegen_tensor_item( + self, dtype: torch.dtype, tensor: str, scalar: str, indented_buffer=None + ): + dtype_str = str(dtype).split(".")[-1] + writer = indented_buffer or self + + if dtype == torch.float16 or dtype == torch.bfloat16: + scalar_tmp = f"{scalar}_tmp" + writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar_tmp};") + + # We know that item_ doesn't alias the input, so borrowing should be safe. + tensor = f"borrow_arrayref_tensor_as_tensor({tensor})" + + writer.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar_tmp}));" + ) + writer.writeline(f"float {scalar} = float({scalar_tmp});") + else: + writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar};") + + # We know that item_ doesn't alias the input, so borrowing should be safe. + tensor = f"borrow_arrayref_tensor_as_tensor({tensor})" + + writer.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar}));" + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_gpu.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..ea66a2f109c7de003c903012d3ff37402d1da2e6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_gpu.py @@ -0,0 +1,1886 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import dataclasses +import os +import re +import sys +from itertools import count, zip_longest +from typing import Any, cast +from typing_extensions import Self + +import sympy + +import torch +from torch import dtype as torch_dtype +from torch._inductor.codecache import get_cpp_wrapper_cubin_path_name +from torch._inductor.runtime.runtime_utils import dynamo_timed +from torch.utils._ordered_set import OrderedSet + +from .. import config +from ..codecache import CudaKernelParamCache +from ..ir import ( + GraphPartitionSignature, + TensorBox, + TMADescriptorExperimental, + TMADescriptorStable, +) +from ..runtime.hints import ( + InductorMeta, + TRITON_DEFAULT_BLOCK_SIZES, + TRITON_DEFAULT_RSPLIT, + TRITON_DEFAULT_RSPLIT_SIZE, + TritonMeta, +) +from ..stream_utils import ( + AOTI_SUPPORTED_STREAM_OP_NAMES, + AOTI_UNSUPPORTED_STREAM_OP_REASONS, + get_stream_name, +) +from ..utils import ( + cache_on_self, + DeferredLineBase, + get_gpu_type, + GPU_ALIGN_BYTES, + IndentedBuffer, + make_codegen_buffer, + XPU_KERNEL_FORMAT, +) +from ..virtualized import V +from .aoti_hipify_utils import maybe_hipify_code_wrapper +from .common import get_device_op_overrides, TritonScratchWorkspace +from .cpp_utils import cexpr +from .cpp_wrapper_cpu import CppWrapperCpu +from .multi_kernel import MultiKernelCall +from .triton_utils import should_unwrap_unspec_arg +from .wrapper import PythonWrapperCodegen, SymbolicCallArg + + +_cpp_string_literal_escapes = { + "\\": "\\\\", + '"': '\\"', + "\n": "\\n", + "\t": "\\t", + "\r": "\\r", +} +_cpp_string_literal_pattern = re.compile(r'["\\\n\t\r]') + + +def cpp_string_literal(s: str) -> str: + escaped = _cpp_string_literal_pattern.sub( + lambda match: _cpp_string_literal_escapes[match.group(0)], s + ) + return f'"{escaped}"' + + +def generate_aoti_kernel_config_header(kernel_names: list[str]) -> str: + """Generate a C header defining macros for each lazy-compiled kernel. + + Called after the JIT first-pass runs and populates CudaKernelParamCache. + The AOTI compilation includes this header so that LazyKernelCompileResult + structs get compile-time-initialized with the autotuned values. + """ + + def braced(values: list[int]) -> str: + return "{" + ", ".join(str(v) for v in values) + "}" + + buf = IndentedBuffer() + buf.splice(""" + #pragma once + // Auto-generated kernel configurations for AOTInductor lazy compile. + """) + + for kernel_name in kernel_names: + params = CudaKernelParamCache.get(kernel_name) + if params is None: + raise RuntimeError( + "When autotune_at_compile_time is False, AOTInductor generates" + " both JIT code and AOT code. They are expected to have exactly" + f" the same kernels. However, AOT code contains kernels, {kernel_names}," + " that is not in the JIT code." + ) + + macro_prefix = kernel_name.upper() + cubin_path = cpp_string_literal(params[get_cpp_wrapper_cubin_path_name()]) + mangled_name = cpp_string_literal(params["mangled_name"]) + num_warps = params["num_warps"] + shared_mem = params["shared_mem"] + + # params["config"] is already a dict (from config_to_dict in CachingAutotuner) + config_dict = params.get("config") or {} + + # For combo/foreach kernels, merge default_config + inductor_meta = params.get("inductor_meta") or {} + combo_grid_meta = inductor_meta.get("combo_grid_meta") + default_config = ( + combo_grid_meta.get("default_config") if combo_grid_meta else None + ) + if default_config: + config_dict = {**default_config, **config_dict} + + config_index: int | None = None + grid_type = inductor_meta.get("grid_type") + if grid_type == "PrecomputedGrid": + precomputed_grids = inductor_meta.get("precomputed_grids", []) + for idx, entry in enumerate(precomputed_grids): + entry_config = entry.get("config", {}) + if all(config_dict.get(k) == v for k, v in entry_config.items()): + config_index = idx + break + + # Per-subkernel block sizes for combo kernels, or single-element lists. + num_kernels = combo_grid_meta.get("num_kernels", 1) if combo_grid_meta else 1 + if num_kernels > 1 and "XBLOCK_0" in config_dict: + xblocks = [ + config_dict.get(f"XBLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["XBLOCK"]) + for i in range(num_kernels) + ] + yblocks = [ + config_dict.get(f"YBLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["YBLOCK"]) + for i in range(num_kernels) + ] + zblocks = [ + config_dict.get(f"ZBLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["ZBLOCK"]) + for i in range(num_kernels) + ] + r0blocks = [ + config_dict.get(f"R0_BLOCK_{i}", TRITON_DEFAULT_BLOCK_SIZES["R0_BLOCK"]) + for i in range(num_kernels) + ] + else: + xblocks = [config_dict.get("XBLOCK", TRITON_DEFAULT_BLOCK_SIZES["XBLOCK"])] + yblocks = [config_dict.get("YBLOCK", TRITON_DEFAULT_BLOCK_SIZES["YBLOCK"])] + zblocks = [config_dict.get("ZBLOCK", TRITON_DEFAULT_BLOCK_SIZES["ZBLOCK"])] + r0blocks = [ + config_dict.get("R0_BLOCK", TRITON_DEFAULT_BLOCK_SIZES["R0_BLOCK"]) + ] + rsplit = config_dict.get("RSPLIT", TRITON_DEFAULT_RSPLIT) + rsplit_size = config_dict.get("RSPLIT_SIZE", TRITON_DEFAULT_RSPLIT_SIZE) + ci = config_index if config_index is not None else -1 + gs = params.get("global_scratch", -1) or -1 + ps = params.get("profile_scratch", -1) or -1 + + buf.writeline("") + buf.splice(f""" + // Kernel: {kernel_name} + #define {macro_prefix}_CUBIN_PATH {cubin_path} + #define {macro_prefix}_MANGLED_NAME {mangled_name} + #define {macro_prefix}_NUM_WARPS {num_warps} + #define {macro_prefix}_SHARED_MEM {shared_mem} + #define {macro_prefix}_XBLOCKS {braced(xblocks)} + #define {macro_prefix}_YBLOCKS {braced(yblocks)} + #define {macro_prefix}_ZBLOCKS {braced(zblocks)} + #define {macro_prefix}_R0BLOCKS {braced(r0blocks)} + #define {macro_prefix}_RSPLIT {rsplit} + #define {macro_prefix}_RSPLIT_SIZE {rsplit_size} + #define {macro_prefix}_CONFIG_INDEX {ci} + #define {macro_prefix}_GLOBAL_SCRATCH {gs} + #define {macro_prefix}_PROFILE_SCRATCH {ps} + """) + + return buf.getvalue() + + +TRITON_SIGNATURE_TO_CPP = { + "i32": "int32_t", + "i64": "int64_t", + "fp32": "float", + "fp64": "double", +} + + +def signature_is_tma_desc(sig: str | None) -> bool: + """Check if a Triton signature represents a TMA descriptor.""" + if not sig: + return False + if sig == "nvTmaDesc": + return True + if sig.startswith("tensordesc<"): + return True + return False + + +def _unpack_tma_descriptor_args(var_name: str, sig_type: str) -> list[str]: + """Unpack a StableTMADescriptor into kernel launch args. + + Given a variable name holding a StableTMADescriptor and its tensordesc<...> + signature, returns the list of pointer args: &var.m, &var.block_shape[i]..., + &var.strides[i]... + """ + match = re.match(r"tensordesc<[^[]*\[([^\]]*)\]", sig_type) + if match is None: + raise AssertionError(f"Cannot parse tensordesc signature: {sig_type}") + ndim = match.group(1).count(",") + 1 + result = [f"&{var_name}.m"] + for i in range(ndim): + result.append(f"&{var_name}.block_shape[{i}]") + for i in range(ndim): + result.append(f"&{var_name}.strides[{i}]") + return result + + +class _LazyTritonCompileKickoffLine(DeferredLineBase): + def __init__(self, lazy_kernel_names: list[str], line: str): + super().__init__(line) + self.lazy_kernel_names = lazy_kernel_names + + def __call__(self) -> str | None: + return self.line if self.lazy_kernel_names else None + + def _new_line(self, line: str) -> _LazyTritonCompileKickoffLine: + return _LazyTritonCompileKickoffLine(self.lazy_kernel_names, line) + + +@dataclasses.dataclass +class DeferredTritonCallWrapper: + """ + When using cpp wrapper, GPU kernel load and launch needs to wait for Triton kernels + to be tuned and stored as cubin files, so use a deferred generating the final wrapper around + the triton kernel until right before the prefix is written. + """ + + wrapper_name: str + kernel_name: str + kernel_name_to_body: dict[str, str] + arg_types: list[Any] + triton_meta: TritonMeta | None = None + inductor_meta: dict[str, Any] | None = None + tma_tensor_args: dict[str, str] = dataclasses.field(default_factory=dict) + + @cache_on_self + def _get_tma_args(self) -> dict[str, str]: + """Get mapping of TMA descriptor arg names to their signature types.""" + triton_meta = self.triton_meta or {} + signature = triton_meta.get("signature", {}) + for name, sig_type in signature.items(): + if 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." + ) + return { + name: sig_type + for name, sig_type in signature.items() + if isinstance(sig_type, str) and sig_type.startswith("tensordesc<") + } + + def _get_cpp_param_type( + self, name: str, arg_type: Any, signature: dict[str, str] | None = None + ) -> str: + """Get the C++ parameter declaration for a given arg type.""" + if isinstance(arg_type, (torch_dtype, UnwrapUnspecArg)): + # TMA descriptors need non-const references since their fields + # are passed as void* pointers to kernel launch args + if signature and signature_is_tma_desc(signature.get(name)): + return f"{name}_type_& {name}" + return f"const {name}_type_& {name}" + elif issubclass(arg_type, (SymbolicCallArg, sympy.Expr, int)): + return f"int64_t {name}" + elif arg_type is float: + return f"float {name}" + elif arg_type is bool: + return f"bool {name}" + else: + raise ValueError(f"Unexpected arg type {arg_type}") + + def _write_wrapper_signature( + self, + prefix: IndentedBuffer, + wrapper: CppWrapperGpu, + arg_names: list[str], + arg_types: list[Any] | None = None, + signature: dict[str, str] | None = None, + ) -> None: + """Write the wrapper function signature including template and parameters.""" + if arg_types is None: + arg_types = self.arg_types + + template_types = [ + f"typename {name}_type_" + for name, arg_type in zip(arg_names, arg_types) + if isinstance(arg_type, (torch_dtype, UnwrapUnspecArg)) + ] + if template_types: + prefix.writeline_jit(f"template <{', '.join(template_types)}>") + prefix.writeline_aot( + f"template <{', '.join([*template_types, 'typename kernels_type_'])}>" + ) + + cubin_dir_param = "const std::optional& cubin_dir_ = std::nullopt" + kernels_param = "kernels_type_& kernels_" + + shared_params = [ + self._get_cpp_param_type(name, arg_type, signature) + for name, arg_type in zip(arg_names, arg_types) + ] + shared_params.append("int32_t device_idx_") + shared_params.append( + maybe_hipify_code_wrapper( + f"{wrapper.device_codegen.cpp_stream_type()} stream_" + ) + ) + + def emit(writer, params): + for p in params[:-1]: + writer(f"{p},") + writer(params[-1]) + + prefix.writeline(f"static __attribute__((noinline)) void {self.wrapper_name}(") + with prefix.indent(): + emit(prefix.writeline_jit, [*shared_params, cubin_dir_param]) + emit(prefix.writeline_aot, [*shared_params, kernels_param, cubin_dir_param]) + prefix.writeline("){") + + def generate(self, wrapper: CppWrapperGpu): + """ + Generate the GPU kernel definition, as well as load and launch code. + """ + prefix = wrapper.prefix + if self.kernel_name.startswith("multi_kernel_"): + # MultiKernel will select one kernel after running the autotune block + self.kernel_name = MultiKernelCall.lookup_choice(self.kernel_name) + + # Defer compilation to runtime if autotune_at_compile_time is False (JIT only). + # AOTI lazy-compile emission is wired up later in the stack. + if config.triton.autotune_at_compile_time is False: + return self.generate_lazy(wrapper) + + params = CudaKernelParamCache.get(self.kernel_name) + if not params: + raise AssertionError( + f"CudaKernelParamCache not populated for {self.kernel_name}" + ) + def_args = params["def_args"] + arg_types = self.arg_types + inductor_meta = params["inductor_meta"] + + if "extra_launcher_args" in inductor_meta and len(def_args) > len(arg_types): + # extra_launcher_args should already be in def_args + if len(def_args) != len(arg_types) - len( + inductor_meta["extra_launcher_args"] + ): + raise AssertionError( + "expected len(def_args) == len(arg_types) - " + f"len(extra_launcher_args), got {len(def_args)}" + ) + arg_types = arg_types + [SymbolicCallArg] * len( + inductor_meta["extra_launcher_args"] + ) + + if not V.graph.aot_mode: + prefix.writeline( + maybe_hipify_code_wrapper( + f"static {wrapper.device_codegen.cpp_kernel_type()} {self.kernel_name} = nullptr;" + ) + ) + kernel_var_name = self.kernel_name + else: + kernel_var_name = f"kernels_.{self.kernel_name}" + + # Write wrapper function signature + self._write_wrapper_signature(prefix, wrapper, def_args, arg_types) + + with prefix.indent(): + if V.graph.aot_mode: + # Emit the original Triton kernel for debugging purposes + prefix.writeline("/*") + prefix.splice(self.kernel_name_to_body[self.kernel_name]) + prefix.writeline("*/") + self.generate_grid(prefix, inductor_meta, params) + self.generate_load_kernel(prefix, kernel_var_name, params) + self.generate_launch_kernel(prefix, wrapper, kernel_var_name, params) + prefix.writeline("}") + + if not config.aot_inductor.embed_kernel_binary: + # Ensure the cubin file is included in the package + V.graph.wrapper_code.additional_files.append( + params[get_cpp_wrapper_cubin_path_name()] + ) + + def _resolve_lazy_arg_names(self) -> tuple[list[str], list[str]]: + """Compute wrapper and kernel arg names from triton_meta signature. + + Returns (wrapper_arg_names, kernel_arg_names) where: + - wrapper_arg_names: params accepted by the C++ wrapper function + - kernel_arg_names: params passed to the GPU kernel launch (non-constexpr only) + """ + if self.triton_meta is None: + raise AssertionError( + f"triton_meta is required for lazy compile of {self.kernel_name}" + ) + signature = self.triton_meta.get("signature", {}) + inductor_meta = self.inductor_meta or {} + extra_launcher_args_count = len(inductor_meta.get("extra_launcher_args", [])) + tma_tensor_args = self.tma_tensor_args + num_tma_tensor_args = len(tma_tensor_args) + + # Matches internal config params like XBLOCK, RSPLIT_SIZE, and their + # per-subkernel variants like XBLOCK_0, YBLOCK_1. + internal_config_re = re.compile(r"(?:BLOCK|RSPLIT_SIZE|RSPLIT)(?:_\d+)?$") + # Declared constexpr params (tl.constexpr in kernel signature) are excluded + # from arg_types for user-defined kernels, while value-based constexpr params + # (e.g. numel=1, arg=None) are still in arg_types. + declared_constexpr_names = OrderedSet( + inductor_meta.get("declared_constexpr_names", []) + ) + wrapper_arg_names = [] + kernel_arg_names = [] + for name, sig_type in signature.items(): + if internal_config_re.search(name): + continue + if sig_type != "constexpr": + kernel_arg_names.append(name) + if name not in declared_constexpr_names: + wrapper_arg_names.append(name) + + num_wrapper_args = ( + len(self.arg_types) - extra_launcher_args_count - num_tma_tensor_args + ) + if num_wrapper_args != len(wrapper_arg_names): + raise AssertionError( + f"Mismatch between ({num_wrapper_args}) arg_types and " + f"{len(wrapper_arg_names)} wrapper_arg_names for {self.kernel_name}." + ) + + # Append grid args: passed to wrapper. Kernel args will handle grids separately. + for i in range(extra_launcher_args_count): + wrapper_arg_names.append(f"_grid_{i}") + + # Add TMA tensor args after grid args + if tma_tensor_args: + sig_tma_keys = list(self._get_tma_args().keys()) + if list(tma_tensor_args.keys()) != sig_tma_keys: + raise AssertionError( + f"TMA tensor args order mismatch for {self.kernel_name}: " + f"{list(tma_tensor_args.keys())} vs signature order {sig_tma_keys}" + ) + for desc_name in tma_tensor_args: + wrapper_arg_names.append(f"_tma_tensor_{desc_name}") + + return wrapper_arg_names, kernel_arg_names + + def _generate_lazy_grid(self, prefix: IndentedBuffer) -> None: + """Generate grid computation code for lazy-compiled kernels.""" + kernel_name = self.kernel_name + grid_type = self.inductor_meta.get("grid_type") if self.inductor_meta else None + + # For PrecomputedGrid, generate switch statement on config_index + if grid_type == "PrecomputedGrid": + if self.inductor_meta is None: + raise AssertionError("inductor_meta is required for PrecomputedGrid") + precomputed_grids = self.inductor_meta.get("precomputed_grids", []) + extra_launcher_args = self.inductor_meta.get("extra_launcher_args", []) + + switch_cases = [] + for idx, entry in enumerate(precomputed_grids): + cpp_grids = list(entry.get("cpp", ["1L", "1L", "1L"])) + # Replace internal arg names with C++ parameter names + # e.g., _launcher_s0 -> _grid_0 + for i, arg_name in enumerate(extra_launcher_args): + cpp_grids = [g.replace(arg_name, f"_grid_{i}") for g in cpp_grids] + g0 = cpp_grids[0] + g1 = cpp_grids[1] if len(cpp_grids) > 1 else "1" + g2 = cpp_grids[2] if len(cpp_grids) > 2 else "1" + switch_cases.append( + f"case {idx}: grid_0 = {g0}; grid_1 = {g1}; grid_2 = {g2}; break;" + ) + switch_cases.append("default: grid_0 = 1; grid_1 = 1; grid_2 = 1; break;") + switch_body = "\n ".join(switch_cases) + + prefix.splice( + f"""\ + uint32_t grid_0, grid_1, grid_2; + switch ({kernel_name}_result.config_index) {{ + {switch_body} + }} + if (grid_0 == 0) return; + """ + ) + else: + from ..runtime.triton_heuristics import GridExpr + + grid = GridExpr.from_meta_lazy( + cast("InductorMeta | None", self.inductor_meta), kernel_name + ) + for line in grid.prefix: + prefix.writeline(line) + + prefix.splice( + f"""\ + uint32_t grid_0 = {grid.x_grid}; + uint32_t grid_1 = {grid.y_grid}; + uint32_t grid_2 = {grid.z_grid}; + if (grid_0 == 0) return; + """ + ) + + def _generate_lazy_tma_args( + self, + prefix: IndentedBuffer, + call_args_str: str, + kernel_arg_names: list[str], + tma_arg_names: OrderedSet[str], + signature: dict[str, str], + ) -> str: + """Unpack TMA descriptor args into kernel launch args.""" + for arg_name in kernel_arg_names: + if arg_name in tma_arg_names: + tma_parts = _unpack_tma_descriptor_args(arg_name, signature[arg_name]) + tma_str = ", ".join(tma_parts) + call_args_str = ( + f"{call_args_str}, {tma_str}" if call_args_str else tma_str + ) + return call_args_str + + def _generate_lazy_scratch( + self, + prefix: IndentedBuffer, + wrapper: CppWrapperGpu, + call_args_str: str, + ) -> str: + """Generate scratch space allocations with runtime-known sizes.""" + kernel_name = self.kernel_name + dtype_str = wrapper.codegen_dtype(torch.uint8) + device_type, _ = wrapper.codegen_device(torch.device(get_gpu_type())).split( + ", " + ) + device_ptr_type = wrapper.device_codegen.cpp_device_ptr() + # Triton reports per-CTA scratch via kernel.metadata.global_scratch_size; + # the kernel writes its slot at offset (pid * scratch_size). Scale by the + # full launch grid so concurrent CTAs don't collide. + grid_extent = "static_cast(grid_0) * grid_1 * grid_2" + for scratch_name in ("global_scratch", "profile_scratch"): + size_expr = f"{kernel_name}_result.{scratch_name}" + var = f"{scratch_name}_ptr" + prefix.splice( + maybe_hipify_code_wrapper( + f"""\ + int64_t {var}_numel = {size_expr} * {grid_extent}; + RAIIAtenTensorHandle {var}_tensor; + {device_ptr_type} {var} = allocate_scratch_tensor<{device_ptr_type}>( + {var}_numel, {dtype_str}, {device_type}, device_idx_, {var}_tensor); + """ + ) + ) + call_args_str += f", &{var}" + return call_args_str + + def _generate_lazy_launch( + self, + prefix: IndentedBuffer, + wrapper: CppWrapperGpu, + wrapper_arg_names: list[str], + kernel_arg_names: list[str], + ) -> None: + """Generate kernel launch code for lazy-compiled kernels.""" + kernel_name = self.kernel_name + signature = (self.triton_meta or {}).get("signature", {}) + tma_tensor_args = self.tma_tensor_args + num_tma_tensor_args = len(tma_tensor_args) + + # wrapper_arg_names may include grid and TMA tensor args at the end; + # only the leading portion maps 1:1 to kernel signature params. + num_signature_args = len(wrapper_arg_names) - num_tma_tensor_args + inductor_meta = self.inductor_meta or {} + num_signature_args -= len(inductor_meta.get("extra_launcher_args", [])) + + arg_type_lookup = dict( + zip(wrapper_arg_names, self.arg_types[:num_signature_args]) + ) + + # Identify TMA args — they are already passed as StableTMADescriptor params, + # so we just unpack them directly (no need to reconstruct from tensors). + tma_arg_names = OrderedSet(self._get_tma_args().keys()) + + # Non-TMA args go through generate_args_decl + non_tma_arg_names = [n for n in kernel_arg_names if n not in tma_arg_names] + non_tma_arg_types = [ + arg_type_lookup[n] for n in non_tma_arg_names if n in arg_type_lookup + ] + non_tma_arg_sigs = [signature.get(n) for n in non_tma_arg_names] + + call_args_str = wrapper.generate_args_decl( + prefix, + non_tma_arg_names, + non_tma_arg_types, + non_tma_arg_sigs, + ) + + call_args_str = self._generate_lazy_tma_args( + prefix, call_args_str, kernel_arg_names, tma_arg_names, signature + ) + call_args_str = self._generate_lazy_scratch(prefix, wrapper, call_args_str) + + common_launch_args = ( + f"grid_0, grid_1, grid_2," + f" {kernel_name}_result.num_warps," + f" {kernel_name}_result.shared_mem," + f" kernel_args_, stream_" + ) + # stream_ comes from the generated wrapper signature on both JIT and + # AOTI sides. + launch_kernel_args = [ + "grid_0", + "grid_1", + "grid_2", + f"{kernel_name}_result.num_warps", + f"{kernel_name}_result.shared_mem", + ] + + # kernel_args_ is consumed by both JIT and AOT launchKernel calls. + prefix.writeline(f"void* kernel_args_[] = {{{call_args_str}}};") + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + prefix.writeline_jit(f"launchKernel({kernel_name}, {common_launch_args});") + if enable_kernel_profile: + profile_arg_types = [arg_type_lookup.get(n) for n in kernel_arg_names] + profile_arg_sigs = [signature.get(n) for n in kernel_arg_names] + aot_profile = IndentedBuffer(initial_indent=prefix._indent) + self.generate_profiled_launch_kernel( + aot_profile, + f"kernels_.{kernel_name}", + kernel_arg_names, + profile_arg_types, + profile_arg_sigs, + [ + f"kernels_.{kernel_name}", + *launch_kernel_args, + "kernel_args_", + "stream_", + ], + num_warps=f"{kernel_name}_result.num_warps", + shared_mem=f"{kernel_name}_result.shared_mem", + ) + prefix.splice_aot(aot_profile) + else: + prefix.writeline_aot( + f"launchKernel(kernels_.{kernel_name}, {common_launch_args});" + ) + + def generate_lazy(self, wrapper: CppWrapperGpu): + """ + Generate dual-wrapper-mode C++ code for lazy Triton kernel compilation. + + DualIndentedBuffer routes lines into separate JIT and AOTI sources: + - JIT side: embeds Triton source, compiles at runtime, autotunes + with real inputs. + - AOTI side: uses a compile-time-initialized LazyKernelCompileResult + from a config header generated after the JIT first-pass. + + Grid computation and kernel launch are shared between both sides + via the LazyKernelCompileResult struct. + """ + prefix = wrapper.prefix + kernel_name = self.kernel_name + macro_prefix = kernel_name.upper() + + # Track kernel names for parallel initialization (JIT only) + wrapper._lazy_kernel_names.append(kernel_name) + + # Include TMA helpers if any args use TMA descriptors + tma_signature_types = self._get_tma_args() + if tma_signature_types: + wrapper.write_tma_descriptor_helpers_once() + + kernel_type = maybe_hipify_code_wrapper( + wrapper.device_codegen.cpp_kernel_type() + ) + + # JIT-only: static CUfunction and embedded Triton source + prefix.writeline_jit(f"static {kernel_type} {kernel_name} = nullptr;") + kernel_source_str = self.kernel_name_to_body.get(kernel_name, "") + kernel_body = f'R"TRITON(\n{kernel_source_str}\n)TRITON"' + prefix.writeline_jit( + f"static const char* {kernel_name}_source = {kernel_body};" + ) + + # LazyKernelCompileResult: JIT fills at runtime; AOTI uses compile-time + # init from the config header generated after the first pass. + prefix.writeline_jit(f"static LazyKernelCompileResult {kernel_name}_result;") + prefix.splice_aot( + f"""\ + static LazyKernelCompileResult {kernel_name}_result = {{ + {macro_prefix}_CUBIN_PATH, + {macro_prefix}_MANGLED_NAME, + {macro_prefix}_NUM_WARPS, + {macro_prefix}_SHARED_MEM, + {macro_prefix}_XBLOCKS, + {macro_prefix}_YBLOCKS, + {macro_prefix}_ZBLOCKS, + {macro_prefix}_R0BLOCKS, + {macro_prefix}_RSPLIT, + {macro_prefix}_RSPLIT_SIZE, + {macro_prefix}_CONFIG_INDEX, + {macro_prefix}_GLOBAL_SCRATCH, + {macro_prefix}_PROFILE_SCRATCH, + }}; + """ + ) + + wrapper_arg_names, kernel_arg_names = self._resolve_lazy_arg_names() + signature = (self.triton_meta or {}).get("signature", {}) + + # kernels_type_/kernels_ are routed to the AOTI buffer; if prefix is a + # plain IndentedBuffer (pure JIT lazy compile) those writes are dropped. + self._write_wrapper_signature( + prefix, + wrapper, + wrapper_arg_names, + self.arg_types, + signature, + ) + + # Build autotune args - for TMA, pass tensors instead of descriptors. + # Only iterate over signature params and grid args, not the trailing + # TMA tensor params (those are only in the C++ wrapper signature). + tma_tensor_args = self.tma_tensor_args + num_autotune_args = len(wrapper_arg_names) - len(tma_tensor_args) + autotune_arg_list = [] + # Track which args need scalar extraction for the autotune call. + # UnwrapUnspecArg args are 0-dim tensors in C++ that Triton expects + # as Python scalars; we use codegen_tensor_item to extract them. + scalar_extractions: list[tuple[str, str, torch_dtype]] = [] + for idx, name in enumerate(wrapper_arg_names[:num_autotune_args]): + if name in tma_signature_types: + autotune_arg_list.append(f"_tma_tensor_{name}") + elif isinstance(self.arg_types[idx], UnwrapUnspecArg): + scalar_var = f"_autotune_scalar_{name}" + scalar_extractions.append((name, scalar_var, self.arg_types[idx].dtype)) + autotune_arg_list.append(scalar_var) + else: + autotune_arg_list.append(name) + autotune_args = ", ".join(autotune_arg_list) + + with prefix.indent(): + # First-call initialization: JIT lazy compiles, AOTI loads cubin + + # JIT: lazy compile with autotuning on first invocation. + # Build into temp buffer to avoid DualIndentedBuffer dispatch. + jit_init = IndentedBuffer(initial_indent=prefix._indent) + jit_init.writeline(f"if ({kernel_name} == nullptr) {{") + with jit_init.indent(): + for tensor_name, scalar_var, dtype in scalar_extractions: + wrapper.codegen_tensor_item( + dtype, tensor_name, scalar_var, indented_buffer=jit_init + ) + jit_init.splice( + f"""\ + {kernel_name}_result = runTritonKernelWithAutotune( + _module_pending_kernels, "{kernel_name}", stream_, {autotune_args}); + + {kernel_name} = loadKernel( + {kernel_name}_result.cubin_path, + {kernel_name}_result.mangled_name, + {kernel_name}_result.shared_mem); + + // First invocation already ran the kernel, so return early + return; + """ + ) + jit_init.writeline("}") + prefix.splice_jit(jit_init) + + # AOTI: load precompiled cubin from compile-time-initialized result. + loaded_modules_arg = ( + ",\n &kernels_.loaded_modules_" + if V.graph.device_type != "xpu" + else "" + ) + aoti_init = IndentedBuffer(initial_indent=prefix._indent) + aoti_init.writeline(f"if (kernels_.{kernel_name} == nullptr) {{") + with aoti_init.indent(): + aoti_init.splice( + f"""\ + kernels_.{kernel_name} = loadKernel( + {kernel_name}_result.cubin_path, + {kernel_name}_result.mangled_name, + {kernel_name}_result.shared_mem, + cubin_dir_{loaded_modules_arg}); + """ + ) + aoti_init.writeline("}") + prefix.splice_aot(aoti_init) + + # Shared: grid computation and launch using result struct + self._generate_lazy_grid(prefix) + self._generate_lazy_launch( + prefix, + wrapper, + wrapper_arg_names, + kernel_arg_names, + ) + prefix.writeline("}") + + def generate_grid( + self, + prefix: IndentedBuffer, + inductor_meta: dict[str, Any], + params: dict[str, Any], + ): + from ..runtime.triton_heuristics import GridExpr + + grid = GridExpr.from_meta( + cast("InductorMeta", inductor_meta), params["config"], mode="cpp" + ) + for line in grid.prefix: + prefix.writeline(line) + prefix.splice( + f"""\ + uint32_t grid_0 = {grid.x_grid}; + uint32_t grid_1 = {grid.y_grid}; + uint32_t grid_2 = {grid.z_grid}; + """ + ) + prefix.writeline("if (grid_0 == 0 || grid_1 == 0 || grid_2 == 0) return;") + + def generate_load_kernel(self, prefix, kernel_var_name, params): + prefix.writeline(f"if ({kernel_var_name} == nullptr) {{") + with prefix.indent(): + embed_kernel_args = [f"__{params['inductor_meta']['kernel_name']}_start"] + if torch.xpu.is_available(): + # XPU needs the end address of the kernel to calculate the size of the kernel binary. + embed_kernel_args.append( + f"__{params['inductor_meta']['kernel_name']}_end" + ) + + if V.graph.aot_mode and config.aot_inductor.embed_kernel_binary: + load_kernel_args = [ + *embed_kernel_args, + cpp_string_literal(params["mangled_name"]), + str(params["shared_mem"]), + ] + if torch.xpu.is_available(): + is_spv = "true" if XPU_KERNEL_FORMAT == "spv" else "false" + if config.aot_inductor.emit_multi_arch_kernel: + is_spv = "true" + load_kernel_args.append(is_spv) + else: + load_kernel_args = [ + cpp_string_literal(params[get_cpp_wrapper_cubin_path_name()]), + cpp_string_literal(params["mangled_name"]), + str(params["shared_mem"]), + "cubin_dir_", + ] + + # In AOTI mode on CUDA/HIP, pass the loaded_modules_ vector so + # CUmodule handles are tracked and can be unloaded on destruction, + # preventing GPU code object leaks. XPU is excluded because its + # loadKernel returns std::unique_ptr and manages + # cleanup via RAII. + if V.graph.aot_mode and V.graph.device_type != "xpu": + load_kernel_args = load_kernel_args + ["&kernels_.loaded_modules_"] + + prefix.writeline( + f"{kernel_var_name} = loadKernel({', '.join(load_kernel_args)}); " + ) + prefix.writeline("}") + + def generate_launch_kernel(self, prefix, wrapper, kernel_var_name, params): + """ + Generate the GPU kernel launching code. + This is where all the call args are sorted out and generated. + If enable_kernel_profile is enabled, all args related information would be packed in this function. + """ + triton_meta = params["triton_meta"] + if len(self.arg_types) != len(params["def_args"]): + raise AssertionError((self.arg_types, params["def_args"])) + arg_type_lookup = dict(zip(params["def_args"], self.arg_types)) + # difference between Python and C++ wrapper: C++ wrapper strips out equal_to_1 constants + call_args = [ + name for name in params["call_args"] if name not in triton_meta["constants"] + ] + arg_types = [arg_type_lookup[name] for name in call_args] + arg_signatures = [triton_meta["signature"][name] for name in call_args] + num_ctas = params.get("config", {}).get("num_ctas", 1) + scratch_spaces = { + name: params[name] * num_ctas + for name in ["global_scratch", "profile_scratch"] + if params.get(name, None) is not None + } + call_args_str = wrapper.generate_args_decl( + prefix, + call_args, + arg_types, + arg_signatures, + scratch_spaces=scratch_spaces, + ) + prefix.writeline(f"void* kernel_args_[] = {{{call_args_str}}};") + num_warps = str(params["num_warps"]) + shared_mem = str(params["shared_mem"]) + launch_kernel_args = [ + kernel_var_name, + "grid_0", + "grid_1", + "grid_2", + num_warps, + shared_mem, + "kernel_args_", + "stream_", + ] + + enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [ + "linux", + "win32", + ] + if enable_kernel_profile: + self.generate_profiled_launch_kernel( + prefix, + kernel_var_name, + call_args, + arg_types, + arg_signatures, + launch_kernel_args, + num_warps=num_warps, + shared_mem=shared_mem, + ) + else: + prefix.writeline(f"launchKernel({', '.join(launch_kernel_args)});") + + def generate_profiled_launch_kernel( + self, + prefix: IndentedBuffer, + kernel_var_name: str, + call_args: list[str], + arg_types: list[Any], + arg_signatures: list[str | None], + launch_kernel_args: list[str], + num_warps: str, + shared_mem: str, + ) -> None: + """Wrap a kernel launch in an AOTI record_function profiling scope.""" + normalized_kernel_name = re.sub(r"[^a-zA-Z0-9_]", "_", kernel_var_name) + prefix.writeline("{") + with prefix.indent(): + prefix.writelines( + [ + f"std::unordered_map kwargs_{normalized_kernel_name};", + "", + ] + ) + # Add launch args info + record_launch_kernel_args = [ + ("grid_0", "grid_0"), + ("grid_1", "grid_1"), + ("grid_2", "grid_2"), + ("num_warps", num_warps), + ("shared_mem", shared_mem), + ] + for k, v in record_launch_kernel_args: + arg_name = f"{normalized_kernel_name}_{k}" + prefix.writelines( + [ + f"// Create c10::IValue for {k}", + f"C10IValueHandle tmp_{arg_name};", + f"aoti_torch_int64_to_ivalue({v}, &tmp_{arg_name});", + f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});", + f'kwargs_{normalized_kernel_name}.emplace("{k}", RAII_{arg_name});', + ] + ) + + # Add input info (This copies the logic from args_decl) + curr_arg_id = -1 + total_args = [] + ordered_argsname = [] + + def write_dummy_scalar_ivalue(arg_name): + # We only care about the shape, therefore we create a dummy scalar here. + prefix.writelines( + [ + f"// Create c10::IValue for arg_{curr_arg_id}", + f"C10IValueHandle tmp_{arg_name};", + f"aoti_torch_int64_to_ivalue(0, &tmp_{arg_name});", + f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});", + ] + ) + # pyrefly: ignore [bad-argument-type] + total_args.append(f"tmp_{arg_name}") + + def process_args_for_input_shape(arg, arg_type, arg_signature=None): + nonlocal curr_arg_id + curr_arg_id += 1 + arg_name = f"{normalized_kernel_name}_arg_{curr_arg_id}" + # ignore tma descriptors, as host-side TMA descriptors need + # to be passed to the compiled Triton kernel by value + if isinstance(arg_type, UnwrapUnspecArg) and not signature_is_tma_desc( + arg_signature + ): + write_dummy_scalar_ivalue(arg_name) + elif isinstance(arg_type, torch_dtype) and not signature_is_tma_desc( + arg_signature + ): + # This is an at::Tensor. + prefix.writelines( + [ + f"// Create c10::IValue for arg_{curr_arg_id}", + f"C10IValueHandle tmp_{arg_name};", + f"aoti_torch_tensor_to_ivalue({arg}, &tmp_{arg_name});", + f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});", + ] + ) + # pyrefly: ignore [bad-argument-type] + total_args.append(f"tmp_{arg_name}") + elif ( + isinstance(arg_type, type(SymbolicCallArg)) + and arg_signature is not None + and arg_signature in TRITON_SIGNATURE_TO_CPP + ) or arg_type in (sympy.Integer, int, sympy.Float, float): + write_dummy_scalar_ivalue(arg_name) + elif arg_signature and arg_signature.startswith("tensordesc<"): + # Skip tma related args + pass + else: + write_dummy_scalar_ivalue(arg_name) + + # Add input name and shape information + for arg, arg_type, arg_signature in zip_longest( + call_args, arg_types, arg_signatures + ): + # pyrefly: ignore [bad-argument-type] + ordered_argsname.append(f'"{arg}"') + process_args_for_input_shape(arg, arg_type, arg_signature) + + # Add input name into kwargs + name_var = f"{normalized_kernel_name}_input_names" + prefix.writelines( + [ + "// Create c10::IValue for input names", + f"C10IValueHandle tmp_{name_var};", + f"std::vector {name_var}({{{', '.join(ordered_argsname)}}});", + f"aoti_torch_strlist_to_ivalue({name_var}.data(), {len(ordered_argsname)}, &tmp_{name_var});", + f"RAIIC10IValueHandle RAII_{name_var}(tmp_{name_var});", + f'kwargs_{normalized_kernel_name}.emplace("Input Args", RAII_{name_var});', + ] + ) + + inputs_info_ = f"{normalized_kernel_name}_inputs_info_" + # We pass in the non-RAII handles, since C10 doesn't automatically free them. + # The RAII will make sure they get freed when they are out of scope. + tmp_args = ",".join(total_args) + prefix.writelines( + [ + "// Aggregate all c10::IValue for inputs", + f"std::vector {inputs_info_}({{{tmp_args}}});", + ] + ) + + # Start recording Function + prefix.writelines( + [ + "", + ( + "torch::aot_inductor::RAIIAtenRecordFunctionHandle " + f"record_{normalized_kernel_name}_" + f'("{kernel_var_name}", ' + f"reinterpret_cast(&kwargs_{normalized_kernel_name}), " + f"{inputs_info_});" + ), + "", + f"launchKernel({', '.join(launch_kernel_args)});", + ] + ) + prefix.writeline("}") + + +class CppWrapperGpu(CppWrapperCpu): + """ + Generates cpp wrapper for running on GPU and calls CUDA kernels + """ + + def __init__(self) -> None: + self.device = get_gpu_type() + self.device_codegen = get_device_op_overrides(self.device) + super().__init__() + self.grid_id = count() + self._kernel_name_to_body: dict[str, str] = {} + self._triton_call_wrappers: dict[str, DeferredTritonCallWrapper] = {} + self.autotune_input_prefix = "_REAL_AUTOTUNE_INPUT" + self._lazy_kernel_names: list[str] = [] + self._declared_aux_stream_slots: OrderedSet[int] = OrderedSet() + self._aoti_current_stream_guard_declared = False + self._aoti_stream_helpers_emitted = False + + def generate_debug_sync(self, buffer): + if self.device == "cuda": + # The fbcode JIT cpp_wrapper CUDA build links only the CUDA driver + # (libcuda), not libcudart, so the runtime cudaDeviceSynchronize symbol + # is undefined at dlopen -> use the driver-API cuCtxSynchronize there. + # On ROCm the driver-context sync hipCtxSynchronize returns + # hipErrorNotSupported at runtime, so keep the runtime cudaDeviceSynchronize + # (which hipifies to hipDeviceSynchronize and IS linked in the ROCm build). + if torch.version.hip is not None: + buffer.writeline( + maybe_hipify_code_wrapper( + "AOTI_RUNTIME_CUDA_CHECK(cudaDeviceSynchronize());" + ) + ) + else: + buffer.writeline("CUDA_DRIVER_CHECK(cuCtxSynchronize());") + return + + raise NotImplementedError( + f"triton debug sync is not supported with {self.device} cpp_wrapper" + ) + + @staticmethod + def create( + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: GraphPartitionSignature | None = None, + ): + # TODO - support subgraph codegen by lifting functions. Check the + # comment at CppWrapperCpu `codegen_subgraph` function. + return CppWrapperGpu() + + def write_header(self): + if V.graph.is_const_graph and not V.graph.is_dual_wrapper_mode: + # We do not write header for constant graph, it will be written by main module. + return + + super().write_header() + kernel_driver = maybe_hipify_code_wrapper(self.device_codegen.kernel_driver()) + if V.graph.is_const_graph and V.graph.is_dual_wrapper_mode: + # For a dual-wrapper-mode const graph, only the standalone JIT + # output needs this header content. The AOTI const body is spliced + # into the main AOTI source, which has its own kernel driver. + # super().write_header() early-returns for const graphs before it + # can call add_device_include, so emit the JIT device include here; + # otherwise the kernel driver's CUfunction/CUmodule/uint32_t types + # have no declaring header and fail to compile under -nostdinc. + for device in V.graph.device_types: + if device != "meta": + self.header.splice_jit(self.get_device_include_path_jit(device)) + self.header.splice_jit(kernel_driver) + else: + self.header.splice(kernel_driver) + + def _generate(self, is_inference): + # Per-Run()-function state, reset each generation. Do NOT reset + # _aoti_stream_helpers_emitted here: the helper structs are spliced into + # the file-level header once per instance, and _generate can run more + # than once against the same header (resetting it re-splices and yields + # a C++ redefinition). + self._declared_aux_stream_slots.clear() + self._aoti_current_stream_guard_declared = False + return super()._generate(is_inference) + + @cache_on_self + def write_tma_descriptor_helpers_once(self): + self.header.splice(self.device_codegen.tma_descriptor_helpers()) + + def write_get_raw_stream(self, device_idx: int, graph_name: str) -> str: + # Pure AOTI receives the stream as a function parameter. JIT and + # dual-wrapper-mode code use an explicit stream variable so the shared kernel + # call arguments are valid for the JIT entry point. + if V.graph.aot_mode and not V.graph.is_dual_wrapper_mode: + return "stream" + + name = f"stream{device_idx}" + # In dual-wrapper mode, the JIT stream is declared at the entry function + # prologue (see _codegen_entry_impl_prologue) so it stays in scope + # across all kernel call sites. + if V.graph.is_dual_wrapper_mode: + return name + + self.writeline( + maybe_hipify_code_wrapper( + f"{self.device_codegen.cpp_stream_type()} {name};" + ) + ) + self.writeline( + f"AOTI_TORCH_ERROR_CODE_CHECK({self.device_codegen.aoti_get_stream()}({device_idx}, (void**)&{name}));" + ) + return name + + def _ensure_aoti_stream_helpers_emitted(self) -> None: + if self._aoti_stream_helpers_emitted: + return + # The stream/event helpers in streams.h are CUDA-specific (cudaEvent_t, + # cudaStream_t, cudaEventRecord, ...). Guarding here on the device type + # prevents the CUDA-only symbols from being emitted into XPU generated + # code, where SYCL in-order queues handle event ordering implicitly. + if self.device == "xpu": + return + self._aoti_stream_helpers_emitted = True + with open( + os.path.join(os.path.dirname(__file__), "aoti_runtime", "streams.h") + ) as f: + self.header.splice(maybe_hipify_code_wrapper(f.read())) + self.header.splice( + """ + namespace { + + static thread_local torch::aot_inductor::AOTIPerThreadEventCache + _aoti_event_cache; + static thread_local torch::aot_inductor::AOTIPerThreadStreamCache + _aoti_aux_stream_cache; + + } // namespace + """ + ) + + def codegen_stream_info_prologue( + self, + code: IndentedBuffer, + num_streams: int, + stream_idx_to_user_obj_idx: dict[int, int], + ) -> None: + if num_streams <= 1: + return + if not V.graph.aot_mode: + raise NotImplementedError( + "Multi-stream cpp_wrapper codegen is only supported for AOTI." + ) + self._ensure_aoti_stream_helpers_emitted() + code.writeline( + f"_aoti_aux_stream_cache.ensure({num_streams}, this->device_idx_, stream);" + ) + if not self._aoti_current_stream_guard_declared: + code.writeline( + f"std::unique_ptr<{V.graph.device_ops.cpp_aoti_stream_guard()}> " + "_aoti_current_stream_guard;" + ) + self._aoti_current_stream_guard_declared = True + + stream_type = self.device_codegen.cpp_stream_type() + for i in range(1, num_streams): + if i in self._declared_aux_stream_slots: + continue + code.writeline( + maybe_hipify_code_wrapper( + f"{stream_type} {get_stream_name(i)} = " + f"_aoti_aux_stream_cache.get({i}, this->device_idx_, stream);" + ) + ) + self._declared_aux_stream_slots.add(i) + + def codegen_enter_cuda_stream_context( + self, code: IndentedBuffer, stream_idx: int + ) -> None: + if stream_idx == 0: + return + code.writeline( + "_aoti_current_stream_guard = " + f"std::make_unique<{V.graph.device_ops.cpp_aoti_stream_guard()}>(" + f"{self._stream_expr_for_idx(stream_idx)}, this->device_idx_);" + ) + + def codegen_exit_cuda_stream_context(self, code: IndentedBuffer) -> None: + code.writeline("_aoti_current_stream_guard.reset();") + + def _stream_expr_for_idx(self, stream_idx: int) -> str: + if stream_idx == 0: + return "stream" + return f"_aoti_aux_stream_cache.get({stream_idx}, this->device_idx_, stream)" + + def _emit_stream_op_inline(self, kernel_name: str | None, args: list[str]) -> bool: + if kernel_name is None or not V.graph.aot_mode: + return False + if self.device == "xpu": + return False + if kernel_name in AOTI_UNSUPPORTED_STREAM_OP_REASONS: + raise NotImplementedError( + f"{kernel_name} is not supported in AOTI cpp_wrapper. " + f"{AOTI_UNSUPPORTED_STREAM_OP_REASONS[kernel_name]}" + ) + op = AOTI_SUPPORTED_STREAM_OP_NAMES.get(kernel_name) + if op is None: + return False + + def _parse_idx(arg: str) -> int: + return int(arg.rstrip("Ll")) + + self._ensure_aoti_stream_helpers_emitted() + event_idx = _parse_idx(args[0]) + if op == "record_event": + stream_idx = _parse_idx(args[1]) + self.writeline( + maybe_hipify_code_wrapper( + "AOTI_RUNTIME_CUDA_CHECK(cudaEventRecord(" + f"_aoti_event_cache.get({event_idx}, this->device_idx_), " + f"{self._stream_expr_for_idx(stream_idx)}));" + ) + ) + return True + if op == "wait_event": + stream_idx = _parse_idx(args[1]) + self.writeline( + maybe_hipify_code_wrapper( + "AOTI_RUNTIME_CUDA_CHECK(cudaStreamWaitEvent(" + f"{self._stream_expr_for_idx(stream_idx)}, " + f"_aoti_event_cache.get({event_idx}, this->device_idx_), 0));" + ) + ) + return True + if op == "synchronize_event": + self.writeline( + maybe_hipify_code_wrapper( + "AOTI_RUNTIME_CUDA_CHECK(cudaEventSynchronize(" + f"_aoti_event_cache.get({event_idx}, this->device_idx_)));" + ) + ) + return True + return False + + def _generate_extern_kernel_alloc_helper(self, extern_kernel, args): + kernel_name = getattr(extern_kernel, "python_kernel_name", None) + if self._emit_stream_op_inline(kernel_name, args): + if V.extern_kernel_nodes: + V.extern_kernel_nodes.pop() + return + super()._generate_extern_kernel_alloc_helper(extern_kernel, args) + + def generate_fallback_kernel_with_runtime_lookup( + self, + buf_name, + python_kernel_name, + get_args, + op_overload, + raw_args, + outputs, + ): + if self._emit_stream_op_inline(python_kernel_name, list(get_args())): + if V.extern_kernel_nodes: + V.extern_kernel_nodes.pop() + return + super().generate_fallback_kernel_with_runtime_lookup( + buf_name, + python_kernel_name, + get_args, + op_overload, + raw_args, + outputs, + ) + + def get_autotuning_input_name(self, idx): + return f"{self.autotune_input_prefix}_{idx}" + + def codegen_inputs(self): + # See Note: [Input Alignment handling in Inductor] + # + # JIT Inductor does not guard on input alignment. It relies on copy_misaligned_inputs to + # copy misaligned inputs to aligned buffers. For AOTInductor, we need to do the same in cpp. + + if config.is_fbcode(): + # TODO: This is added because FC. Remove this once the newly added shim symbols, + # e.g. aoti_torch_clone_preserve_strides, have landed + return super().codegen_inputs() + + if V.graph.aot_mode and V.graph.inputs_to_check: + for idx in V.graph.inputs_to_check: + input_name = V.graph.graph_input_names[idx] + if input_name not in V.graph.graph_inputs: + raise AssertionError(f"{input_name} not found in graph inputs") + value = V.graph.graph_inputs[input_name] + if not isinstance(value, TensorBox): + raise AssertionError( + f"{input_name} is expected to be tensor but found as {type(value)}" + ) + warn_msg = ( + f"Input {idx} was compiled as {GPU_ALIGN_BYTES}-bytes aligned, " + "but it is not aligned at run time. Copying to an aligned tensor " + "to guarantee correctness, but expect a performance hit." + ) + alignment_check = f""" + if ((reinterpret_cast({input_name}.data_ptr()) & ({GPU_ALIGN_BYTES} -1)) != 0) {{ + AOTI_TORCH_WARN("{warn_msg}"); + AtenTensorHandle {input_name}_aligned; + AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_clone_preserve_strides({input_name}, &{input_name}_aligned)); + {input_name} = std::move(RAIIAtenTensorHandle({input_name}_aligned)); + }} + """ + self.prefix.splice_aot(alignment_check) + + super().codegen_inputs() + + def _define_kernel_helper( + self, + kernel_name: str, + kernel_body: str, + metadata: str | None = None, + gpu: bool = True, + cpp_definition: str | None = None, + ): + if gpu: + self._kernel_name_to_body[kernel_name] = kernel_body + if config.triton.autotune_at_compile_time: + # Call PythonWrapperCodegen to create the autotune code block + PythonWrapperCodegen._define_kernel_helper( + self, kernel_name, kernel_body, metadata, gpu, cpp_definition + ) + else: + return CppWrapperCpu._define_kernel_helper( + self, kernel_name, kernel_body, metadata, gpu, cpp_definition + ) + + def generate(self, is_inference): + with dynamo_timed("CppWrapperGpu.generate", log_pt2_compile_event=True): + return super().generate(is_inference) + + def _codegen_entry_impl_prologue(self): + super()._codegen_entry_impl_prologue() + # ensure_triton_kernel_compiles_started() is JIT-only; AOTI has no + # Python-dependent lazy compile flow. + self.prefix.writeline_jit( + _LazyTritonCompileKickoffLine( + self._lazy_kernel_names, "ensure_triton_kernel_compiles_started();" + ) + ) + # In dual-wrapper mode, hoist the JIT-side stream declaration to the entry + # function prologue. Kernel calls run inside KernelContextGuard + # scopes, so a per-call declaration would be scoped to the guard + # and unavailable to other kernel calls in the same function. + if V.graph.is_dual_wrapper_mode: + stream_type = maybe_hipify_code_wrapper( + self.device_codegen.cpp_stream_type() + ) + get_stream = self.device_codegen.aoti_get_stream() + for device_idx in sorted(V.graph.device_idxs): + name = f"stream{device_idx}" + self.prefix.writeline_jit(f"{stream_type} {name};") + self.prefix.writeline_jit( + f"AOTI_TORCH_ERROR_CODE_CHECK(" + f"{get_stream}({device_idx}, (void**)&{name}));" + ) + + def finalize_prefix(self): + """Define the triton kernels now that autotuning is finished""" + old_prefix = self.prefix # new content should go at start of prefix + + # Generating triton kernel callers can modify the prefix (cached dtypes), + # so do this before running finalize_prefix(), but put the generated code + # after the finalize_prefix() code. + triton_prefix = make_codegen_buffer() + with self._target_buf("prefix", triton_prefix): + for kernel in self._triton_call_wrappers.values(): + self.prefix.writeline("\n") + kernel.generate(self) + + # Generate parallel kernel compilation initialization function. + # JIT-only since AOTI has no Python dependency. + if self._lazy_kernel_names: + start_compile_body = ( + "loadLazyCompileFuncs();\n" + " _module_pending_kernels = PyDict_New();\n" + ' AOTI_TORCH_CHECK(_module_pending_kernels, "Failed to create pending kernels dict");\n' + " " + + "\n ".join( + f'startKernelCompile(_module_pending_kernels, "{name}", {name}_source);' + for name in self._lazy_kernel_names + ) + ) + self.include_extra_header("mutex") + self.prefix.writeline_jit("") + self.prefix.splice_jit( + f"""\ +// Start parallel compilation of all Triton kernels. +static inline void start_all_triton_kernel_compiles() {{ + {start_compile_body} +}} + +// inductor_entry_impl calls this on every forward; +// std::call_once makes the first call do the work. +static std::once_flag _triton_kernel_compile_init_flag; +static inline void ensure_triton_kernel_compiles_started() {{ + std::call_once(_triton_kernel_compile_init_flag, [] {{ + start_all_triton_kernel_compiles(); + }}); +}} +""" + ) + + self.prefix = make_codegen_buffer() + super().finalize_prefix() + + self.prefix.splice(triton_prefix) + self.prefix.writeline("\n") + self.prefix.splice(old_prefix) + + def generate_tma_descriptor(self, desc): + self.write_tma_descriptor_helpers_once() + + if isinstance(desc, TMADescriptorExperimental): + self._generate_experimental_tma_descriptor(desc) + else: + if not isinstance(desc, TMADescriptorStable): + raise AssertionError(f"expected TMADescriptorStable, got {type(desc)}") + self._generate_stable_tma_descriptor(desc) + + def _generate_experimental_tma_descriptor(self, desc): + # generate data pointer for the source tensor + source = self.generate_args_decl( + code=self, + call_args=[self.val_to_arg_str(desc.tensor)], + arg_types=[desc.tensor.get_dtype()], + arg_signatures=[None], + # these args are passed to initNDTMADescriptor, which is NOT a triton kernel + is_triton_kernel=False, + ) + + desc_name = desc.name + self.writeline(f"alignas(64) CUtensorMap {desc_name};") + + # `source` is in the form of `&var_x`, where `var_x` is the data pointer + # (CUdeviceptr); we dereference `source` and cast to `void*` to pass to + # the data pointer of the source tensor to the helper function + # `init{1,2}DTMADescriptor` + ptr = f"reinterpret_cast(*({source}))" + dims = ", ".join(self.val_to_arg_str(dim) for dim in desc.dims) + block_dims = ", ".join(self.val_to_arg_str(dim) for dim in desc.block_dims) + element_size = self.val_to_arg_str(desc.element_size) + fn = f"init{desc.rank}DTMADescriptor" + args = f"&{desc_name}, {ptr}, {dims}, {block_dims}, {element_size}" + self.writeline(f"{fn}({args});") + + def _generate_stable_tma_descriptor(self, desc): + source = self.generate_args_decl( + code=self, + call_args=[self.val_to_arg_str(desc.tensor)], + arg_types=[desc.tensor.get_dtype()], + arg_signatures=[None], + # these args are passed to initNDTMADescriptor, which is NOT a triton kernel + is_triton_kernel=False, + ) + + desc_name = desc.name + # Pack the relevant information into a StableTMADescriptor struct. + # See [Note: AOTI TMA Stable handling] for more details. + self.writeline(f"alignas(64) StableTMADescriptor {desc_name};") + + def fill_array(name, values): + for i, val in enumerate(values): + self.writeline(f"{name}[{i}] = {val};") + + ptr = f"reinterpret_cast(*({source}))" + rank = len(desc.tensor.get_size()) + + fill_array(f"{desc_name}.block_shape", desc.block_shape) + fill_array(f"{desc_name}.global_shape", desc.tensor.get_size()) + fill_array(f"{desc_name}.strides", desc.tensor.get_stride()) + + element_size = self.val_to_arg_str(desc.tensor.get_dtype().itemsize) + fn = "initTMADescriptor" + args = ", ".join( + str(x) + for x in [ + f"&{desc_name}.m", + ptr, + element_size, + rank, + f"{desc_name}.block_shape", + f"{desc_name}.global_shape", + f"{desc_name}.strides", + ] + ) + self.writeline(f"{fn}({args});") + + def generate_args_decl( + self, + code: IndentedBuffer | Self, + call_args, + arg_types, + arg_signatures, + is_triton_kernel=True, + scratch_spaces: dict[str, int] | None = None, + ): + """ + Generates any declarations of args to pass into a kernel call, and then returns the arg names. + + In more detail: + * declarations: e.g. this function has a side effect of generating lines like `auto var_0 = ...;` + * returns: a string with the list of args, e.g. "var_0, var_1" + + call_args: list of call arguments + arg_types: list of argument types + arg_signatures: list with signatures of all the args + is_triton_kernel: whether these are passed into a triton kernel or not. In particular, + calls to triton kernels will have an additional global scratch space + arg injected at the front of the arg list. + """ + new_args: list[str] = [] + + def process_tma_stable_arg(arg, arg_type, arg_signature, var_name): + # [Note: AOTI TMA Stable handling] + # For most args, a single arg passed to the python triton interface + # maps to a single arg in the cubin interface. However, for host-side + # TMA descriptors, a single python arg turns into 1 + 2 * N args in the + # cubin interface (where N is the rank). + # + # To do this: at TMA codegen time (for aoti), we generate a struct + # (StableTMADescriptor) containing the necessary information; and then + # when we call the function (i.e. here), we unpack the struct members. + code.writeline(f"auto {var_name} = {cexpr(arg)};") + return _unpack_tma_descriptor_args(var_name, arg_signature) + + def process_args(arg, arg_type, arg_signature=None): + var_name = f"var_{next(self.arg_var_id)}" + # ignore tma descriptors, as host-side TMA descriptors need + # to be passed to the compiled Triton kernel by value + if isinstance(arg_type, UnwrapUnspecArg) and not signature_is_tma_desc( + arg_signature + ): + self.codegen_tensor_item( + arg_type.dtype, + arg, + var_name, + indented_buffer=code, + ) + new_args.append(f"&{var_name}") + elif isinstance(arg_type, torch_dtype) and not signature_is_tma_desc( + arg_signature + ): + device_ptr_type = self.device_codegen.cpp_device_ptr() + code.writeline( + maybe_hipify_code_wrapper( + f"{device_ptr_type} {var_name} = reinterpret_cast<{device_ptr_type}>({arg}.data_ptr());" + ) + ) + new_args.append(f"&{var_name}") + # For symbolic call arguments, examine the arg signatures from triton meta + # to explicitly cast to the right type + # Reason: `auto` can infer unexpected type against kernel input signature. + elif ( + isinstance(arg_type, type(SymbolicCallArg)) + and arg_signature is not None + and arg_signature in TRITON_SIGNATURE_TO_CPP + ): + code.writeline( + f"{TRITON_SIGNATURE_TO_CPP[arg_signature]} {var_name} = {cexpr(arg)};" + ) + new_args.append(f"&{var_name}") + elif arg_type in (sympy.Integer, int): + code.writeline(f"int {var_name} = {cexpr(arg)};") + new_args.append(f"&{var_name}") + elif arg_type in (sympy.Float, float): + # Use signature type if available, otherwise default to float + cpp_type = TRITON_SIGNATURE_TO_CPP.get( # pyrefly: ignore[no-matching-overload] + arg_signature, "float" + ) + code.writeline(f"{cpp_type} {var_name} = {cexpr(arg)};") + new_args.append(f"&{var_name}") + elif arg_signature and arg_signature.startswith("tensordesc<"): + new_args.extend( + process_tma_stable_arg(arg, arg_type, arg_signature, var_name) + ) + else: + code.writeline(f"auto {var_name} = {cexpr(arg)};") + new_args.append(f"&{var_name}") + + for arg, arg_type, arg_signature in zip_longest( + call_args, arg_types, arg_signatures + ): + process_args(arg, arg_type, arg_signature) + + for scratch_name, workspace_size in (scratch_spaces or {}).items(): + if ( + is_triton_kernel + and ( + scratch := self.device_codegen.cpp_scratch( + next(self.arg_var_id), + workspace=TritonScratchWorkspace( + size=workspace_size, + generate_dtype_str=( + lambda: self.codegen_dtype(torch.uint8) + ), + ), + prefix=scratch_name, + ) + ) + is not None + ): + scratch_def, scratch_var = scratch + code.writelines([maybe_hipify_code_wrapper(x) for x in scratch_def]) + new_args.append(f"&{scratch_var}") + + return ", ".join(new_args) + + 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, + ): + """ + Override the default value of argument 'gpu' to True here. + generate_kernel_call can still be called with gpu=False because of + a mix of cpu kernels and gpu kernels. + """ + device = device or V.graph.get_current_device_or_throw() + if device.type == "cpu": + # Even in CppWrapperGpu, we may see cpp kernels + return CppWrapperCpu._generate_kernel_call_helper( + self, + kernel_name, + call_args, + device=device, + triton=triton, + arg_types=arg_types, + raw_keys=raw_keys, + raw_args=raw_args, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + ) + + if ( + triton + and config.triton.autotune_at_compile_time + and kernel_name not in self.kernel_autotune_names + ): + # Call PythonWrapperCodegen to create the autotune code block + PythonWrapperCodegen._generate_kernel_call_helper( + self, + kernel_name, + call_args, + device=device, + triton=triton, + arg_types=arg_types, + raw_keys=raw_keys, + raw_args=raw_args, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + original_fxnode_name=original_fxnode_name, + ) + + if ( + V.graph.aot_mode + and current_stream_idx is not None + and current_stream_idx != 0 + ): + stream = get_stream_name(current_stream_idx) + else: + stream = self.write_get_raw_stream(device.index, graph_name) + + if triton: + call_args, arg_types = self.prepare_triton_wrapper_args( + call_args, + # pyrefly: ignore [bad-argument-type] + arg_types, + ) + + # For lazy compile mode with TMA, extract underlying tensor names + tma_tensor_args: dict[str, str] = {} + is_lazy_compile = config.triton.autotune_at_compile_time is False + if is_lazy_compile and raw_args and triton_meta: + signature = triton_meta.get("signature", {}) + raw_keys_list = raw_keys or [] + for key, raw_arg in zip(raw_keys_list, raw_args): + sig_type = signature.get(key, "") + if isinstance(sig_type, str) and signature_is_tma_desc(sig_type): + if isinstance(raw_arg, TMADescriptorStable): + # Get the underlying tensor name + tensor_name = raw_arg.get_tensor().get_name() + tma_tensor_args[key] = tensor_name + else: + raise AssertionError("Unsupported TMA descriptor type") + + wrapper_name = f"call_{kernel_name}" + if wrapper_name not in self._triton_call_wrappers: + self._triton_call_wrappers[wrapper_name] = DeferredTritonCallWrapper( + wrapper_name, + kernel_name, + self._kernel_name_to_body, + arg_types, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + tma_tensor_args=tma_tensor_args, + ) + + # For TMA in lazy compile mode, add tensor args to the call + if is_lazy_compile and tma_tensor_args: + for tensor_name in tma_tensor_args.values(): + call_args.append(tensor_name) + arg_types.append( + torch.float32 + ) # dtype doesn't matter, just need tensor type + + # AOTI side uses this->device_idx_ so the model honors runtime device + # assignment; JIT side has no this->device_idx_ in scope, so use the + # concrete graph device index. Similarly, AOTI side always uses the + # `stream` function parameter of run_impl, while JIT side uses the + # locally-declared stream{idx} (see _codegen_entry_impl_prologue). + aoti_device_idx = ( + "this->device_idx_" if V.graph.aot_mode else str(device.index) + ) + jit_device_idx = str(device.index) + jit_call_args = [*call_args, jit_device_idx, stream] + aot_call_args = [*call_args, aoti_device_idx, "stream"] + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + jit_call_args[: len(arg_types)], kernel_name, arg_types, None + ) + # DebugPrinterManager is AOTI-only: route its writes through + # writeline_aot so they're dropped on the JIT side (no-op for the + # pure-JIT IndentedBuffer; AOT-only for DualIndentedBuffer). Without + # this, the JIT buffer would receive before/after-launch prints + # after the JIT launch, reporting post-launch state as pre-launch. + with self.set_writeline(self.wrapper_call, self.wrapper_call.writeline_aot): + with debug_printer_manager: + self.wrapper_call.writeline_jit( + f"{wrapper_name}({', '.join(jit_call_args)});" + ) + self.wrapper_call.writeline_aot( + f"{wrapper_name}({', '.join(aot_call_args)}, " + f"kernels, this->cubin_dir_);" + ) + else: + casted = [] + # pyrefly: ignore [bad-argument-type, no-matching-overload] + for arg_type, arg in zip(arg_types, call_args): + new_arg = arg + if arg_type.endswith("*") and arg != "nullptr": + new_arg = f"{arg}.data_ptr()" + # pyrefly: ignore [bad-argument-type] + casted.append(f"({arg_type}){cexpr(new_arg)}") + call_args_str = ", ".join(casted) + # AOT: dispatch through AOTInductorModelKernels member. + # JIT: call the extern "C" symbol directly (resolved at link time + # via extra_flags pointing at the compiled .so). + kernel_prefix = "kernels." if V.graph.aot_mode else "" + self.writeline(f"{kernel_prefix}{kernel_name}({call_args_str}, {stream});") + + def prepare_triton_wrapper_args( + self, call_args: list[Any], arg_types: list[Any] + ) -> tuple[list[Any], list[Any]]: + if len(call_args) != len(arg_types): + raise AssertionError((call_args, arg_types)) + new_args = [] + new_args_types = [] + for arg, arg_type in zip(call_args, arg_types): + if isinstance(arg, str): + if isinstance(arg_type, torch_dtype) and should_unwrap_unspec_arg(arg): + # dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar + arg_type = UnwrapUnspecArg(dtype=arg_type) + new_args.append(arg) + elif isinstance(arg, bool): + new_args.append(str(arg).lower()) + elif isinstance(arg, (int, float, SymbolicCallArg)): + if isinstance(arg, float): + new_args.append(self.generate_float_value(arg)) + else: + new_args.append(str(arg)) + else: + new_args.append(cexpr(V.graph.sizevars.simplify(arg))) + new_args_types.append(arg_type) + return new_args, new_args_types + + def make_zero_buffer(self, name): + return f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_zero_({name}.get()));" + + +@dataclasses.dataclass +class UnwrapUnspecArg: + """Marker that we need to call .item() on the tensor""" + + dtype: torch_dtype diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_mps.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_mps.py new file mode 100644 index 0000000000000000000000000000000000000000..8ddeeed7678d8704a8ed9221be5ffc9534321fa6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpp_wrapper_mps.py @@ -0,0 +1,306 @@ +from typing import Any + +import sympy + +import torch +from torch.utils._ordered_set import OrderedSet + +from ..ir import GraphPartitionSignature +from ..runtime.hints import TritonMeta +from ..virtualized import V +from .cpp_wrapper_cpu import CppWrapperCpu +from .cpp_wrapper_gpu import CppWrapperGpu +from .wrapper import KernelCallLine, PythonWrapperCodegen + + +class CppWrapperMps(CppWrapperGpu): + """ + Generates cpp wrapper for running on MPS and calls metal kernels + """ + + def __init__(self) -> None: + super().__init__() + self._used_kernel_names: OrderedSet[str] = OrderedSet() + self._lambda_counter: int = 0 + + @staticmethod + def create( + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: GraphPartitionSignature | None = None, + ) -> "CppWrapperMps": + return CppWrapperMps() + + def _generate_kernel_call_helper( + self, + kernel_name: str, + call_args: list[str], + *, + device: torch.device | None = None, + triton: bool = True, + arg_types: tuple[Any, ...] | None = None, + raw_keys: tuple[Any, ...] | None = None, + raw_args: tuple[Any, ...] | None = None, + triton_meta: TritonMeta | None = None, + inductor_meta: dict[str, Any] | None = None, + graph_name: str = "", + original_fxnode_name: str | None = None, + current_stream_idx: int | None = None, + ) -> None: + """ + Generates MPS kernel call code. It should look something like: + ``` + auto mps_lib_0_lambda = [&](AOTIMetalKernelFunctionHandle handle) { + aoti_torch_mps_start_encoding(handle); + aoti_torch_mps_set_arg_tensor(handle, 0, buf0); + aoti_torch_mps_set_arg_tensor(handle, 1, arg0_1); + aoti_torch_mps_set_arg_tensor(handle, 2, arg1_1); + aoti_torch_mps_dispatch_single(handle, static_cast(10LL)); + }; + + std::function mps_lib_0_func_wrapper = mps_lib_0_lambda; + aoti_torch_mps_run_command_block(get_mps_lib_0_handle(), aoti_torch_mps_shared_callback, &mps_lib_0_func_wrapper); + ``` + """ + device = device or V.graph.get_current_device_or_throw() + if device.type == "cpu": + # Even in CppWrapperGpu, we may see cpp kernels + return CppWrapperCpu._generate_kernel_call_helper( + self, + kernel_name, + call_args, + device=device, + triton=triton, + arg_types=arg_types, + raw_keys=raw_keys, + raw_args=raw_args, + triton_meta=triton_meta, + inductor_meta=inductor_meta, + ) + + if device.type != "mps": + raise AssertionError(f"expected device.type == 'mps', got {device.type}") + + if arg_types is None: + raise AssertionError("expected arg_types to not be None") + + new_args = [] + for idx, (arg, arg_type) in enumerate(zip(call_args[:-2], arg_types[:-2])): + if isinstance(arg_type, torch.dtype): + new_args.append(f"aoti_torch_mps_set_arg_tensor(handle, {idx}, {arg});") + elif arg_type in (int, sympy.core.symbol.Symbol): + new_args.append(f"aoti_torch_mps_set_arg_int(handle, {idx}, {arg});") + else: + raise NotImplementedError( + f"Unsupported arg type {arg_type} for arg {arg} for kernel {kernel_name}" + ) + + threads, group_size = call_args[-2], call_args[-1] + if threads is None: + raise NotImplementedError("No threads or group_size provided") + + # Check if threads is a single value or an array-like structure + threads_str = threads + is_single_value = ( + threads_str.startswith("{") + and threads_str.endswith("}") + and threads_str.count(",") == 0 + ) or not threads_str.startswith(("{", "[")) + + if is_single_value: + # Extract single value from braces if present + if threads_str.startswith("{") and threads_str.endswith("}"): + single_value = threads_str[1:-1].strip() # Remove braces + else: + single_value = threads_str + + if group_size is None: + new_args.append( + f"aoti_torch_mps_dispatch_single(handle, {single_value});" + ) + else: + # Extract group size value if it's also in braces + group_size_str = group_size + if group_size_str.startswith("{") and group_size_str.endswith("}"): + group_size_value = group_size_str[1:-1].strip() + else: + group_size_value = group_size_str + new_args.append( + f"aoti_torch_mps_dispatch_single_with_group_size(handle, {single_value}, {group_size_value});" + ) + else: + # Handle array case - need to convert initializer list to array + # Use kernel name to make variable names unique + threads_var = f"{kernel_name}_threads_array" + group_size_var = f"{kernel_name}_group_size_array" + + # Extract array size from the initializer list string + def get_array_size(array_str: str) -> int: + # Remove braces and whitespace + content = array_str.strip() + if content.startswith("{") and content.endswith("}"): + content = content[1:-1].strip() + + if not content: # Empty array + return 0 + + # Count elements by counting commas, accounting for nested structures + depth = 0 + comma_count = 0 + for char in content: + if char in "({[<": + depth += 1 + elif char in ")}]>": + depth -= 1 + elif char == "," and depth == 0: + comma_count += 1 + + return comma_count + 1 # Number of elements = commas + 1 + + threads_size = get_array_size(threads_str) + + if group_size is None: + new_args.append("{") + new_args.append(f" uint64_t {threads_var}[] = {threads};") + new_args.append( + f" aoti_torch_mps_dispatch_array(handle, {threads_var}, {threads_size});" + ) + new_args.append("}") + else: + group_size_str = group_size + group_size_size = get_array_size(group_size_str) + new_args.append("{") + new_args.append(f" uint64_t {threads_var}[] = {threads};") + new_args.append(f" uint64_t {group_size_var}[] = {group_size};") + dispatch_args = f"handle, {threads_var}, {threads_size}, {group_size_var}, {group_size_size}" + new_args.append( + f" aoti_torch_mps_dispatch_array_with_group_size({dispatch_args});" + ) + new_args.append("}") + + # debug printer related logic for cpp kernel type. + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + call_args[:-2], + kernel_name, + None, + None, + "cpp", + ) + with debug_printer_manager: + self.write_mps_kernel_call(kernel_name, new_args) + + def write_mps_kernel_call(self, name: str, call_args: list[str]) -> None: + # Generate unique variable names to avoid duplicate declarations + # when the same MPS lib is used multiple times + unique_suffix = self._lambda_counter + self._lambda_counter += 1 + + lambda_name = f"{name}_lambda_{unique_suffix}" + wrapper_name = f"{name}_func_wrapper_{unique_suffix}" + + # Generate the function call code (in current location) + # Create lambda that captures by reference and pass its pointer through void* + self.writeline( + f"auto {lambda_name} = [&](AOTIMetalKernelFunctionHandle handle) {{" + ) + self.writeline(" aoti_torch_mps_start_encoding(handle);") + + # Output call args directly since we're capturing by reference + for call_arg in call_args: + self.writeline(f" {call_arg}") + self.writeline("};") + self.writeline("") + + # Pass lambda pointer through void* + self.writeline( + f"std::function {wrapper_name} = {lambda_name};" + ) + self.writeline( + f"aoti_torch_mps_run_command_block(get_{name}_handle(), aoti_torch_mps_shared_callback, &{wrapper_name});" + ) + + @staticmethod + def get_device_include_path_aot(device: str) -> str: + return ( + "#include \n" + "#include " + ) + + def codegen_additional_funcs(self) -> None: + """ + Generate thread-safe lazy singleton pattern for MPS shader libraries with RAII cleanup. + + The generated code will look like: + ``` + AOTIMetalKernelFunctionHandle get_mps_lib_0_handle() { + static auto kernel_handle = []() { + AOTIMetalShaderLibraryHandle lib_handle = nullptr; + AOTIMetalKernelFunctionHandle kern_handle = nullptr; + + aoti_torch_mps_create_shader_library(mps_lib_0_source, &lib_handle); + aoti_torch_mps_get_kernel_function(lib_handle, "generated_kernel", &kern_handle); + + // RAII wrapper with custom deleter + auto lib_deleter = [](AOTIMetalShaderLibraryHandle h) { + if (h) aoti_torch_mps_delete_shader_library(h); + }; + + using LibDeleter = decltype(lib_deleter); + using LibPtr = std::unique_ptr; + + // Return pair of kernel handle and library smart pointer for cleanup + return std::make_pair(kern_handle, LibPtr(lib_handle, lib_deleter)); + }(); + return kernel_handle.first; + } + ``` + """ + + # Add shimified handles and functions + shader_libraries: OrderedSet[str] = OrderedSet() + for line in self.lines: + if not isinstance(line, KernelCallLine): + continue + if line.device.type != "mps": + continue + + # Extract library name from kernel name (e.g., "mps_lib_0" from kernel calls) + if line.kernel_name not in self._used_kernel_names: + self._used_kernel_names.add(line.kernel_name) + shader_libraries.add(line.kernel_name) + + # NOTE: For shimified version, we expect the shader source constant to be generated + # by the existing MPS shader generation process, but instead of instantiating the + # DynamicMetalShaderLibrary directly, we'll use our shim functions. + # The existing codegen should produce something like: + # const char* mps_lib_0_source = R"MTL(...shader_source...)MTL"; + # instead of: + # at::native::mps::DynamicMetalShaderLibrary mps_lib_0(R"MTL(...shader_source...)MTL"); + + # Generate thread-safe lazy singleton with RAII for each library + for lib_name in shader_libraries: + self.prefix.splice(f""" +AOTIMetalKernelFunctionHandle get_{lib_name}_handle() {{ + static auto kernel_handle = []() {{ + AOTIMetalShaderLibraryHandle lib_handle = nullptr; + AOTIMetalKernelFunctionHandle kern_handle = nullptr; + + aoti_torch_mps_create_shader_library({lib_name}_source, &lib_handle); + aoti_torch_mps_get_kernel_function(lib_handle, "generated_kernel", &kern_handle); + + // RAII wrapper with custom deleter + auto lib_deleter = [](AOTIMetalShaderLibraryHandle h) {{ + if (h) aoti_torch_mps_delete_shader_library(h); + }}; + + using LibDeleter = decltype(lib_deleter); + using LibPtr = std::unique_ptr; + + // Return pair of kernel handle and library smart pointer for cleanup + return std::make_pair(kern_handle, LibPtr(lib_handle, lib_deleter)); + }}(); + return kernel_handle.first; +}} +""") diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpu_device_op_overrides.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpu_device_op_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..1843688e900e27d0bceb8daae0d49b333209195b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cpu_device_op_overrides.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from textwrap import dedent + +from .common import DeviceIdx, DeviceOpOverrides, register_device_op_overrides + + +class CpuDeviceOpOverrides(DeviceOpOverrides): + def import_get_raw_stream_as(self, name: str) -> str: + return dedent( + """ + def get_raw_stream(_): + return 0 + """ + ) + + def cpp_kernel_type(self) -> str: + return "void*" + + def set_device(self, device_idx: DeviceIdx) -> str: + return "pass" + + def synchronize(self) -> str: + return "pass" + + def device_guard(self, device_idx: DeviceIdx) -> str: + return "torch._ops.contextlib.nullcontext()" + + +register_device_op_overrides("cpu", CpuDeviceOpOverrides()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b5113f8ecefa0b768c98c270a1e9ccc196d07b7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/compile_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/compile_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..152c7c665b8203f0d37082f7ab8ecebc63703464 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/compile_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/cuda_env.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/cuda_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c86dad93bc51847b95ab4423e8c812f5d318bb1a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/cuda_env.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/device_op_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/device_op_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..632da3a0a29fdf034f373cec23802851c4f64d77 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/__pycache__/device_op_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/compile_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/compile_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f795fe56f2ff06d539f514ab7cd9498fbde39bc4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/compile_utils.py @@ -0,0 +1,384 @@ +# mypy: allow-untyped-defs +import logging +import os +import re +import shutil + +import torch +from torch._inductor import config +from torch._inductor.codegen.cuda import cuda_env +from torch._inductor.cpp_builder import _set_gpu_runtime_env, _transform_cuda_paths +from torch._inductor.utils import is_linux +from torch.utils._ordered_set import OrderedSet + + +if config.is_fbcode(): + from triton.fb.build import build_paths + + +log = logging.getLogger(__name__) +autotuning_log = torch._logging.getArtifactLogger(__name__, "autotuning") + + +def use_re_build() -> bool: + """ + Use for CUTLASS compilation only right now. + """ + if config.is_fbcode() and not cuda_env.nvcc_exist(_cuda_compiler()): + from triton.fb.re_build_helper import should_build_locally + + return not should_build_locally() + return False + + +def _cutlass_path() -> str | None: + if config.is_fbcode(): + from libfb.py import parutil + + return parutil.get_dir_path("cutlass-4-headers") + else: + from torch._inductor.codegen.cutlass.utils import try_import_cutlass + + return config.cutlass.cutlass_dir if try_import_cutlass() else None + + +def _cutlass_paths() -> list[str]: + return [ + "include", + "tools/library/include", + "tools/library/src", + "tools/util/include", + ] + + +def _clone_cutlass_paths(build_root: str) -> list[str]: + cutlass_root = _cutlass_path() + if cutlass_root is None: + return [] + paths = [] + for path in _cutlass_paths(): + old_path = os.path.join(cutlass_root, path) + new_path = os.path.join(build_root, path) + shutil.copytree(old_path, new_path, dirs_exist_ok=True) + paths.append(new_path) + return paths + + +def _cutlass_include_paths() -> list[str]: + cutlass_root = _cutlass_path() + if cutlass_root is None: + return [] + return [ + # Use realpath to get canonical absolute paths, in order not to mess up cache keys + os.path.realpath(os.path.join(cutlass_root, path)) + for path in _cutlass_paths() + ] + + +def _cuda_compiler() -> str | None: + if cuda_env.nvcc_exist(config.cuda.cuda_cxx): + return config.cuda.cuda_cxx + if config.is_fbcode(): + return os.path.join(build_paths.sdk_home, "bin", "nvcc") + if cuda_env.nvcc_exist(os.getenv("CUDACXX")): + return os.getenv("CUDACXX", "") + if cuda_env.nvcc_exist(os.getenv("CUDA_HOME")): + return os.path.realpath(os.path.join(os.getenv("CUDA_HOME", ""), "bin/nvcc")) + return "nvcc" + + +def _cuda_lib_options() -> list[str]: + """ + Util function for CUTLASS backend to find the correct CUDA libraries. + """ + _set_gpu_runtime_env() # cpp_extension consults the env + from torch.utils import cpp_extension + + lpaths = cpp_extension.library_paths(device_type="cuda") + if use_re_build(): + lpaths += [ + build_paths.sdk_lib, + os.path.join(build_paths.sdk_lib, "stubs"), + ] + extra_ldflags: list[str] = [] + if is_linux(): + _transform_cuda_paths(lpaths) + for path in lpaths: + if "torch/lib" in path: + # don't want to depend on pytorch + continue + extra_ldflags.append(f"-L{path}") + # -rpath ensures the DLL can find its dependencies when loaded, even + # if the library path is non-standard. + # But do not add the stubs folder to rpath as the driver is expected to be found at runtime + if os.path.basename(path) != "stubs": + extra_ldflags.extend(["-Xlinker", f"-rpath={path}"]) + extra_ldflags.append("-lcuda") + extra_ldflags.append("-lcudart") + else: + raise NotImplementedError( + "Unsupported env, failed to find cuda libs! Currently only Linux is supported." + ) + return extra_ldflags + + +def _nvcc_host_compiler_options() -> list[str]: + return [ + "-fPIC", + "-fno-strict-aliasing", + "-fvisibility=hidden", + "-Wconversion", + ] + + +def _cuda_arch_with_compile_suffix(arch: str) -> str: + arch = _normalize_cuda_arch(arch) + if arch == "90": + # Required by cutlass compilation. + return "90a" + if arch == "100": + return "100a" + if arch == "101": + return "101a" + if arch == "103": + return "103a" + if arch == "107": + return "107a" + if arch == "110": + return "110a" + if arch == "120": + return "120a" + if arch == "121": + return "121a" + return arch + + +def _nvcc_arch_as_compile_option() -> str | None: + arch = cuda_env.get_cuda_arch() + if arch is None: + return arch + return _cuda_arch_with_compile_suffix(arch) + + +def _nvcc_arch_as_compile_option_or_raise() -> str: + arch = _nvcc_arch_as_compile_option() + if arch is None: + raise RuntimeError("Unable to determine CUDA architecture") + return arch + + +def _normalize_cuda_arch(arch: str) -> str: + arch = arch.removeprefix("sm_").removeprefix("compute_").replace(".", "") + if not re.fullmatch(r"\d+[a-z]?", arch): + raise ValueError(f"Unrecognized CUDA arch: {arch}") + return arch + + +def _cuda_arch_number(arch: str) -> int: + arch = _normalize_cuda_arch(arch) + if arch[-1].isalpha(): + arch = arch[:-1] + return int(arch) + + +def _cuda_arch_suffix(arch: str) -> str: + arch = _normalize_cuda_arch(arch) + return arch[-1] if arch[-1].isalpha() else "" + + +def _cuda_arch_same_generation(arch: str, other: str) -> bool: + arch = _normalize_cuda_arch(arch) + other = _normalize_cuda_arch(other) + if _cuda_arch_suffix(arch) or _cuda_arch_suffix(other): + return arch == other + return _cuda_arch_number(arch) == _cuda_arch_number(other) + + +def _cuda_arch_is_compatible_with_current(arch: str, current_arch: str) -> bool: + if _cuda_arch_suffix(current_arch): + return _normalize_cuda_arch(arch) == _normalize_cuda_arch(current_arch) + return _cuda_arch_number(arch) >= _cuda_arch_number(current_arch) + + +def _aoti_cuda_target_arch() -> str: + if config.cuda.arch is not None: + return _cuda_arch_with_compile_suffix(str(config.cuda.arch)) + return _nvcc_arch_as_compile_option_or_raise() + + +def _parse_gencode_options(flags: list[str]) -> OrderedSet[tuple[str, str]]: + options: OrderedSet[tuple[str, str]] = OrderedSet() + for flag in flags: + if flag.startswith("-gencode="): + option = flag.removeprefix("-gencode=") + elif flag.startswith("-gencode "): + option = flag.removeprefix("-gencode ") + else: + continue + + try: + _, code = option.split(",code=", 1) + except ValueError: + continue + code = code.removeprefix("[").removesuffix("]") + for entry in code.split(","): + try: + kind, arch = entry.split("_", 1) + except ValueError: + continue + if kind in ("sm", "compute"): + options.add((kind, _normalize_cuda_arch(arch))) + return options + + +def _cuda_multi_arch_gencode_options(current_arch: str | None = None) -> list[str]: + """ + Return nvcc -gencode option payloads for AOTI CUDA fatbins. + + AOTI captures PTX for the architecture Triton compiled on. That PTX can be + used for the current architecture and newer architectures, but not older + ones, so explicit TORCH_CUDA_ARCH_LIST entries below the current target are + intentionally ignored. + """ + if not current_arch: + current_arch = _nvcc_arch_as_compile_option_or_raise() + current_arch = _normalize_cuda_arch(current_arch) + options: OrderedSet[tuple[str, str]] = OrderedSet() + + arch_list = os.environ.get("TORCH_CUDA_ARCH_LIST") + if arch_list and arch_list != "native": + from torch.utils.cpp_extension import _get_cuda_arch_flags + + for kind, arch in _parse_gencode_options(_get_cuda_arch_flags([])): + if kind == "sm" and _cuda_arch_is_compatible_with_current( + arch, current_arch + ): + options.add((kind, arch)) + elif kind == "sm": + log.warning( + "Ignoring TORCH_CUDA_ARCH_LIST entry sm_%s for AOTI CUDA " + "multi-arch packaging because it is not compatible with " + "target arch %s.", + arch, + current_arch, + ) + + if not any( + kind == "sm" and _cuda_arch_same_generation(arch, current_arch) + for kind, arch in options + ): + options.add(("sm", current_arch)) + + # Always keep a PTX image for the compile architecture as the fallback for + # GPUs newer than the generated SASS images. + options.add(("compute", current_arch)) + + def sort_key(option: tuple[str, str]) -> tuple[int, int, str]: + kind, arch = option + return (_cuda_arch_number(arch), 0 if kind == "sm" else 1, arch) + + return [ + f"arch=compute_{arch},code={kind}_{arch}" + for kind, arch in sorted(options, key=sort_key) + ] + + +def _cuda_gencode_options_have_non_current_sass( + gencode_options: list[str], current_arch: str | None = None +) -> bool: + if not current_arch: + current_arch = _nvcc_arch_as_compile_option_or_raise() + current_arch = _normalize_cuda_arch(current_arch) + for kind, arch in _parse_gencode_options( + [f"-gencode={option}" for option in gencode_options] + ): + if kind == "sm" and not _cuda_arch_same_generation(arch, current_arch): + return True + return False + + +def _nvcc_compiler_options() -> list[str]: + arch = _nvcc_arch_as_compile_option_or_raise() + code = [f"sm_{arch}", f"compute_{arch}"] + if config.cuda.enable_cuda_lto: + code += [f"lto_{arch}"] + options = [ + "-t=0", + "-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1", + "-DCUTLASS_ENABLE_SM90_EXTENDED_MMA_SHAPES=1", + "-DCUTE_SM90_EXTENDED_MMA_SHAPES_ENABLED", + "-w", + f"-gencode=arch=compute_{arch},code=[{','.join(code)}]", + config.cutlass.compile_opt_level, + "-std=c++20", + "--expt-relaxed-constexpr", + "-DNDEBUG", + ] + if config.is_fbcode(): + options.extend(["-ccbin", os.path.dirname(build_paths.gcc)]) + if config.cutlass.enable_debug_info: + options.extend(["-lineinfo", "-g", "-DCUTLASS_DEBUG_TRACE_LEVEL=1"]) + if config.cuda.enable_ptxas_info: + options.extend( + [ + "--keep", # Keep the intermediate files for debugging (including ptx, sass, cubin etc.) + "--ptxas-options=--warn-on-local-memory-usage", # warn us if local memory is used in CUDA Kernels + "--ptxas-options=--warn-on-spills", # warn us if register spilling happens in CUDA Kernels + "--resource-usage", # Report on CUDA resource usage (shared mem, registers etc.) + "--source-in-ptx", + ] + ) # Annotate the ptx file with source information + if config.cutlass.use_fast_math: + options.extend( + [ + "--use_fast_math", + "-DCUTLASS_USE_TANH_FOR_SIGMOID=1", + ] + ) + return options + + +def cuda_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 = [] + if use_re_build(): + build_path = os.path.dirname(dst_file) + include_paths = _clone_cutlass_paths(build_path) + src_files = [os.path.basename(src_file) for src_file in src_files] + dst_file = os.path.basename(dst_file) + else: + include_paths = _cutlass_include_paths() + cuda_lib_options = _cuda_lib_options() + nvcc_host_compiler_options = _nvcc_host_compiler_options() + nvcc_compiler_options = _nvcc_compiler_options() + options = ( + nvcc_compiler_options + + extra_args + + [ + f"-Xcompiler {opt}" if "=" in opt else f"-Xcompiler={opt}" + for opt in nvcc_host_compiler_options + ] + + ["-I" + path for path in include_paths] + + cuda_lib_options + ) + src_file = " ".join(src_files) + res = "" + if dst_file_ext == "o": + res = f"{_cuda_compiler()} {' '.join(options)} -c -o {dst_file} {src_file}" + elif dst_file_ext == "so": + options.append("-shared") + res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}" + elif dst_file_ext == "exe": + res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}" + else: + raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!") + if log.isEnabledFor(logging.DEBUG): + log.debug("CUDA command: %s", res) + else: + autotuning_log.debug("CUDA command: %s", res) + return res diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/cuda_env.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/cuda_env.py new file mode 100644 index 0000000000000000000000000000000000000000..e12bd94d2a677f1e4c03fba78e7fa3b288d046b7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/cuda_env.py @@ -0,0 +1,54 @@ +import functools +import logging +import shutil + +import torch +from torch._inductor.utils import clear_on_fresh_cache + +from ... import config + + +log = logging.getLogger(__name__) + + +@clear_on_fresh_cache +@functools.lru_cache(1) +def get_cuda_arch() -> str | None: + try: + cuda_arch = config.cuda.arch + if cuda_arch is None: + # Get Compute Capability of the first Visible device + major, minor = torch.cuda.get_device_capability(0) + return str(major * 10 + minor) + return str(cuda_arch) + except Exception: + log.exception("Error getting cuda arch") + return None + + +@clear_on_fresh_cache +@functools.lru_cache(1) +def is_datacenter_blackwell_arch() -> bool: + arch = get_cuda_arch() + if arch is None: + return False + arch_number = int(arch) + return arch_number >= 100 and arch_number < 110 + + +@clear_on_fresh_cache +@functools.lru_cache(1) +def get_cuda_version() -> str | None: + try: + cuda_version = config.cuda.version + if cuda_version is None: + cuda_version = torch.version.cuda + return cuda_version + except Exception: + log.exception("Error getting cuda version") + return None + + +@functools.cache +def nvcc_exist(nvcc_path: str | None = "nvcc") -> bool: + return nvcc_path is not None and shutil.which(nvcc_path) is not None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/device_op_overrides.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/device_op_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..ab67a1ee63e3a441a9aeb2337e9759da905954e1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda/device_op_overrides.py @@ -0,0 +1,387 @@ +from __future__ import annotations + +import torch + +from ...runtime.hints import get_warp_size +from ..common import ( + DeviceIdx, + DeviceOpOverrides, + register_device_op_overrides, + TritonScratchWorkspace, +) + + +class CUDADeviceOpOverrides(DeviceOpOverrides): + """ + CUDA-specific codegen functions, see DeviceOpOverrides for details + """ + + def import_get_raw_stream_as(self, name: str) -> str: + return f"from torch._C import _cuda_getCurrentRawStream as {name}" + + def set_device(self, device_idx: DeviceIdx) -> str: + return f"torch.cuda.set_device({device_idx})" + + def synchronize(self) -> str: + return "torch.cuda.synchronize()" + + def device_guard(self, device_idx: DeviceIdx) -> str: + return f"torch.cuda._DeviceGuard({device_idx})" + + def current_device_idx_expr(self) -> str: + return "torch.cuda.current_device()" + + def current_stream(self) -> str: + return "torch.cuda.current_stream()" + + def cpp_device_guard(self) -> str: + return "at::cuda::CUDAGuard" + + def cpp_aoti_device_guard(self) -> str: + return "AOTICudaGuard" + + def cpp_stream_guard(self) -> str: + return "at::cuda::CUDAStreamGuard" + + def cpp_aoti_stream_guard(self) -> str: + return "AOTICudaStreamGuard" + + def cpp_getStreamFromExternal(self) -> str: + return "at::cuda::getStreamFromExternal" + + def kernel_header(self) -> str: + source_codes = """ + #include + #include + #include + """ + return source_codes + + def kernel_driver(self) -> str: + """Return C++ host-side helpers (loadKernel, launchKernel, CUDA_DRIVER_CHECK) + embedded in AOTI-generated wrapper code.""" + # NVIDIA devices have a warp size of 32, while AMD devices can have a + # warp size of 32 or 64 depending on the architecture. + source_codes = """ + #define CUDA_DRIVER_CHECK(EXPR) \\ + do { \\ + CUresult code = EXPR; \\ + const char *msg; \\ + CUresult code_get_error = cuGetErrorString(code, &msg); \\ + if (code_get_error != CUDA_SUCCESS) { \\ + throw std::runtime_error( \\ + std::string("CUDA driver error: ") + \\ + std::string("invalid error code!")); \\ + } \\ + if (code != CUDA_SUCCESS) { \\ + throw std::runtime_error( \\ + std::string("CUDA driver error: ") + \\ + std::string(msg)); \\ + } \\ + } while (0); + + static inline CUfunction loadKernel( + std::string filePath, + const std::string &funcName, + uint32_t sharedMemBytes, + const std::optional &cubinDir = std::nullopt, + std::vector* loaded_modules = nullptr) { + if (cubinDir) { + std::filesystem::path p1{*cubinDir}; + std::filesystem::path p2{filePath}; + filePath = (p1 / p2.filename()).string(); + } + + CUmodule mod; + CUfunction func; + CUDA_DRIVER_CHECK(cuModuleLoad(&mod, filePath.c_str())); + if (loaded_modules) { + loaded_modules->push_back(mod); + } + CUDA_DRIVER_CHECK(cuModuleGetFunction(&func, mod, funcName.c_str())); + if (sharedMemBytes > 0) { + CUDA_DRIVER_CHECK(cuFuncSetAttribute( + func, + CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, + sharedMemBytes + )) + } + return func; + } + + static inline CUfunction loadKernel( + const void* start, + const std::string &funcName, + uint32_t sharedMemBytes, + std::vector* loaded_modules = nullptr) { + CUmodule mod; + CUfunction func; + CUDA_DRIVER_CHECK(cuModuleLoadData(&mod, start)); + if (loaded_modules) { + loaded_modules->push_back(mod); + } + CUDA_DRIVER_CHECK(cuModuleGetFunction(&func, mod, funcName.c_str())); + if (sharedMemBytes > 0) { + CUDA_DRIVER_CHECK(cuFuncSetAttribute( + func, + CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES, + sharedMemBytes + )) + } + return func; + } + + static inline void launchKernel( + CUfunction func, + uint32_t gridX, + uint32_t gridY, + uint32_t gridZ, + uint32_t numWarps, + uint32_t sharedMemBytes, + void* args[], + cudaStream_t stream) { + CUDA_DRIVER_CHECK(cuLaunchKernel( + func, gridX, gridY, gridZ, __WARP_SIZE__*numWarps, 1, 1, sharedMemBytes, stream, args, nullptr + )); + } + """ + if torch.version.hip is not None and torch.cuda.is_available(): + device = torch.device("cuda", torch.cuda.current_device()) + warp_size = get_warp_size(device) + else: + warp_size = 32 + return source_codes.replace("__WARP_SIZE__", str(warp_size)) + + def tma_descriptor_helpers(self) -> str: + """ + CUDA helper functions for initializing TMA Descriptors on host side + """ + if torch.version.hip is not None: + raise RuntimeError("Host-side TMA descriptors not supported on HIP.") + + # helper functions for initializing 1D and 2D TMA descriptors in C++. borrowed from the Triton code here: + # Old APIs (fill(1|2)DTMADescriptor): + # https://github.com/triton-lang/triton/blob/6af4f88591c85de079d8a36a4d7dba67918e2b39/third_party/nvidia/backend/driver.c#L283 + # New APIs (fillTMADescriptor): + # https://github.com/triton-lang/triton/blob/main/third_party/nvidia/backend/driver.c#L283 + return """ + #if !defined(USE_ROCM) && defined(CUDA_VERSION) && CUDA_VERSION >= 12000 + [[maybe_unused]] static void init1DTMADescriptor( + CUtensorMap* m, + void* globalAddress, + uint64_t dim, + uint32_t blockDim, + uint32_t elementSize) { + uint64_t dims[1] = {dim}; + uint64_t globalStrides[1] = {dim * elementSize}; + uint32_t tensorDims[1] = {blockDim}; + uint32_t elementStrides[1] = {1}; + + CUtensorMapDataType type; + switch (elementSize) { + case 1: + type = CU_TENSOR_MAP_DATA_TYPE_UINT8; + break; + case 2: + type = CU_TENSOR_MAP_DATA_TYPE_UINT16; + break; + case 4: + type = CU_TENSOR_MAP_DATA_TYPE_UINT32; + break; + default: + throw std::runtime_error("elementSize must be 1, 2, or 4"); + } + + if (elementSize * blockDim < 32) { + throw std::runtime_error("block size too small"); + } + + int rank = 1; + + CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled( + m, type, rank, globalAddress, dims, + globalStrides, tensorDims, elementStrides, CU_TENSOR_MAP_INTERLEAVE_NONE, + CU_TENSOR_MAP_SWIZZLE_NONE, CU_TENSOR_MAP_L2_PROMOTION_NONE, + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE)); + } + + [[maybe_unused]] static void init2DTMADescriptor( + CUtensorMap* m, + void* globalAddress, + uint64_t dim1, + uint64_t dim0, + uint32_t blockDim1, + uint32_t blockDim0, + uint32_t elementSize) { + uint64_t dims[2] = {dim0, dim1}; + uint32_t tensorDims[2] = {blockDim0, blockDim1}; + uint64_t globalStrides[2] = {dims[0] * elementSize, + dims[0] * dims[1] * elementSize}; + uint32_t elementStrides[2] = {1, 1}; + + CUtensorMapDataType type; + switch (elementSize) { + case 1: + type = CU_TENSOR_MAP_DATA_TYPE_UINT8; + break; + case 2: + type = CU_TENSOR_MAP_DATA_TYPE_UINT16; + break; + case 4: + type = CU_TENSOR_MAP_DATA_TYPE_UINT32; + break; + default: + throw std::runtime_error("elementSize must be 1, 2, or 4"); + } + + int rank = 2; + + CUtensorMapSwizzle swizzle = CU_TENSOR_MAP_SWIZZLE_128B; + uint32_t contigDimSizeInByte = elementSize * tensorDims[0]; + if (contigDimSizeInByte >= 128) { + swizzle = CU_TENSOR_MAP_SWIZZLE_128B; + } else if (contigDimSizeInByte >= 64) { + swizzle = CU_TENSOR_MAP_SWIZZLE_64B; + } else if (contigDimSizeInByte >= 32) { + swizzle = CU_TENSOR_MAP_SWIZZLE_32B; + } else { + throw std::runtime_error("block size too small"); + } + + if (contigDimSizeInByte > 128) { + tensorDims[0] = 128 / elementSize; + } + + CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled( + m, type, rank, globalAddress, dims, + globalStrides, tensorDims, elementStrides, CU_TENSOR_MAP_INTERLEAVE_NONE, + swizzle, CU_TENSOR_MAP_L2_PROMOTION_L2_128B, + CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE)); + } + + [[maybe_unused]] static void initTMADescriptor( + CUtensorMap* m, + void* globalAddress, + int elemSize, + int rank, + uint32_t* blockSize, + uint64_t* shape, + uint64_t* stride + ) { + uint32_t elementStrides[5] = {1, 1, 1, 1, 1}; + uint32_t blockSizeInt[5]; + uint64_t shapeInt[5]; + uint64_t stridesLL[5]; + + // Reorder blockSize (reverse the order) + for (int i = 0; i < rank; ++i) { + blockSizeInt[rank - i - 1] = blockSize[i]; + } + + // Reorder shape (reverse the order) + for (int i = 0; i < rank; ++i) { + shapeInt[rank - i - 1] = shape[i]; + } + + // Reorder and calculate strides + for (int i = 0; i + 1 < rank; ++i) { + stridesLL[rank - i - 2] = elemSize * stride[i]; + } + stridesLL[rank - 1] = + shapeInt[rank - 1] * (rank == 1 ? elemSize : stridesLL[rank - 2]); + + CUtensorMapDataType type; + // In Triton this is computed ahead of time; but for simplicity + // in the PyTorch version we copied this code from the old + // TMA API handling (i.e. init2DTMADescriptor) + switch (elemSize) { + case 1: + type = CU_TENSOR_MAP_DATA_TYPE_UINT8; + break; + case 2: + type = CU_TENSOR_MAP_DATA_TYPE_UINT16; + break; + case 4: + type = CU_TENSOR_MAP_DATA_TYPE_UINT32; + break; + default: + throw std::runtime_error("elemSize must be 1, 2, or 4"); + } + + // Calculate the size of the most contiguous dimension in bytes + CUtensorMapSwizzle swizzle = CU_TENSOR_MAP_SWIZZLE_128B; + uint32_t contigDimSizeInByte = elemSize * blockSizeInt[0]; + if (rank == 1) { + // rank 1 should not be swizzled + swizzle = CU_TENSOR_MAP_SWIZZLE_NONE; + } else if (contigDimSizeInByte >= 128) { + swizzle = CU_TENSOR_MAP_SWIZZLE_128B; + } else if (contigDimSizeInByte >= 64) { + swizzle = CU_TENSOR_MAP_SWIZZLE_64B; + } else if (contigDimSizeInByte >= 32) { + swizzle = CU_TENSOR_MAP_SWIZZLE_32B; + } else { + throw std::runtime_error("block size too small"); + } + + CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled( + m, type, rank, globalAddress, + shapeInt, stridesLL, blockSizeInt, elementStrides, + CU_TENSOR_MAP_INTERLEAVE_NONE, (CUtensorMapSwizzle)swizzle, + CU_TENSOR_MAP_L2_PROMOTION_L2_128B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE)); + } + + struct StableTMADescriptor { + CUtensorMap m; + uint32_t block_shape[5]; + uint64_t global_shape[5]; + uint64_t strides[5]; + }; + #endif + """ + + def cpp_stream_type(self) -> str: + return "cudaStream_t" + + def aoti_get_stream(self) -> str: + return "aoti_torch_get_current_cuda_stream" + + def cpp_kernel_type(self) -> str: + return "CUfunction" + + def cpp_device_ptr(self) -> str: + return "CUdeviceptr" + + def cpp_scratch( + self, idx: int, workspace: TritonScratchWorkspace, prefix: str | None = None + ) -> tuple[list[str], str] | None: + prefix = f"{prefix}_" if prefix else "" + var_name = f"{prefix}scratch_{idx}" + if workspace.size > 0: + size_expr = ( + f"static_cast({workspace.size}) * grid_0 * grid_1 * grid_2" + ) + size_array = f"int64_t {var_name}_size[] = {{{size_expr}}};" + stride_array = f"int64_t {var_name}_stride[] = {{1}};" + device_type = "cached_torch_device_type_cuda" + device_idx = "device_idx_" + + return ( + [ + f"{size_array}", + f"{stride_array}", + f"AtenTensorHandle {var_name}_handle;", + ( + f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided(1, {var_name}_size, {var_name}_stride, " + f"{workspace.generate_dtype_str()}, {device_type}, {device_idx}, &{var_name}_handle));" + ), + f"RAIIAtenTensorHandle {var_name}_tensor({var_name}_handle);", + f"CUdeviceptr {var_name} = reinterpret_cast({var_name}_tensor.data_ptr());", + ], + var_name, + ) + else: + return [f"CUdeviceptr {var_name} = 0;"], var_name + + +register_device_op_overrides("cuda", CUDADeviceOpOverrides()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda_combined_scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda_combined_scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..e2636b543295adc951850dfcf4c7048f9a6d6b7d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cuda_combined_scheduling.py @@ -0,0 +1,301 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import logging +from typing import Any, TYPE_CHECKING + +from ..ir import MultiTemplateBuffer +from ..scheduler import ( + BaseSchedulerNode, + BaseScheduling, + FusedSchedulerNode, + Scheduler, + SchedulerNode, +) +from .cutedsl.cutedsl_scheduling import CuteDSLScheduling +from .cutlass.scheduling import CUTLASSScheduling +from .nv_universal_gemm.nv_universal_gemm_scheduling import NVUniversalGemmScheduling +from .rocm.rocm_cpp_scheduling import ROCmCPPScheduling +from .triton import TritonScheduling + + +log = logging.getLogger(__name__) + + +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 CUDACombinedScheduling(BaseScheduling): + """ + Scheduler for CUDA Kernels, which delegates calls as appropriate + to the CUDA-C++ and Triton Schedulers, which both work for CUDA devices + and use a unified-wrapper for codegen. + + If Scheduling code needs to be specialized for the case of mixed Triton / CUDA 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) + self._rocm_cpp_scheduling = ROCmCPPScheduling(scheduler) + self._cutedsl_scheduling = CuteDSLScheduling(scheduler) + self._nv_universal_gemm_scheduling = NVUniversalGemmScheduling(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 + if self._rocm_cpp_scheduling.is_rocm_cpp_template(node): + return self._rocm_cpp_scheduling + if self._cutedsl_scheduling.is_cutedsl_template(node): + return self._cutedsl_scheduling + if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template(node): + return self._nv_universal_gemm_scheduling + if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_fused_template(node): + return self._nv_universal_gemm_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 + # CuteDSL doesn't support vertical fusion currently + elif self._cutedsl_scheduling.is_cutedsl_template( + node1 + ) or self._cutedsl_scheduling.is_cutedsl_template(node2): + return False + # Only intercept when node1 is the NVGEMM template (epilogue direction). + # Prologue direction (node1=pointwise, node2=template) must fall through to + # Triton, or NVGEMM-winning MTBs silently lose Triton prologue fusion. + # For MTBs, if NVGEMM can't fuse, fall through to Triton scheduling so + # Triton choices in the same MTB can still attempt epilogue fusion. + elif self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template(node1): + if self._nv_universal_gemm_scheduling.can_fuse_vertical(node1, node2): + return True + if isinstance(node1, SchedulerNode) and isinstance( + node1.node, MultiTemplateBuffer + ): + return self._triton_scheduling.can_fuse_vertical(node1, node2) + return False + elif self._nv_universal_gemm_scheduling.is_nv_universal_gemm_fused_template( + node1 + ): + if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_fused_template( + node2 + ): + return False + return self._nv_universal_gemm_scheduling.can_fuse_vertical(node1, node2) + 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 + if self._cutedsl_scheduling.is_cutedsl_template(node): + return self._cutedsl_scheduling.can_fuse_horizontal( + node1, node2 + ) # always False at the moment + if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template( + node + ) or self._nv_universal_gemm_scheduling.is_nv_universal_gemm_fused_template( + node + ): + return self._nv_universal_gemm_scheduling.can_fuse_horizontal( + node1, node2 + ) # always False at the moment + return self._triton_scheduling.can_fuse_horizontal(node1, node2) + + def can_fuse_reduction_epilogue( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template( + node1 + ) or self._nv_universal_gemm_scheduling.is_nv_universal_gemm_fused_template( + node1 + ): + return self._nv_universal_gemm_scheduling.can_fuse_reduction_epilogue( + node1, node2 + ) + return False + + 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 + ) + elif self._rocm_cpp_scheduling.is_rocm_cpp_template(template_node): + if epilogue_nodes: + raise AssertionError( + "rocm cpp template does not support epilogue nodes" + ) + if prologue_nodes: + raise AssertionError( + "rocm cpp template does not support prologue nodes" + ) + return self._rocm_cpp_scheduling.codegen_template( + template_node, epilogue_nodes, prologue_nodes + ) + elif self._cutedsl_scheduling.is_cutedsl_template(template_node): + # TODO remove this when we add epilogue support + if epilogue_nodes: + raise AssertionError("cutedsl template does not support epilogue nodes") + if prologue_nodes: + raise AssertionError("cutedsl template does not support prologue nodes") + return self._cutedsl_scheduling.codegen_template( + template_node, epilogue_nodes, prologue_nodes + ) + elif self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template( + template_node + ): + if prologue_nodes: + raise AssertionError( + "NVIDIA Universal GEMM doesn't support prologue fusion yet" + ) + return self._nv_universal_gemm_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): + if getattr(module, "is_nvgemm", False): + return self._benchmark_nvgemm_module(module) + return self._triton_scheduling.benchmark_codegened_module(module) + + def _benchmark_nvgemm_module(self, module) -> tuple[float, str]: + from torch._dynamo.utils import preserve_rng_state + from torch._inductor.runtime.benchmarking import benchmarker + from torch._inductor.utils import get_interface_for_device + from torch._inductor.virtualized import V + + device_interface = get_interface_for_device(V.graph.device_type) + + with ( + preserve_rng_state(), + device_interface.device(V.graph.get_current_device_or_throw()), + ): + args = module.get_args() + call = module.call + + try: + call(args) + except Exception as e: + log.debug( + "Exception (%s) in compiling NVGEMM fused kernel", + e, + ) + return float("inf"), module.__file__ or "" + + device = V.graph.get_current_device_or_throw() + try: + ms = benchmarker.benchmark( + lambda: call(args), + device=device, + ) + except Exception as e: + log.debug( + "Exception (%s) while benchmarking NVGEMM fused kernel", + e, + ) + return float("inf"), module.__file__ or "" + + return ms, module.__file__ or "" + + def _is_nvgemm_node(self, node) -> bool: + """Check if a template node is currently configured for NVGEMM codegen.""" + from torch._inductor.ir import MultiTemplateBuffer, NVUniversalGemmBuffer + + template_node = node.get_template_node() + if isinstance(template_node, NVUniversalGemmBuffer): + return True + if isinstance(template_node, MultiTemplateBuffer): + return template_node._render_kind == "nvgemm" + return False + + def generate_kernel_code_from_nodes( + self, + nodes: Sequence[Any], + benchmark_kernel: bool = False, + hint_override: int | None = None, + ) -> str: + for node in nodes: + if not (hasattr(node, "is_template") and node.is_template()): + continue + if self._is_nvgemm_node(node): + return ( + self._nv_universal_gemm_scheduling.generate_kernel_code_from_nodes( + nodes, benchmark_kernel, hint_override=hint_override + ) + ) + break + 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/custom_extern_kernel_codegen.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/custom_extern_kernel_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..fd2df36d5aa3a6c7ad8f581250fe70ca43b1513e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/custom_extern_kernel_codegen.py @@ -0,0 +1,101 @@ +""" +Custom extern kernel codegen registry. + +This module provides a registry that maps operators to their custom codegen +implementations. This allows us to keep all custom implementations in one place +and easily extend support for both Python and C++ wrappers. + +To add a new custom implementation: +1. Create a codegen function with signature: + def my_codegen(node: ir.FallbackKernel, writeline: Callable[[str], None]) -> None: +2. Register it in CUSTOM_EXTERN_KERNEL_CODEGEN with the operator name as key + +Example: + CUSTOM_EXTERN_KERNEL_CODEGEN = { + "torch.ops.higher_order.print": CustomCodegen( + python=generate_print_python, + cpp=generate_print_cpp, # Optional + ), + } + +Usage: + codegen = CUSTOM_EXTERN_KERNEL_CODEGEN[op] + codegen.python(node, writeline) # Direct attribute access +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, TYPE_CHECKING + + +if TYPE_CHECKING: + from collections.abc import Callable + + from .. import ir + + # Type alias for codegen function signature (only used for type checking) + CodegenFunc = Callable[[ir.FallbackKernel, Callable[[str], None]], None] + + +@dataclass +class CustomCodegen: + """ + Container for custom codegen implementations. + + Attributes: + python: Codegen function for Python wrapper (optional) + cpp: Codegen function for C++ wrapper (optional) + """ + + python: Any = None + cpp: Any = None + + +def generate_print_python( + node: ir.FallbackKernel, + writeline: Callable[[str], None], +) -> None: + """ + Generate a builtin print call for the print HOP fallback (Python wrapper). + + This function generates Python code that calls the builtin print function + with format string interpolation. + + Args: + node: The FallbackKernel IR node representing the print HOP call. + writeline: A function that writes a line of code to the output buffer. + + Example generated code: + print('x = {}, y = {}'.format(buf0, buf1)) + print('x = {x}, y = {y}'.format(x=buf0, y=buf1)) + print('x = {}, y = {y}'.format(buf0, y=buf1)) + """ + codegen_args: list[str] = node.codegen_args() + codegen_kwargs: list[str] = node.codegen_kwargs() + + # First arg is the format string + if not codegen_args: + raise ValueError( + "generate_print_python requires a format string as the first positional argument" + ) + format_str: str = codegen_args[0] + + # Remaining args are positional arguments for .format() + positional_args = codegen_args[1:] + + args_str = ", ".join(positional_args + codegen_kwargs) + writeline( + f"print({format_str}.format({args_str}))" + if args_str + else f"print({format_str})" + ) + + +# Registry mapping operator names to their custom codegen implementations +# Usage: CUSTOM_EXTERN_KERNEL_CODEGEN[op_name].python(node, writeline) +CUSTOM_EXTERN_KERNEL_CODEGEN: dict[str, CustomCodegen] = { + "torch.ops.higher_order.print": CustomCodegen( + python=generate_print_python, + ), +} diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f12fa963fd60c00deb9f36f9515e3e794c9529ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__init__.py @@ -0,0 +1,8 @@ +# mypy: allow-untyped-defs +from .cutedsl_template import CuteDSLTemplate, CuteDSLTemplateCaller + + +__all__ = [ + "CuteDSLTemplate", + "CuteDSLTemplateCaller", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d68f26793efed7647c11a2c22b5a647fa3d487c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_cutedsl_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_cutedsl_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..065f878af047ebab03b7ba9f738a24d27a6fe4a3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_cutedsl_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_inline_asm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_inline_asm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..227130d63c6a65e669ec10b39b634a369939d0b2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/_inline_asm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/aux_scalars.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/aux_scalars.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18491a80c648c7041d6a459c4ff63104be220d33 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/aux_scalars.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac7e3fb5879c4c133fb19559b297a8e87c162376 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_op_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_op_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cebc2e296e889af955ad759aa26ab70d732fa157 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_op_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6488b6385117b0402fd8eca31b362ec91bdec720 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15ef936b4e7913f2e9ea462e8da890627c2104f5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/lane_analysis.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/lane_analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cc969ae600f6583b8ccb756c763d3ee81729306 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/__pycache__/lane_analysis.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_cutedsl_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_cutedsl_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..de27f9b09a10866ae546c89dd9945cccdb30690c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_cutedsl_utils.py @@ -0,0 +1,45 @@ +# mypy: disable-error-code=import-not-found +# pyrefly: ignore [import-error, missing-import] +import cutlass +import cutlass.cute as cute + + +@cute.jit # type: ignore[misc] +def ssa_to_indexable(ssa_value: cute.TensorSSA, dtype: str) -> cute.Numeric: + """ + Convert SSA form to indexable non-SSA form. + + Workaround for lack of gather support: SSA values cannot be used directly + as indices in tensor loads. This converts SSA to a register fragment, then + extracts a scalar for indexing. + """ + frag = ssa_to_fragment(ssa_value, dtype) + return frag[0] + + +@cute.jit # type: ignore[misc] +def ssa_to_fragment(ssa_value: cute.TensorSSA, dtype: str) -> cute.Tensor: + """Materialize an SSA vector into a register fragment. + + Casts to the fragment dtype when the SSA dtype differs (e.g. an int64 index + expression materialized into an int32 index fragment), since fragment + stores require matching element types. + """ + if cutlass.const_expr(ssa_value.dtype != dtype): + ssa_value = ssa_value.to(dtype) + frag = cute.make_rmem_tensor(ssa_value.shape, dtype) + frag.store(ssa_value) + return frag + + +@cute.jit # type: ignore[misc] +def result_to_ssa(value: cute.Numeric, dtype: str) -> cute.TensorSSA: + """ + Convert non-SSA result back to SSA form. + + After performing operations with non-SSA values (like indexed loads), + convert the result back to SSA form for further computation. + """ + frag = cute.make_rmem_tensor(1, dtype) + frag[0] = value + return frag.load() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_inline_asm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_inline_asm.py new file mode 100644 index 0000000000000000000000000000000000000000..364df3b7a85af988ebc7a9a207f27832202249a2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/_inline_asm.py @@ -0,0 +1,251 @@ +"""Lower elementwise inline PTX over CuteDSL fragments. + +Each assembly invocation consumes `pack` adjacent fragment elements. LLVM +constraints select the physical register type for every operand, so inputs are +bitcast into those registers rather than numerically converted. Multiple outputs +are returned as an LLVM struct and extracted before rebuilding the fragment. +Partial packs are zero-padded, and outputs for padded elements are discarded. + +Integer register results are narrowed to the requested element width. E8M0 codes +1 through 254 map directly to the matching Float32 exponent bits; codes 0 and 255 +map explicitly to `2^-127` and NaN. This lets fused arithmetic use exact Float32 +values while preserving E8M0 as the stored result type. +""" + +import functools +import hashlib +import math +from pathlib import Path + +import cutlass +import cutlass.cute as cute +from cutlass._mlir import ir +from cutlass._mlir.dialects import arith, llvm, vector +from cutlass.cute.tensor import _infer_broadcast_shape +from cutlass.cutlass_dsl import dsl_user_op, T + + +@functools.cache +def inline_asm_cache_key() -> str: + """Include this module's source in generated kernel cache keys.""" + return hashlib.sha256(Path(__file__).read_bytes()).hexdigest() + + +# PTX register classes, as accepted by the NVPTX inline-asm backend. +CONSTRAINT_TYPES = { + "h": T.i16, + "r": T.i32, + "l": T.i64, + "f": T.f32, + "d": T.f64, +} + + +def split_constraints(constraints: str) -> tuple[list[str], list[str]]: + """Split an LLVM constraint list into output and input register classes.""" + outputs, inputs = [], [] + for entry in constraints.split(","): + entry = entry.strip() + target = outputs if entry.startswith("=") else inputs + letter = entry.lstrip("=&") + if letter not in CONSTRAINT_TYPES: + raise NotImplementedError( + f"CuteDSL inline asm supports constraints {sorted(CONSTRAINT_TYPES)}, " + f"got {entry!r}" + ) + target.append(letter) + return outputs, inputs + + +def bitcast_to(value: ir.Value, target: ir.Type) -> ir.Value: + """Reinterpret a value's bits as an equally wide type.""" + if value.type == target: + return value + return arith.bitcast(target, value) + + +def narrow_integer(value: ir.Value, width: int) -> ir.Value: + """Truncate an integer register to `width` bits.""" + if not ir.IntegerType.isinstance(value.type): + raise TypeError(f"expected an integer inline-asm result, got {value.type}") + if ir.IntegerType(value.type).width > width: + return arith.trunci(ir.IntegerType.get_signless(width), value) + return value + + +def decode_e8m0(value: ir.Value) -> ir.Value: + """Decode one biased E8M0 bit pattern to its exact Float32 value.""" + code = arith.extui(T.i32(), narrow_integer(value, 8)) + bits = arith.shli(code, arith.constant(T.i32(), 23)) + is_zero = arith.cmpi(arith.CmpIPredicate.eq, code, arith.constant(T.i32(), 0)) + bits = arith.select(is_zero, arith.constant(T.i32(), 0x00400000), bits) + is_nan = arith.cmpi(arith.CmpIPredicate.eq, code, arith.constant(T.i32(), 255)) + bits = arith.select(is_nan, arith.constant(T.i32(), 0x7FC00000), bits) + return arith.bitcast(T.f32(), bits) + + +def convert_output(value: ir.Value, result_type) -> ir.Value: + """Convert a register result to the requested logical element type.""" + if result_type == cutlass.Float8E8M0FNU: + return decode_e8m0(value) + target = result_type.mlir_type + if value.type == target: + return value + if ir.IntegerType.isinstance(value.type): + value = narrow_integer(value, result_type.width) + return bitcast_to(value, target) + + +def fragment_element(source, index: int) -> ir.Value: + """Extract element `index` from a TensorSSA, or unwrap a scalar value.""" + if isinstance(source, cute.TensorSSA): + return vector.extract(source.ir_value(), [], [index]) + if isinstance(source, ir.Value): + return source + if isinstance(source, (int, float)): + return cutlass.Float32(source).ir_value() + return source.ir_value() + + +def zero_for_constraint(letter: str) -> ir.Value: + """Create a zero in the register type named by an inline-asm constraint.""" + target = CONSTRAINT_TYPES[letter]() + return arith.constant(target, 0.0 if letter in ("f", "d") else 0) + + +def packed_operands( + sources, + input_letters: list[str], + scalar_sources: tuple[bool, ...], + base: int, + count: int, + pack: int, +) -> list[ir.Value]: + """Gather one source-major inline-asm pack, padding a partial tail with zero.""" + operands = [] + for source_index, source in enumerate(sources): + for lane in range(pack): + letter = input_letters[source_index * pack + lane] + index = base + lane + operands.append( + bitcast_to( + fragment_element( + source, 0 if scalar_sources[source_index] else index + ) + if index < count + else zero_for_constraint(letter), + CONSTRAINT_TYPES[letter](), + ) + ) + return operands + + +@dsl_user_op +def inline_asm_elementwise_intrinsic( + *sources, + asm: str, + constraints: str, + result_type, + is_pure: bool = True, + pack: int = 1, + scalar_sources: tuple[bool, ...] = (), + loc=None, + ip=None, +): + """Apply an inline PTX block elementwise across a TensorSSA fragment. + + Args: + sources: Broadcastable TensorSSA fragments or repeated scalar values. + asm: PTX text using `$N` operand syntax, output first. + constraints: LLVM constraint list, e.g. `"=h,r"`. + result_type: Logical cutlass numeric type of the produced fragment. + E8M0 integer results are decoded to Float32 for fused consumers. + is_pure: Whether the block may be reordered and CSEd. + pack: Elements consumed per asm invocation. Missing tail elements are + zero-padded and their corresponding outputs are discarded. + scalar_sources: Sources whose physical TensorSSA value represents one + logical scalar and must be repeated for every lane. + """ + if pack < 1: + raise ValueError(f"CuteDSL inline asm requires pack >= 1, got pack={pack}") + output_letters, input_letters = split_constraints(constraints) + if len(output_letters) != pack: + raise ValueError( + f"inline asm pack={pack} requires {pack} output constraints, " + f"got {len(output_letters)} in {constraints!r}" + ) + expected_inputs = len(sources) * pack + if len(input_letters) != expected_inputs: + raise ValueError( + f"inline asm pack={pack} with {len(sources)} sources requires " + f"{expected_inputs} input constraints, got {len(input_letters)} " + f"in {constraints!r}" + ) + if not scalar_sources: + scalar_sources = (False,) * len(sources) + elif len(scalar_sources) != len(sources): + raise ValueError( + f"inline asm received {len(scalar_sources)} scalar-source flags " + f"for {len(sources)} sources" + ) + + output_types = [CONSTRAINT_TYPES[letter]() for letter in output_letters] + asm_result_type = output_types[0] + if len(output_types) > 1: + fields = ", ".join(str(output_type) for output_type in output_types) + asm_result_type = ir.Type.parse(f"!llvm.struct<({fields})>") + compute_type = ( + cutlass.Float32 if result_type == cutlass.Float8E8M0FNU else result_type + ) + fragments = [ + source + for source, is_scalar in zip(sources, scalar_sources) + if isinstance(source, cute.TensorSSA) and not is_scalar + ] + if fragments: + shape = fragments[0].shape + if any(source.shape != shape for source in fragments[1:]): + shape = _infer_broadcast_shape(*(source.shape for source in fragments)) + sources = tuple( + source.broadcast_to(shape) + if isinstance(source, cute.TensorSSA) and not is_scalar + else source + for source, is_scalar in zip(sources, scalar_sources) + ) + first_fragment = next( + source + for source, is_scalar in zip(sources, scalar_sources) + if isinstance(source, cute.TensorSSA) and not is_scalar + ) + count = math.prod(ir.VectorType(first_fragment.ir_value().type).shape) + else: + count = 1 + shape = None + + converted = [] + for base in range(0, count, pack): + produced = llvm.inline_asm( + asm_result_type, + packed_operands(sources, input_letters, scalar_sources, base, count, pack), + asm, + constraints, + has_side_effects=not is_pure, + is_align_stack=False, + ) + outputs = [produced] + if len(output_types) > 1: + outputs = [ + llvm.extractvalue(output_type, produced, [index]) + for index, output_type in enumerate(output_types) + ] + valid_outputs = min(pack, count - base) + converted.extend( + convert_output(output, result_type) for output in outputs[:valid_outputs] + ) + + if shape is None: + return compute_type(converted[0]) + vector_type = ir.VectorType.get([count], compute_type.mlir_type) + return cute.TensorSSA( + vector.from_elements(vector_type, converted), shape, compute_type + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/aux_scalars.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/aux_scalars.py new file mode 100644 index 0000000000000000000000000000000000000000..85f2defd260d9eff92490082f7c6844845e9dfdd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/aux_scalars.py @@ -0,0 +1,56 @@ +# mypy: allow-untyped-defs + +import dataclasses +from collections.abc import Callable +from typing import ClassVar + +import sympy + + +@dataclasses.dataclass(frozen=True, slots=True) +class CuteDSLAuxScalarBindings: + """Render symbolic shape captures through FA4's runtime aux_scalars tuple. + + Inductor represents captured dynamic ints/floats as SymPy expressions in the + other-buffer list, while tensor captures remain TensorBox-backed aux_tensors. + CuTe kernels receive those scalar values as ordinary kernel arguments, wrap + them for FA4, and rewrite matching symbols in generated score_mod/mask_mod + expressions to tuple lookups. + """ + + symbols: tuple[sympy.Symbol, ...] = () + tuple_name: ClassVar[str] = "aux_scalars" + + def symbol_codes(self) -> dict[sympy.Symbol, str]: + """Render symbols as tuple lookups for CuTe expressions.""" + return { + symbol: f"{self.tuple_name}[{index}]" + for index, symbol in enumerate(self.symbols) + } + + def symbol_codes_with_renames( + self, rename: Callable[[sympy.Symbol], sympy.Expr] + ) -> dict[sympy.Symbol, str]: + """Include Inductor-renamed symbols used in generated kernel signatures.""" + codes = self.symbol_codes() + for symbol, code in list(codes.items()): + renamed = rename(symbol) + if isinstance(renamed, sympy.Symbol): + codes[renamed] = code + return codes + + def tuple_expr( + self, + rename: Callable[[sympy.Symbol], sympy.Expr], + print_expr: Callable[[sympy.Expr], str], + ) -> str: + """Render runtime scalar values with FA4-compatible scalar wrapper types.""" + if not self.symbols: + return "None" + scalar_values = [] + for symbol in self.symbols: + scalar_type = "cutlass.Int64" if symbol.is_integer else "cutlass.Float64" + scalar_values.append(f"{scalar_type}({print_expr(rename(symbol))})") + if len(scalar_values) == 1: + return f"({scalar_values[0]},)" + return f"({', '.join(scalar_values)})" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..9049bb22c38aa0f3c99413470e441737b9fdb744 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_kernel.py @@ -0,0 +1,1163 @@ +# mypy: allow-untyped-defs +import contextlib +import dataclasses +import logging +import textwrap +from collections.abc import Callable +from typing import Any +from unittest.mock import patch + +import sympy + +import torch +from torch._inductor import config +from torch._inductor.codegen.common import ( + CSE, + CSEVariable, + IndentedBuffer, + Kernel, + PythonPrinter, + ValueRanges, +) +from torch._inductor.ir import ( + BaseView, + Buffer, + ComputedBuffer, + ExternKernel, + InputBuffer, + MutableBox, + ReinterpretView, +) +from torch._inductor.ops_handler import StoreMode +from torch._inductor.utils import OrderedSet +from torch._inductor.virtualized import V + +from ...utils import sympy_index_symbol +from .aux_scalars import CuteDSLAuxScalarBindings +from .cutedsl_op_overrides import CuteDSLCSEVariable, CuteDSLOpOverrides +from .lane_analysis import classify_lane_expr + + +# TODO setting the 'main' kernel w/ this suffix. We have 3 should probably just auto generate this +MAIN_SUFFIX = "main" + + +log = logging.getLogger(__name__) +kernel_code_log = torch._logging.getArtifactLogger(__name__, "kernel_code") + + +class CuteDSLPrinter(PythonPrinter): + def _print_ToFloat(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("ToFloat expects exactly one argument") + return f"cutlass.Float64({self.doprint(expr.args[0])})" + + +cutedsl_pexpr = CuteDSLPrinter().doprint + + +class CuteDSLKernelWrapper: + """Wrapper to provide .run() interface for CuteDSL kernels""" + + def __init__(self, kernel_fn: Callable[..., Any], kernel_path: str | None = None): + self.kernel_fn = kernel_fn + self.kernel_path = kernel_path + kernel_code_log.info("CuteDSL kernel path: %s", kernel_path) + + def run(self, *args, stream=None, **kwargs): + """ + Execute the CuteDSL kernel. + + Args: + *args: Arguments to pass to the kernel function + stream: CUDA stream to pass to the kernel function + **kwargs: Additional keyword arguments for the kernel + + Returns: + Result of the kernel execution + """ + return self.kernel_fn(*args, stream=stream, **kwargs) + + +@dataclasses.dataclass(frozen=True, slots=True) +class CuteDSLVectorLoadConfig: + vec_size: int + index: sympy.Symbol + dim: int + + @staticmethod + def from_fixed_inputs( + fixed_inputs: dict[str, Any], + ) -> "CuteDSLVectorLoadConfig | None": + vec_size = fixed_inputs.pop("vector_load_vec_size", None) + index = fixed_inputs.pop("vector_load_index", None) + dim = fixed_inputs.pop("vector_load_dim", None) + if vec_size is None or index is None or dim is None: + return None + return CuteDSLVectorLoadConfig( + vec_size=int(vec_size), + index=sympy_index_symbol(str(index)), + dim=int(dim), + ) + + def normalized_dim(self, ndim: int) -> int: + return self.dim + ndim if self.dim < 0 else self.dim + + +@dataclasses.dataclass(frozen=True, slots=True) +class CuteDSLIndexFragment: + """Generated index expression metadata for CuteDSL tensor loads. + + Attributes: + code: Python source expression for the index or index fragment. + is_static_int: True when code is an inline integer index, not a fragment. + is_lane_uniform: True when every vector lane has the same index. + is_contiguous: True when code is aligned and contiguous for the full + requested vector width. + """ + + code: str + is_static_int: bool + is_lane_uniform: bool = False + is_contiguous: bool = False + contiguous_width: int | None = None + + +@dataclasses.dataclass(frozen=True) +class IndexSymbolInfo: + """What lane analysis may assume about a generated index symbol. + + expr: Recovered semantic index expression, or None when the value's + semantics are unknown (loaded from a captured tensor, or produced by + ops outside the traced index algebra). Unknown semantics force a + per-lane gather: assuming lane-uniform would broadcast lane 0's load + across the vectorized group (#188878). + contiguous_ok: False when the value passed through a negative-index wrap + (idx + size for negative lanes only). Uniform lanes all wrap + identically, so lane-uniformity survives, but a contiguous window + straddling 0 jumps from size-1 back to 0 and we can't prove a window + avoids 0. + """ + + expr: sympy.Expr | None + contiguous_ok: bool = True + + +@dataclasses.dataclass +class CuteDSLSubgraphInfo: + """Minimal subgraph info for CuteDSL kernels.""" + + body: IndentedBuffer + template_mask: str | None = None + template_out: str | None = None + cse: CSE[Any, str] | None = None + + def __post_init__(self): + self.only_copy_if_non_none_fields = ("cse",) + + def to_dict(self): + return { + field.name: getattr(self, field.name) for field in dataclasses.fields(self) + } + + +class CuteDSLTemplateKernel(Kernel): + """ + Template kernel implementation for CuteDSL (CUTLASS Python DSL). + Handles code generation and argument management for CuteDSL CUDA kernels. + Provides CuteDSL-specific functionality for tensor conversion and kernel configuration. + """ + + def __init__( + self, + kernel_name: str, + input_nodes: list[Buffer], + output_node: Buffer, + subgraphs: list[Buffer] | None = None, + ) -> None: + # Call parent Kernel constructor + super().__init__() + self.kernel_name = kernel_name + self.input_nodes = input_nodes + self.output_node = output_node + self.subgraphs = subgraphs + self.subgraph_bodies: dict[str, CuteDSLSubgraphInfo] = {} + + # Template attributes + self.body: IndentedBuffer = IndentedBuffer() + self.template_mask: str | None = None + self.template_out: str | None = None + self.template_indices: list[Any] | None = None + self.render_hooks: dict[str, Any] = {} + + # TODO Additional attributes needed by template system + self.prologue_fused_inputs: OrderedSet[str] = OrderedSet() + self.prologue_fused_inputs_preserve_zero: OrderedSet[str] = OrderedSet() + self.named_input_nodes: dict[str, Buffer] = {} + + # Create named input nodes mapping + for i, input_node in enumerate(input_nodes): + node_name = getattr(input_node, "name", f"input_{i}") + self.named_input_nodes[node_name] = input_node + + self.cse = CSE(name_prefix="tmp") + + # Track all tensor buffers added during modification processing + self.collected_tensor_buffers: list[str] = [] + self.aux_scalar_bindings = CuteDSLAuxScalarBindings() + + # Captured IR nodes keyed by buffer name. Used by call_kernel to emit + # reinterpret_tensor for view captures in the python_argdefs loop. + self._capture_input_nodes: dict[str, Any] = {} + + def set_capture_input_nodes(self, nodes_by_name: dict[str, Any]) -> None: + """Set captured inputs collected while rendering the CuteDSL template.""" + self._capture_input_nodes = nodes_by_name + + def _get_capture_input_node(self, name: str) -> Any | None: + """Return the IR node for a captured input name, if known.""" + graph_captures = getattr(V.graph, "_cutedsl_capture_nodes", {}) + return self._capture_input_nodes.get(name, graph_captures.get(name)) + + @contextlib.contextmanager + def _patch_get_dtype_for_captures(self): + """Teach python_argdefs to resolve synthetic captured input names.""" + original_get_dtype = V.graph.get_dtype + + def get_dtype(name: str) -> torch.dtype: + capture = self._get_capture_input_node(name) + if capture is not None: + return capture.get_dtype() + return original_get_dtype(name) + + with patch.object(V.graph, "get_dtype", get_dtype): + yield + + def kexpr(self, expr: sympy.Expr) -> str: + """Convert sympy expression to CuteDSL string representation.""" + symbol_codes = self.aux_scalar_bindings.symbol_codes_with_renames( + self.rename_indexing + ) + if symbol_codes: + expr = expr.xreplace( + {symbol: sympy.Symbol(code) for symbol, code in symbol_codes.items()} + ) + return cutedsl_pexpr(expr) + + def create_cse_var(self, *args, **kwargs): + return CuteDSLCSEVariable(*args, **kwargs) + + def gen_imports(self) -> str: + """Generate common imports for CuteDSL templates.""" + imports = IndentedBuffer() + imports.splice( + """ + import torch + import cutlass + import cutlass.cute as cute + from cutlass.cute.runtime import from_dlpack + import cuda.bindings.driver as cuda + from cutlass._mlir.dialects import math as mlir_math + import operator + from torch._inductor.codegen.cutedsl._cutedsl_utils import result_to_ssa, ssa_to_fragment, ssa_to_indexable + """ + ) + return imports.getvalue() + + def gen_defines(self, **kwargs) -> str: + """Generate CuteDSL parameter definitions from kwargs, similar to Triton's gen_defines.""" + params = IndentedBuffer() + for name, val in kwargs.items(): + params.writeline(f"{name}: cutlass.Constexpr = {val}") + return params.getvalue() + + def render(self, template, **kwargs): + from torch._inductor.select_algorithm import PartialRender + + """Render the kernel using the template, returning PartialRender object with hooks.""" + self._template_kwargs = dict(kwargs) + self.aux_scalar_bindings = CuteDSLAuxScalarBindings( + tuple(kwargs.get("AUX_SCALAR_SYMBOLS", ())) + ) + + # Available {{}} hooks for jinja rendering + template_env = { + "def_kernel": self.def_kernel, + "gen_defines": lambda: self.gen_defines(**kwargs), + "get_output": self.get_output, + "get_tensor_buffers": self.get_tensor_buffers, + "add_tensor_inputs": self.add_tensor_inputs, + "define_aux_scalars": self.define_aux_scalars, + "unpack_buffers": self.unpack_buffers, + "modification": self.modification, + "set_cute_hash": self.set_cute_hash, + } + + # Render the template with the environment and provided kwargs + rendered_code = template.render( + kernel_name=self.kernel_name, + input_nodes=self.input_nodes, + output_node=self.output_node, + **template_env, + **kwargs, + ) + + # Always prepend the common imports + imports = self.gen_imports() + full_code = imports + rendered_code + + return PartialRender(full_code, self.render_hooks) + + @contextlib.contextmanager + def set_subgraph_body(self, body_name: str): + """Set the active subgraph body for template processing.""" + if not all( + hasattr(self, field.name) + for field in dataclasses.fields(CuteDSLSubgraphInfo) + ): + raise AssertionError( + "expected all CuteDSLSubgraphInfo fields to be set on self" + ) + old_state = { + key.name: getattr(self, key.name) + for key in dataclasses.fields(CuteDSLSubgraphInfo) + } + + if body_name not in self.subgraph_bodies: + self.subgraph_bodies[body_name] = CuteDSLSubgraphInfo( + body=IndentedBuffer(), + template_mask=None, + template_out=None, + cse=None, + ) + + subgraph = self.subgraph_bodies[body_name] + for key, value in subgraph.to_dict().items(): + if value is None and key in getattr( + subgraph, "only_copy_if_non_none_fields", () + ): + continue + setattr(self, key, value) + + try: + yield + finally: + # Save current state back to subgraph + self.subgraph_bodies[body_name] = CuteDSLSubgraphInfo( + **{ + key.name: getattr(self, key.name) + for key in dataclasses.fields(CuteDSLSubgraphInfo) + } + ) + # Restore old state + 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): + """Create a new subgraph body for template processing.""" + if body_name in self.subgraph_bodies: + raise AssertionError(f"Subgraph body '{body_name}' already exists") + new_cse = self.cse.clone() if clear_cse else None + self.subgraph_bodies[body_name] = CuteDSLSubgraphInfo( + body=IndentedBuffer(), + template_mask=None, + template_out=None, + cse=new_cse, + ) + with self.set_subgraph_body(body_name): + yield + + def _get_reinterpret_view(self, node) -> ReinterpretView | None: + """Extract or convert to ReinterpretView from a node, handling all views.""" + while isinstance(node, MutableBox): + node = node.data + if isinstance(node, BaseView): + return ExternKernel.convert_to_reinterpret_view(node) + return None + + def def_kernel(self, *argnames): + """Define kernel function signature for CuteDSL templates. + + When inputs are ReinterpretViews of the same underlying buffer (e.g., Q/K/V + from fused QKV projection), we generate separate arguments for each input + even though they share the same underlying buffer. + """ + renames = IndentedBuffer(initial_indent=1) + + # Track template input args - each input gets its own arg even if buffers are shared + self._template_input_args: list[tuple[str, Buffer]] = [] + self._seen_input_args: OrderedSet[str] = OrderedSet() + + for i, input_node in enumerate(self.input_nodes): + buf_name = input_node.get_name() + # Register with args system (may deduplicate, but we track separately) + self.args.input(buf_name) + + if i < len(argnames): + template_name = argnames[i] + arg_name = f"arg_{template_name}" + self.args.input_buffers[buf_name] = arg_name + renames.writeline(f"{template_name} = {arg_name}") + self._template_input_args.append((arg_name, input_node)) + self._seen_input_args.add(arg_name) + + if self.output_node: + self.args.output(self.output_node.get_name()) + + def hook(): + # Generate signature with template input args plus additional args (output, sizevars) + code = IndentedBuffer() + code.writeline(f"# Kernel function signature: {self.kernel_name}") + + # Start with template input args + params = [arg_name for arg_name, _ in self._template_input_args] + + # Get additional args from python_argdefs (output, sizevars, etc.) + with self._patch_get_dtype_for_captures(): + arg_defs, _, _, _ = self.args.python_argdefs() + 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") + code.writeline( + f"def {self.kernel_name}_{MAIN_SUFFIX}({', '.join(params)}):" + ) + with code.indent(): + code.splice(renames.getvalue()) + return code.getvalue() + + if "" in self.render_hooks: + raise AssertionError(" hook already registered") + # Placeholder-based rendering: hook will be called when template encounters "" + self.render_hooks[""] = hook + return "" + + def get_output(self): + """Get the actual argument name for the output buffer.""" + if not self.output_node: + raise AssertionError("Output node must exist to get output buffer name") + buf_name = self.output_node.get_name() + output = self.args.output_buffers.get(buf_name, None) + if output is None: + raise ValueError(f"Output buffer '{buf_name}' not found in args") + return output + + def set_cute_hash(self, func_name: str, suffix: str = ""): + """Generate code to set __cute_hash__ on a codegen function. + + This allows hash_callable in flash_attn to skip expensive runtime hashing + for Inductor-generated functions. The hash is based on the kernel name + which already contains a unique hash suffix. + """ + hash_value = f"{self.kernel_name}_{suffix}" if suffix else self.kernel_name + return f'{func_name}.__cute_hash__ = "{hash_value}"' + + def get_tensor_buffers(self): + """Get list of tensor buffer names that were collected during modifications.""" + return self.collected_tensor_buffers + + def add_tensor_inputs(self, buffers): + """Register extra tensor buffers and return their rendered input names.""" + buffer_names = [] + for buffer in buffers: + if isinstance(buffer, sympy.Expr): + continue + remapped_name = self.args.input(buffer.get_name()) + if remapped_name not in self.collected_tensor_buffers: + self.collected_tensor_buffers.append(remapped_name) + buffer_names.append(remapped_name) + return buffer_names + + def define_aux_scalars(self, symbols): + """Return the runtime scalar tuple for captured symbolic scalars.""" + if tuple(symbols) != self.aux_scalar_bindings.symbols: + raise AssertionError( + f"Expected aux scalar symbols {self.aux_scalar_bindings.symbols}, " + f"got {tuple(symbols)}" + ) + return self.aux_scalar_bindings.tuple_expr(self.rename_indexing, cutedsl_pexpr) + + def unpack_buffers(self, buffer_list_name: str, *, indent_width: int = 4): + """Generate buffer unpacking code via render hook.""" + + def hook(): + tensor_buffers = self.get_tensor_buffers() + if not tensor_buffers: + return "" + + # Generate unpacking assignments: in_ptr4 = buffers[0], etc. + unpacking_lines = [] + for i, buffer_name in enumerate(tensor_buffers): + # pyrefly: ignore [bad-argument-type] + unpacking_lines.append(f"{buffer_name} = {buffer_list_name}[{i}]") + + indent = " " * indent_width + return "\n" + indent + ("\n" + indent).join(unpacking_lines) + + # Register the hook and return placeholder + placeholder = "" + # TODO: I think double invoking is fine for this specific hook + # assert placeholder not in self.render_hooks + self.render_hooks[placeholder] = hook + return placeholder + + def call_kernel(self, name: str, node=None): + """Call the kernel function. Simplified version of TritonTemplateKernel.call_kernel. + + For inputs that are ReinterpretViews (e.g., Q/K/V slices from fused QKV), + we generate reinterpret_tensor() calls to properly handle the views. + """ + wrapper = V.graph.wrapper_code + + # Build call args matching the signature generated in `def_kernel` + call_args = [] + arg_types = [] + + for _, input_node in self._template_input_args: + reinterpret_view = self._get_reinterpret_view(input_node) + if reinterpret_view is not None: + call_args.append(reinterpret_view.codegen_reference()) + else: + call_args.append(input_node.get_name()) + arg_types.append(V.graph.get_dtype(input_node.get_name())) + + # Add additional args from python_argdefs (output, sizevars, ..) + with self._patch_get_dtype_for_captures(): + orig_arg_defs, orig_call_args, _, orig_arg_types = ( + self.args.python_argdefs() + ) + for arg_def, call_arg, arg_type in zip( + orig_arg_defs, orig_call_args, orig_arg_types + ): + if arg_def.full_name() in self._seen_input_args: + continue + capture = self._get_capture_input_node(call_arg) + if isinstance(capture, ReinterpretView): + # Pass the original view expression so stride/offset metadata is + # preserved at the kernel call site. + call_args.append(capture.codegen_reference()) + else: + call_args.append(call_arg) + arg_types.append(arg_type) + + # TODO this karg really should not be called `triton` + wrapper.generate_kernel_call(name, call_args, triton=True, arg_types=arg_types) + + def _get_subgraph(self, subgraph_number: int): + """Get subgraph by number for modification processing.""" + 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 modification( + self, + subgraph_number: int, + output_name: str | None, + mask: str | None = None, + **fixed_inputs, + ) -> str: + """Generate CuteDSL code for a subgraph modification.""" + # Find unique name to avoid collisions between multiple modifications of same subgraph + num = 0 + while f"mod_{subgraph_number}_{num}" in self.subgraph_bodies: + num += 1 + + with self.create_subgraph_body(f"mod_{subgraph_number}_{num}", clear_cse=True): + subgraph = self._get_subgraph(subgraph_number) + modification_handler = ModificationWrapperCuteDSL( + self, subgraph_number, fixed_inputs, mask + ) + with V.set_kernel_handler(self), V.set_ops_handler(modification_handler): + if not isinstance(subgraph, (ComputedBuffer, list)): + raise AssertionError( + f"Expected ComputedBuffer or List[ComputedBuffer], got {type(subgraph)}" + ) + + if isinstance(subgraph, list): + raise NotImplementedError( + "Scatter graphs are not supported for CuteDSL" + ) + + if isinstance(subgraph.data, InputBuffer): + # grad_score_mod can be InputBuffers + out = subgraph.data.make_loader()(()) + else: + # Inline a pointwise lowering into the template + out = subgraph.data.inner_fn(()) + + if output_name is not None: + if out is None: + raise AssertionError( + f"Expected computation result for named output {output_name}" + ) + self.body.writeline(f"{output_name} = {out.value}") + else: + # Side-effect only: no output assignment (currently only for scatter operations) + raise NotImplementedError( + "Side-effect only modifications not yet supported for CuteDSL" + ) + + # Add Buffers that were added during modification + self.collected_tensor_buffers.extend(modification_handler.tensor_buffers) + + return self.body.getvalue() + + +class ModificationWrapperCuteDSL(V.WrapperHandler): # type: ignore[name-defined] + """ + Wrapper handler that enables CuteDSL code generation during subgraph modifications. + + This class sits between the PyTorch IR and CuteDSL code generation, providing: + 1. Operation substitution: converts PyTorch ops to CuteDSL equivalents via CuteDSLOpOverrides + 2. Placeholder handling: resolves fixed_inputs during template processing + 3. Limited operation support: currently restricted to pointwise operations + + """ + + def __init__( + self, + kernel, + subgraph_number: int, + fixed_inputs: dict[str, Any], + mask: str | None, + ): + cutedsl_ops = CuteDSLOpOverrides() + super().__init__(cutedsl_ops) + self.name = f"CuteDSLPlaceholderSubstitution_{subgraph_number}" + self.kernel = kernel + self.fixed_inputs = dict(fixed_inputs) + self.vector_load_config = CuteDSLVectorLoadConfig.from_fixed_inputs( + self.fixed_inputs + ) + self.mask = mask + # Track tensor buffers that get added during modification processing + self.tensor_buffers: list[str] = [] + # Maps generated CSE names to their semantic provenance so vector-load + # analysis can reason about the source indexing semantics. + self._index_symbol_info: dict[sympy.Symbol, IndexSymbolInfo] = {} + # Captured modifications are read-only, so repeated loads from the same + # semantic location can share the generated index and value fragments. + self._captured_load_cache: dict[tuple[str, sympy.Expr], CuteDSLCSEVariable] = {} + + def _get_input_dtype(self, name: str) -> torch.dtype: + """Get the dtype for an input from the kernel's named_input_nodes.""" + if name in self.kernel.named_input_nodes: + return self.kernel.named_input_nodes[name].dtype + # TODO: Fallback for common dimension names - should be replaced with proper dtype tracking + return torch.float32 if name not in ("b", "h", "m", "n") else torch.int32 + + def load(self, name: str, index: sympy.Expr): + """Handle loading from tensor or fixed(template args) input for CuteDSL.""" + from torch._inductor.kernel.flex.flex_flash_attention import HierarchicalIndex + + if name not in self.fixed_inputs: + cache_key = (name, index) + cached = self._captured_load_cache.get(cache_key) + if cached is not None: + return self.kernel.cse.generate(self.kernel.body, cached) + + var = self._add_kernel_input(name) + buffer = self.kernel._get_capture_input_node(name) + if buffer is None: + buffer = V.graph.get_buffer(name) + var_dtype = buffer.dtype + + cute_dtype = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get( + var_dtype, "cutlass.Float32" + ) + dim_indices = ( + index.args if isinstance(index, HierarchicalIndex) else (index,) + ) + dim_sizes = buffer.get_size() + if len(dim_sizes) == 0: + dim_indices = () + # Per-dimension indices into captured buffers are bounded by dim + # sizes (not flattened offsets), so Int32 is safe whatever index + # dtype the consuming kernel passes in; wider index expressions are + # narrowed at fragment materialization. + idx_vars = [ + self._emit_index_fragment( + dim_index, dim_size, "cutlass.Int32", torch.int32 + ) + for dim_index, dim_size in zip(dim_indices, dim_sizes, strict=True) + ] + + val_frag = self._emit_tensor_load_fragment( + var, idx_vars, cute_dtype, var_dtype, buffer + ) + final_expr = f"{val_frag}.load()" + + if ( + var_dtype in (torch.float16, torch.bfloat16) + and config.triton.codegen_upcast_to_fp32 + ): + final_expr = f"({final_expr}).to(cutlass.Float32)" + var_dtype = torch.float32 + + out = self.kernel.cse.generate( + self.kernel.body, + final_expr, + dtype=var_dtype, + bounds=ValueRanges.unknown(), + shape=(1,), + ) + self._captured_load_cache[cache_key] = out + return out + + value = self.fixed_inputs[name] + dtype = self._get_input_dtype(name) + + result = self.kernel.cse.generate( + self.kernel.body, value, bounds=ValueRanges.unknown(), dtype=dtype + ) + if ( + isinstance(result, CuteDSLCSEVariable) + and isinstance(value, str) + and dtype in (torch.int32, torch.int64) + ): + result.index_expr = sympy_index_symbol(value) + return result + + def _emit_tensor_load_fragment( + self, + var: str, + idx_vars: list[CuteDSLIndexFragment], + cute_dtype: str, + var_dtype: torch.dtype, + buffer: Any, + ) -> str: + """ + Emit a register fragment load from a captured tensor. + + Static integer indices can be emitted directly as scalar tensor indices. + Dynamic indices are SSA vectors, which must first be materialized into + register fragments so each lane can be used for scalar gather loads. If + all indices are static, emit a single-element fragment; otherwise size + the value fragment to match the dynamic index lanes. + """ + dynamic_index_fragment = next( + (idx for idx in idx_vars if not idx.is_static_int), None + ) + # Dynamic index fragments all carry the same vector width, so one + # representative fragment is enough to size the loaded value fragment. + val_frag = self.kernel.cse.newvar(dtype=var_dtype) + if len(buffer.get_size()) == 0: + self.kernel.body.writeline( + f"{val_frag} = cute.make_rmem_tensor(1, {cute_dtype})" + ) + self.kernel.body.writeline(f"{val_frag}[0] = ({var}[()])") + return str(val_frag) + if dynamic_index_fragment is None: + self.kernel.body.writeline( + f"{val_frag} = cute.make_rmem_tensor(1, {cute_dtype})" + ) + self.kernel.body.writeline( + f"{val_frag}[0] = ({var}[{', '.join(idx.code for idx in idx_vars)}])" + ) + return str(val_frag) + + self.kernel.body.writeline( + f"{val_frag} = cute.make_rmem_tensor(" + f"cute.size({dynamic_index_fragment.code}.shape), {cute_dtype})" + ) + if self.vector_load_config is None: + vector_dim = len(idx_vars) - 1 + else: + vector_dim = self.vector_load_config.normalized_dim(len(idx_vars)) + if self._can_emit_contiguous_dim_load(idx_vars, buffer, var_dtype, vector_dim): + self._emit_contiguous_dim_load( + var, idx_vars, val_frag, cute_dtype, var_dtype, vector_dim + ) + elif self._can_emit_uniform_load(idx_vars): + self._emit_uniform_load(var, idx_vars, val_frag) + else: + self._emit_per_lane_gather_load(var, idx_vars, val_frag) + return str(val_frag) + + def _can_emit_contiguous_dim_load( + self, + idx_vars: list[CuteDSLIndexFragment], + buffer: Any, + var_dtype: torch.dtype, + vector_dim: int, + ) -> bool: + """Return true when vector lanes form a safe contiguous tensor tile. + + This is stricter than lane-contiguity analysis: CuTe autovec also needs + a real byte-addressable copy type, uniform non-vector dimensions, unit + vector stride, and a statically aligned full-width tile. + """ + if var_dtype is torch.bool: + return False + if not idx_vars or not idx_vars[vector_dim].is_contiguous: + return False + if any( + not (idx.is_static_int or idx.is_lane_uniform) + for dim, idx in enumerate(idx_vars) + if dim != vector_dim + ): + return False + sizes = buffer.get_size() + strides = buffer.get_stride() + vector_size = ( + 1 if self.vector_load_config is None else self.vector_load_config.vec_size + ) + contiguous_width = idx_vars[vector_dim].contiguous_width + has_vector_width = vector_size > 1 + has_unit_stride = V.graph.sizevars.statically_known_equals( + strides[vector_dim], 1 + ) + has_full_width_contiguity = ( + contiguous_width is not None and contiguous_width >= vector_size + ) + is_size_aligned = V.graph.sizevars.statically_known_multiple_of( + sizes[vector_dim], vector_size + ) + is_offset_aligned = V.graph.sizevars.statically_known_multiple_of( + buffer.get_layout().offset, vector_size + ) + are_non_vector_strides_aligned = all( + V.graph.sizevars.statically_known_multiple_of(stride, vector_size) + for dim, stride in enumerate(strides) + if dim != vector_dim + ) + return ( + has_vector_width + and has_unit_stride + and has_full_width_contiguity + and is_size_aligned + and is_offset_aligned + and are_non_vector_strides_aligned + ) + + def _emit_contiguous_dim_load( + self, + var: str, + idx_vars: list[CuteDSLIndexFragment], + val_frag: str, + cute_dtype: str, + var_dtype: torch.dtype, + vector_dim: int, + ) -> None: + """Emit an autovec load for lanes contiguous in one tensor dimension.""" + scalar_indices = [ + idx.code if idx.is_static_int else f"{idx.code}[0]" for idx in idx_vars + ] + vec_size = f"cute.size({val_frag}.shape)" + aligned_idx = self.kernel.cse.newvar(dtype=torch.int32) + source_tile = self.kernel.cse.newvar(dtype=var_dtype) + aligned_ptr = self.kernel.cse.newvar(dtype=var_dtype) + aligned_source = self.kernel.cse.newvar(dtype=var_dtype) + + vector_idx = idx_vars[vector_dim].code + tiler_items = ["1"] * len(idx_vars) + tiler_items[vector_dim] = vec_size + coord_items = scalar_indices + coord_items[vector_dim] = f"{aligned_idx} // {vec_size}" + source_view_items = ["0"] * len(idx_vars) + source_view_items[vector_dim] = "None" + source_view = ( + str(aligned_source) + if len(idx_vars) == 1 + else f"{aligned_source}[{', '.join(source_view_items)}]" + ) + tiler = ( + f"({tiler_items[0]},)" + if len(tiler_items) == 1 + else f"({', '.join(tiler_items)})" + ) + coord = ( + f"({coord_items[0]},)" + if len(coord_items) == 1 + else f"({', '.join(coord_items)})" + ) + self.kernel.body.splice( + f""" + {aligned_idx} = cute.assume({vector_idx}[0], divby={vec_size}) + {source_tile} = cute.local_tile({var}, {tiler}, {coord}) + {aligned_ptr} = cute.make_ptr({cute_dtype}, {source_tile}.iterator.toint(), {source_tile}.iterator.memspace, assumed_align=min(16, {vec_size} * {var_dtype.itemsize})) + {aligned_source} = cute.make_tensor({aligned_ptr}, {source_tile}.layout) + cute.autovec_copy({source_view}, {val_frag}) + """ + ) + + @staticmethod + def _can_emit_uniform_load(idx_vars: list[CuteDSLIndexFragment]) -> bool: + """Return true when every vector lane reads the same tensor element.""" + return all(idx.is_static_int or idx.is_lane_uniform for idx in idx_vars) + + def _emit_uniform_load( + self, var: str, idx_vars: list[CuteDSLIndexFragment], val_frag: str + ) -> None: + """Emit one scalar load and broadcast it across the value fragment.""" + scalar_value = self.kernel.cse.newvar(dtype=None) + scalar_indices = [ + idx.code if idx.is_static_int else f"{idx.code}[0]" for idx in idx_vars + ] + self.kernel.body.writeline( + f"{scalar_value} = ({var}[{', '.join(scalar_indices)}])" + ) + self.kernel.body.writeline( + f"for load_idx in cutlass.range(cute.size({val_frag}.shape), unroll_full=True):" + ) + with self.kernel.body.indent(): + self.kernel.body.writeline(f"{val_frag}[load_idx] = {scalar_value}") + + def _emit_per_lane_gather_load( + self, var: str, idx_vars: list[CuteDSLIndexFragment], val_frag: str + ) -> None: + """Emit scalar per-lane loads for non-contiguous gather indices. + + Lane-uniform index fragments hold a single element, so they are indexed + at [0] rather than [load_idx] (which would read out of bounds and + silently corrupt the gathered rows). + """ + self.kernel.body.writeline( + f"for load_idx in cutlass.range(cute.size({val_frag}.shape), unroll_full=True):" + ) + with self.kernel.body.indent(): + load_indices = [ + idx.code + if idx.is_static_int + else f"{idx.code}[0]" + if idx.is_lane_uniform + else f"{idx.code}[load_idx]" + for idx in idx_vars + ] + self.kernel.body.writeline( + f"{val_frag}[load_idx] = ({var}[{', '.join(load_indices)}])" + ) + + def _emit_index_fragment( + self, + expr: sympy.Expr, + dim_size: sympy.Expr, + cute_dtype: str, + torch_dtype: torch.dtype, + ) -> CuteDSLIndexFragment: + """Materialize an index and preserve enough metadata for load selection.""" + static_expr = self._static_integer_expr(expr) + if static_expr is not None: + return CuteDSLIndexFragment( + self.kernel.kexpr(self._wrap_static_index(static_expr, dim_size)), + is_static_int=True, + ) + + expr = self.kernel.rename_indexing(expr) + is_lane_uniform, is_contiguous, contiguous_width = self._analyze_index_fragment( + expr + ) + result = self.kernel.cse.newvar(dtype=torch_dtype) + self.kernel.body.writeline( + f"{result} = ssa_to_fragment({self.kernel.kexpr(expr)}, {cute_dtype})" + ) + return CuteDSLIndexFragment( + str(result), + is_static_int=False, + is_lane_uniform=is_lane_uniform, + is_contiguous=is_contiguous, + contiguous_width=contiguous_width, + ) + + def _analyze_index_fragment( + self, expr: sympy.Expr + ) -> tuple[bool, bool, int | None]: + if self.vector_load_config is None: + return False, False, None + if self.vector_load_config.vec_size <= 1: + return True, False, None + + contiguous_ok = True + for sym in expr.free_symbols: + info = self._index_symbol_info.get(sym) + if info is not None: + if info.expr is None: + # If we dont know the semantics of the index, we cannot determine lane behavior. + # So we default to safe/pessimistic behavior: per-lane gather, no uniformity, no contiguity. + return False, False, None + contiguous_ok &= info.contiguous_ok + + semantic_expr = self._semantic_index_expr(expr) + if self._has_unresolved_index_symbols(semantic_expr): + # ditto -> we dont know so choose safe/pessimistic behavior + return False, False, None + + lane_info = classify_lane_expr( + semantic_expr, + self.vector_load_config.index, + max_width=self.vector_load_config.vec_size, + uniform_symbols=self._lane_uniform_symbols(), + ) + return ( + lane_info.is_uniform, + lane_info.is_contiguous and contiguous_ok, + lane_info.contiguous_width if contiguous_ok else None, + ) + + def _has_unresolved_index_symbols(self, semantic_expr: sympy.Expr) -> bool: + """Return whether the expression references opaque computed indices. + + Lane analysis treats unknown non-lane symbols as lane-uniform scalars, + which is correct for sizes and fixed inputs but silently broadcasts + lane 0's gather when the symbol is actually per-lane runtime data + (#188878). Recovered semantics substitute away generated CSE names, so + a surviving symbol in the reserved ``tmpN`` namespace means recovery + failed and the load must stay a per-lane gather. + """ + prefix = self.kernel.cse.name_prefix + lane_var = self.vector_load_config.index if self.vector_load_config else None + return any( + sym is not lane_var + and sym.name.startswith(prefix) + and sym.name[len(prefix) :].isdigit() + for sym in semantic_expr.free_symbols + ) + + @staticmethod + def _static_integer_expr(expr: object) -> int | sympy.Integer | None: + if isinstance(expr, int | sympy.Integer): + return expr + if isinstance(expr, sympy.Symbol) and expr.name.lstrip("-").isdigit(): + return int(expr.name) + if isinstance(expr, sympy.Expr): + expr = V.graph.sizevars.simplify(expr) + if expr.is_Integer: + return expr + return None + + @staticmethod + def _wrap_static_index( + index: int | sympy.Integer, dim_size: sympy.Expr + ) -> int | sympy.Expr: + if int(index) < 0: + return V.graph.sizevars.simplify(sympy.Integer(index) + dim_size) + return index + + def _semantic_index_expr(self, expr: sympy.Expr) -> sympy.Expr: + """Recover the original index meaning from generated CSE names.""" + replacements: dict[sympy.Symbol, sympy.Expr] = { + symbol: info.expr + for symbol, info in self._index_symbol_info.items() + if info.expr is not None + } + for var in self.kernel.cse._cache.values(): + if isinstance(var, CuteDSLCSEVariable) and var.index_expr is not None: + replacements[sympy_index_symbol(var.name)] = var.index_expr + return V.graph.sizevars.simplify(expr.xreplace(replacements)) + + def _lane_uniform_symbols(self) -> OrderedSet[sympy.Symbol]: + """Return generated CSE source symbols that are uniform across lanes.""" + vector_index_name = ( + None + if self.vector_load_config is None + else self.vector_load_config.index.name + ) + return OrderedSet( + [ + sympy_index_symbol(source_expr) + for source_expr in self.kernel.cse._cache + if isinstance(source_expr, str) and source_expr != vector_index_name + ] + ) + + def indirect_indexing(self, index_var: str, size, check, wrap_neg=True): + """Convert index variable to symbolic form.""" + if isinstance(index_var, int | sympy.Integer): + if wrap_neg and index_var < 0: + return V.graph.sizevars.simplify(sympy.Integer(index_var) + size) + return sympy.Integer(index_var) + if ( + wrap_neg + and isinstance(index_var, CuteDSLCSEVariable) + and index_var.index_expr is not None + and not V.graph.sizevars.statically_known_geq(index_var.index_expr, 0) + ): + wrapped = self.kernel.cse.newvar(dtype=index_var.dtype) + # Dynamic sizes render as Int64 aux_scalars; cast to the index dtype so + # both cute.where branches agree (per-dim size, so narrowing is safe). + index_cute_dtype = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get( + index_var.dtype, "cutlass.Int32" + ) + size_expr = f"{index_cute_dtype}({self.kernel.kexpr(size)})" + self.kernel.body.writeline( + f"{wrapped} = cute.where(" + f"{index_var} < 0, {index_var} + {size_expr}, {index_var})" + ) + symbol = sympy_index_symbol(str(wrapped)) + # Preserve the pre-wrap semantics so lane analysis sees the true + # lane structure; the wrap remaps negative lanes individually, so + # contiguity of the pre-wrap expression does not survive it. + self._index_symbol_info[symbol] = IndexSymbolInfo( + index_var.index_expr, contiguous_ok=False + ) + return symbol + source_name = None + for expr, var in self.kernel.cse._cache.items(): + if var is index_var: + source_name = expr if isinstance(expr, str) else None + break + symbol = sympy_index_symbol(source_name or str(index_var)) + index_expr = ( + index_var.index_expr if isinstance(index_var, CuteDSLCSEVariable) else None + ) + self._index_symbol_info[symbol] = IndexSymbolInfo(index_expr) + return symbol + + # pyrefly: ignore [bad-override] + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> str: + raise NotImplementedError( + "Store operations not supported - CuteDSL limited to read-only operations" + ) + + def _add_kernel_input(self, name: str): + """Add name as input to kernel and return input ref.""" + # Get the remapped name that will be used in the kernel + remapped_name = self.kernel.args.input(name) + # Track the remapped name for later collection + if remapped_name not in self.tensor_buffers: + self.tensor_buffers.append(remapped_name) + return remapped_name + + def _process_indexing(self, index): + """Process and rename indexing, adding symbols as kernel inputs.""" + renamed = self.kernel.rename_indexing(index) + return self.kernel.kexpr(renamed) + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + try: + return getattr(self._inner, name)(*args, **kwargs) + except NotImplementedError as e: + bar = "=" * 80 + msg = textwrap.dedent(f""" + {bar} + UNSUPPORTED CUTEDSL OPERATION: '{name}' + {bar} + This operation is not yet implemented in Inductor. + + Please open an issue at: https://github.com/pytorch/pytorch/issues + with the following information: + + Operation: {name} + Args: {args!r} + Kwargs: {kwargs!r} + + Title your issue: [CuteDSL] Missing operation: {name} + {bar} + """).strip() + raise NotImplementedError(msg) from e diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..156855373852503d2d64754ef8a641a9a1384c77 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py @@ -0,0 +1,939 @@ +# mypy: allow-untyped-defs +""" +CuteDSL-specific operation overrides for pointwise operations. + +This module provides CuteDSL implementations of common operations used in +template kernels, particularly for flex attention modifications. +""" + +import dataclasses +import math +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar + +import sympy + +import torch +from torch._inductor.codegen.common import CSEVariable, OpOverrides +from torch._inductor.ops_handler import ReductionType +from torch._inductor.utils import get_bounds_index_expr +from torch._inductor.virtualized import OpsValue, V +from torch.utils._sympy.functions import Max, Min +from torch.utils._sympy.value_ranges import ValueRanges + + +class CuteDSLCSEVariable(CSEVariable): + def __init__( + self, + name: str, + bounds: ValueRanges[sympy.Expr], + dtype: torch.dtype | None = None, + shape=None, + *, + is_scalar_expr: bool = False, + index_expr: sympy.Expr | None = None, + ): + super().__init__(name, bounds, dtype, shape) + self.is_scalar_expr = is_scalar_expr + self.index_expr = index_expr + + +CuteDSLArg = CSEVariable | str | bool | float | int + + +_CUTEDSL_FAST_MATH: ContextVar[bool] = ContextVar("cutedsl_fast_math", default=False) + + +@contextmanager +def use_cutedsl_fast_math(enabled: bool) -> Iterator[None]: + """Scope whether CuTeDSL math operations request fast-math lowering.""" + token = _CUTEDSL_FAST_MATH.set(enabled) + try: + yield + finally: + _CUTEDSL_FAST_MATH.reset(token) + + +@dataclasses.dataclass(frozen=True) +class TensorSSAReduction: + """Describe the CuTeDSL lowering for one TensorSSA value reduction.""" + + cute_op: str + init_val: str + combine_expr: str + + +TENSORSSA_REDUCTIONS: dict[str, TensorSSAReduction] = { + "sum": TensorSSAReduction("cute.ReductionOp.ADD", "0.0", "lhs + rhs"), + "prod": TensorSSAReduction("cute.ReductionOp.MUL", "1.0", "lhs * rhs"), + "max": TensorSSAReduction( + "cute.ReductionOp.MAX", 'float("-inf")', "cutlass.max(lhs, rhs)" + ), + "min": TensorSSAReduction( + "cute.ReductionOp.MIN", 'float("inf")', "cutlass.min(lhs, rhs)" + ), +} + + +def tensorssa_reduction(reduction_type: ReductionType) -> TensorSSAReduction: + """Return the TensorSSA descriptor for reductions representable by CuTe.""" + reduction = TENSORSSA_REDUCTIONS.get(reduction_type) + if reduction is None: + raise NotImplementedError( + f"{reduction_type} does not map to a CuTe TensorSSA reduction" + ) + return reduction + + +def upcast_compute_type(dtype: torch.dtype) -> torch.dtype: + """Maybe upcast [b]float16 to float32""" + if dtype in (torch.float16, torch.bfloat16): + return torch.float32 + return dtype + + +class CuteDSLOpOverrides(OpOverrides): + """ + CuteDSL-specific operation overrides that generate code using CuteDSL syntax. + + CuteDSL TensorSSA objects have built-in operator overloads (__add__, __mul__, etc.) + and math functions (cute.math.exp, cute.math.sqrt, etc.) + """ + + TORCH_TO_CUTE_DTYPE = { + torch.float16: "cutlass.Float16", + torch.bfloat16: "cutlass.BFloat16", + torch.float32: "cutlass.Float32", + torch.float64: "cutlass.Float64", + torch.int8: "cutlass.Int8", + torch.int16: "cutlass.Int16", + torch.int32: "cutlass.Int32", + torch.int64: "cutlass.Int64", + torch.uint8: "cutlass.Uint8", + torch.uint16: "cutlass.Uint16", + torch.bool: "cutlass.Boolean", + torch.float8_e4m3fn: "cutlass.Float8E4M3FN", + torch.float8_e8m0fnu: "cutlass.Float8E8M0FNU", + torch.float8_e5m2: "cutlass.Float8E5M2", + } + + # Math constants + LOG2_E = 1.4426950408889634 # 1/ln(2) for converting natural exp to base-2 exp + + @staticmethod + def _get_cse_var(arg: CuteDSLArg) -> CSEVariable | None: + """Extract CSEVariable from arg if it's a tensor (either direct or wrapped in OpsValue).""" + if isinstance(arg, CSEVariable): + return arg + if isinstance(arg, OpsValue) and isinstance(arg.value, CSEVariable): + return arg.value + return None + + @staticmethod + def _as_expr(arg: CuteDSLArg) -> str: + cse_var = CuteDSLOpOverrides._get_cse_var(arg) + if cse_var is not None: + return str(cse_var) + return str(arg) + + @staticmethod + def _node_tensor_flags() -> tuple[bool, bool] | None: + node = V.current_node + if not isinstance(node, torch.fx.Node) or len(node.args) < 2: + return None + + def _is_tensor(raw_arg: object) -> bool: + if hasattr(raw_arg, "meta"): + val = raw_arg.meta.get("val") + return isinstance(val, torch.Tensor) and val.ndim > 0 + return False + + return _is_tensor(node.args[0]), _is_tensor(node.args[1]) + + @staticmethod + def _is_scalar_expr(arg: CuteDSLArg) -> bool: + cse_var = CuteDSLOpOverrides._get_cse_var(arg) + return isinstance(cse_var, CuteDSLCSEVariable) and cse_var.is_scalar_expr + + @staticmethod + def _is_tensor_like(arg: CuteDSLArg) -> bool: + cse_var = CuteDSLOpOverrides._get_cse_var(arg) + return cse_var is not None and not CuteDSLOpOverrides._is_scalar_expr(arg) + + @staticmethod + def _index_expr(arg: CuteDSLArg) -> sympy.Expr | None: + cse_var = CuteDSLOpOverrides._get_cse_var(arg) + if isinstance(cse_var, CuteDSLCSEVariable): + return cse_var.index_expr + if isinstance(arg, (int, sympy.Integer)): + return sympy.Integer(arg) + if isinstance(arg, str) and arg.lstrip("-").isdigit(): + return sympy.Integer(int(arg)) + return None + + @staticmethod + def _ensure_tensor_ssa( + arg: CuteDSLArg, + template_tensor: CuteDSLArg, + *, + is_tensor: bool, + dtype: torch.dtype | None = None, + ) -> str: + """ + Convert scalar arguments to TensorSSA using cute.full_like if needed. + + Args: + arg: The argument to check (CSEVariable for tensors, str for scalars, or OpsValue wrapper) + template_tensor: A tensor argument to use as template for full_like + + Returns: + String representation suitable for CuteDSL operations + """ + arg_expr = CuteDSLOpOverrides._as_expr(arg) + if is_tensor: + return arg_expr + template_expr = CuteDSLOpOverrides._as_expr(template_tensor) + if dtype is None: + return f"cute.full_like({template_expr}, {arg_expr})" + cute_dtype = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE[dtype] + return f"cute.full_like({template_expr}, {arg_expr}, {cute_dtype})" + + @staticmethod + def _extract_dtype_and_bounds( + *args: CuteDSLArg, + ) -> tuple[torch.dtype | None, ValueRanges[sympy.Expr]]: + """Extract dtype and bounds from CSEVariable arguments (including OpsValue wrappers).""" + for arg in args: + cse_var = CuteDSLOpOverrides._get_cse_var(arg) + if cse_var is not None: + return cse_var.dtype, cse_var.bounds + return None, ValueRanges.unknown() + + @staticmethod + def _apply_binary_op( + a: CuteDSLArg, + b: CuteDSLArg, + op_format: str, + index_expr_fn=None, + ) -> CuteDSLArg: + """ + Apply a binary operation with automatic scalar-to-tensor conversion. + + CuteDSL requires both operands to be TensorSSA objects for tensor operations. + This helper automatically converts scalar arguments to TensorSSA using + cute.full_like when at least one argument is a tensor (CSEVariable or OpsValue). + + Args: + a: First operand (CSEVariable for tensors, str for scalars, or OpsValue wrapper) + b: Second operand (CSEVariable for tensors, str for scalars, or OpsValue wrapper) + op_format: Format string with {a} and {b} placeholders for the operation + + Returns: + CSEVariable if at least one operand is a tensor, otherwise string + """ + a_cse = CuteDSLOpOverrides._get_cse_var(a) + b_cse = CuteDSLOpOverrides._get_cse_var(b) + + node_flags = CuteDSLOpOverrides._node_tensor_flags() + if node_flags is not None: + a_is_tensor, b_is_tensor = node_flags + a_is_tensor &= not CuteDSLOpOverrides._is_scalar_expr(a) + b_is_tensor &= not CuteDSLOpOverrides._is_scalar_expr(b) + else: + a_is_tensor = CuteDSLOpOverrides._is_tensor_like(a) + b_is_tensor = CuteDSLOpOverrides._is_tensor_like(b) + + tensor_arg = a if a_is_tensor else (b if b_is_tensor else None) + if tensor_arg is None: + tensor_arg = (a_cse if CuteDSLOpOverrides._is_tensor_like(a) else None) or ( + b_cse if CuteDSLOpOverrides._is_tensor_like(b) else None + ) + + if tensor_arg is not None: + if a_cse is None and b_cse is None: + return op_format.format( + a=CuteDSLOpOverrides._as_expr(a), + b=CuteDSLOpOverrides._as_expr(b), + ) + + a_ssa = CuteDSLOpOverrides._ensure_tensor_ssa( + a, tensor_arg, is_tensor=a_is_tensor + ) + b_ssa = CuteDSLOpOverrides._ensure_tensor_ssa( + b, tensor_arg, is_tensor=b_is_tensor + ) + result_expr = op_format.format(a=a_ssa, b=b_ssa) + + dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds(a, b) + expected = CuteDSLOpOverrides._expected_tensor_val() + if dtype is None: + dtype = expected.dtype if expected is not None else torch.int32 + if a_cse is not None: + shape = a_cse.shape + elif b_cse is not None: + shape = b_cse.shape + else: + shape = tuple(expected.size()) if expected is not None else None + + result = V.kernel.cse.generate( + V.kernel.body, result_expr, bounds=bounds, dtype=dtype, shape=shape + ) + if index_expr_fn is not None and isinstance(result, CuteDSLCSEVariable): + a_expr = CuteDSLOpOverrides._index_expr(a) + b_expr = CuteDSLOpOverrides._index_expr(b) + if a_expr is not None and b_expr is not None: + result.index_expr = V.graph.sizevars.simplify( + index_expr_fn(a_expr, b_expr) + ) + return result + + result_expr = op_format.format( + a=CuteDSLOpOverrides._as_expr(a), + b=CuteDSLOpOverrides._as_expr(b), + ) + if a_cse is None and b_cse is None: + return result_expr + + dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds(a, b) + 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 + if index_expr_fn is not None and isinstance(result, CuteDSLCSEVariable): + a_expr = CuteDSLOpOverrides._index_expr(a) + b_expr = CuteDSLOpOverrides._index_expr(b) + if a_expr is not None and b_expr is not None: + result.index_expr = V.graph.sizevars.simplify( + index_expr_fn(a_expr, b_expr) + ) + return result + + @staticmethod + def _expected_tensor_val() -> torch.Tensor | None: + """Return the fake-tensor value from the current FX node's metadata, if any.""" + node = V.current_node + if not isinstance(node, torch.fx.Node): + return None + val = node.meta.get("val") + return val if isinstance(val, torch.Tensor) else None + + @staticmethod + def _cast_expr(expr: str, dtype: torch.dtype) -> str: + cute_type = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get(dtype) + if cute_type is None: + return expr + return f"{cute_type}({expr})" + + @staticmethod + def _math_call(name: str, *args: str) -> str: + fast_math = ", fastmath=True" if _CUTEDSL_FAST_MATH.get() else "" + return f"cute.math.{name}({', '.join(args)}{fast_math})" + + @staticmethod + def _apply_unary_op( + x: CuteDSLArg, op_format: str, index_expr_fn=None + ) -> CuteDSLArg: + """ + Apply a unary operation, returning CSEVariable if input is a tensor. + + Args: + x: Input operand (CSEVariable for tensors, str for scalars, or OpsValue wrapper) + op_format: Format string with {x} placeholder for the operation + index_expr_fn: Optional sympy builder to propagate index semantics + through the op for lane analysis + + Returns: + CSEVariable if input is a tensor, otherwise string + """ + cse_var = CuteDSLOpOverrides._get_cse_var(x) + if cse_var is not None: + result_expr = op_format.format(x=str(cse_var)) + result = V.kernel.cse.generate( + V.kernel.body, + result_expr, + bounds=cse_var.bounds, + dtype=cse_var.dtype, + shape=cse_var.shape, + ) + if index_expr_fn is not None and isinstance(result, CuteDSLCSEVariable): + x_expr = CuteDSLOpOverrides._index_expr(x) + if x_expr is not None: + result.index_expr = V.graph.sizevars.simplify(index_expr_fn(x_expr)) + if CuteDSLOpOverrides._is_scalar_expr(x): + result.is_scalar_expr = True + return result + + return op_format.format(x=x) + + @staticmethod + def _apply_math_unary_op(x: CuteDSLArg, name: str) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_unary_op( + x, CuteDSLOpOverrides._math_call(name, "{x}") + ) + + @staticmethod + def constant(value: bool | float | int, dtype: torch.dtype) -> str: + """Generate CuteDSL constant representation.""" + if value == float("-inf"): + return "float('-inf')" + elif value == float("inf"): + return "float('inf')" + elif math.isnan(value): + return "float('nan')" + return repr(value) + + @staticmethod + def index_expr(expr: sympy.Expr, dtype: torch.dtype) -> CuteDSLArg: + if isinstance(expr, (int, sympy.Integer)): + return CuteDSLOpOverrides.constant(int(expr), dtype) + + idx_str = V.kernel.kexpr(V.kernel.rename_indexing(expr)) + result = V.kernel.cse.generate( + V.kernel.body, + idx_str, + bounds=get_bounds_index_expr(expr), + dtype=dtype, + ) + result.is_scalar_expr = True + if isinstance(result, CuteDSLCSEVariable): + result.index_expr = V.graph.sizevars.simplify(expr) + return result + + @staticmethod + def value_expr(expr: sympy.Expr, dtype: torch.dtype) -> CuteDSLArg: + # CuteDSL index_expr already emits the requested dtype, so value_expr + # has the same lowering here. + return CuteDSLOpOverrides.index_expr(expr, dtype) + + @staticmethod + def add(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op( + a, b, "({a} + {b})", lambda a_expr, b_expr: a_expr + b_expr + ) + + @staticmethod + def mul(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op( + a, b, "({a} * {b})", lambda a_expr, b_expr: a_expr * b_expr + ) + + @staticmethod + def sub(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op( + a, b, "({a} - {b})", lambda a_expr, b_expr: a_expr - b_expr + ) + + @staticmethod + def truediv(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} / {b})") + + @staticmethod + def floordiv(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op( + a, b, "({a} // {b})", lambda a_expr, b_expr: a_expr // b_expr + ) + + @staticmethod + def mod(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + # Inductor ops.mod is C-style; SymPy/Python % is Python-style for + # negative values, so don't attach index_expr metadata here. + return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} % {b})") + + @staticmethod + def remainder(a, b): + return CuteDSLOpOverrides._apply_binary_op( + a, b, "({a} % {b})", lambda a_expr, b_expr: a_expr % b_expr + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def exp(x: CuteDSLArg) -> CuteDSLArg: + """Exponential using CuteDSL cute.math.exp2 with log2(e) scaling.""" + if CuteDSLOpOverrides._get_cse_var(x) is None: + x = CuteDSLOpOverrides._cast_expr(str(x), torch.float32) + return CuteDSLOpOverrides._apply_unary_op( + x, + CuteDSLOpOverrides._math_call( + "exp2", f"{{x}} * {CuteDSLOpOverrides.LOG2_E}" + ), + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def exp2(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "exp2") + + @staticmethod + # pyrefly: ignore [bad-override] + def sqrt(x: CuteDSLArg) -> CuteDSLArg: + """Square root using CuteDSL cute.math.sqrt function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x, "sqrt") + + @staticmethod + # pyrefly: ignore [bad-override] + def rsqrt(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "rsqrt") + + @staticmethod + # pyrefly: ignore [bad-override] + def log(x: CuteDSLArg) -> CuteDSLArg: + """Natural logarithm using CuteDSL cute.math.log function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x, "log") + + @staticmethod + # pyrefly: ignore [bad-override] + def log2(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "log2") + + @staticmethod + # pyrefly: ignore [bad-override] + def log10(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "log10") + + @staticmethod + # pyrefly: ignore [bad-override] + def cos(x: CuteDSLArg) -> CuteDSLArg: + """Cosine using CuteDSL cute.math.cos function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x, "cos") + + @staticmethod + # pyrefly: ignore [bad-override] + def sin(x: CuteDSLArg) -> CuteDSLArg: + """Sine using CuteDSL cute.math.sin function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x, "sin") + + @staticmethod + # pyrefly: ignore [bad-override] + def tan(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "tan") + + @staticmethod + # pyrefly: ignore [bad-override] + def acos(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "acos") + + @staticmethod + # pyrefly: ignore [bad-override] + def asin(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "asin") + + @staticmethod + # pyrefly: ignore [bad-override] + def atan(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "atan") + + @staticmethod + # pyrefly: ignore [bad-override] + def atan2(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op( + a, + b, + CuteDSLOpOverrides._math_call("atan2", "{a}", "{b}"), + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def erf(x: CuteDSLArg) -> CuteDSLArg: + """Error function using CuteDSL cute.math.erf function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x, "erf") + + @staticmethod + # pyrefly: ignore [bad-override] + def sigmoid(x: CuteDSLArg) -> CuteDSLArg: + """Sigmoid with fp32 compute and cast-back to expected output dtype.""" + x_cse = CuteDSLOpOverrides._get_cse_var(x) + if x_cse is not None: + x_fp32: CuteDSLArg = CuteDSLOpOverrides.to_dtype( + x_cse, + torch.float32, + use_compute_types=False, + ) + else: + x_fp32 = CuteDSLOpOverrides._cast_expr(str(x), torch.float32) + + exp = CuteDSLOpOverrides._math_call( + "exp2", f"-{{x}} * {CuteDSLOpOverrides.LOG2_E}" + ) + result = CuteDSLOpOverrides._apply_unary_op( + x_fp32, + f"(1.0 / (1.0 + {exp}))", + ) + + expected = CuteDSLOpOverrides._expected_tensor_val() + expected_dtype = expected.dtype if expected is not None else None + if expected_dtype is not None and expected_dtype != torch.float32: + result_cse = CuteDSLOpOverrides._get_cse_var(result) + if result_cse is not None: + return CuteDSLOpOverrides.to_dtype( + result_cse, + expected_dtype, + use_compute_types=False, + ) + return CuteDSLOpOverrides._cast_expr(str(result), expected_dtype) + return result + + @staticmethod + def _minmax(a: CuteDSLArg, b: CuteDSLArg, *, op: str) -> CuteDSLArg: + index_expr_fn = Max if op == ">" else Min + if CuteDSLOpOverrides._is_tensor_like(a) or CuteDSLOpOverrides._is_tensor_like( + b + ): + return CuteDSLOpOverrides._apply_binary_op( + a, + b, + f"cute.where(({{a}}) {op} ({{b}}), {{a}}, {{b}})", + index_expr_fn, + ) + + lhs = CuteDSLOpOverrides._as_expr(a) + rhs = CuteDSLOpOverrides._as_expr(b) + expected = CuteDSLOpOverrides._expected_tensor_val() + if expected is not None: + lhs = CuteDSLOpOverrides._cast_expr(lhs, expected.dtype) + rhs = CuteDSLOpOverrides._cast_expr(rhs, expected.dtype) + result_expr = f"({lhs} if {lhs} {op} {rhs} else {rhs})" + a_cse = CuteDSLOpOverrides._get_cse_var(a) + b_cse = CuteDSLOpOverrides._get_cse_var(b) + if a_cse is None and b_cse is None: + return result_expr + dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds(a, b) + result = V.kernel.cse.generate( + V.kernel.body, + result_expr, + bounds=bounds, + dtype=dtype if dtype is not None else torch.int32, + ) + if isinstance(result, CuteDSLCSEVariable): + a_expr = CuteDSLOpOverrides._index_expr(a) + b_expr = CuteDSLOpOverrides._index_expr(b) + if a_expr is not None and b_expr is not None: + result.index_expr = V.graph.sizevars.simplify( + index_expr_fn(a_expr, b_expr) + ) + result.is_scalar_expr = True + return result + + @staticmethod + # pyrefly: ignore [bad-override] + def maximum(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._minmax(a, b, op=">") + + @staticmethod + # pyrefly: ignore [bad-override] + def minimum(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._minmax(a, b, op="<") + + @staticmethod + # pyrefly: ignore [bad-override] + def where( + condition: CuteDSLArg, + a: CuteDSLArg, + b: CuteDSLArg, + ) -> CuteDSLArg: + """Conditional selection - handles CSEVariable, OpsValue, and string inputs.""" + a_cse = CuteDSLOpOverrides._get_cse_var(a) + b_cse = CuteDSLOpOverrides._get_cse_var(b) + cond_cse = CuteDSLOpOverrides._get_cse_var(condition) + a_is_tensor = CuteDSLOpOverrides._is_tensor_like(a) + b_is_tensor = CuteDSLOpOverrides._is_tensor_like(b) + cond_is_tensor = CuteDSLOpOverrides._is_tensor_like(condition) + tensor_arg = ( + (a_cse if a_is_tensor else None) + or (b_cse if b_is_tensor else None) + or (cond_cse if cond_is_tensor else None) + ) + + if tensor_arg is not None: + a_ssa = CuteDSLOpOverrides._ensure_tensor_ssa( + a, tensor_arg, is_tensor=a_is_tensor + ) + b_ssa = CuteDSLOpOverrides._ensure_tensor_ssa( + b, tensor_arg, is_tensor=b_is_tensor + ) + cond_ssa = CuteDSLOpOverrides._ensure_tensor_ssa( + condition, tensor_arg, is_tensor=cond_is_tensor, dtype=torch.bool + ) + result_expr = f"cute.where({cond_ssa}, {a_ssa}, {b_ssa})" + + dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds( + a, b, condition + ) + + return V.kernel.cse.generate( + V.kernel.body, result_expr, bounds=bounds, dtype=dtype + ) + + result_expr = ( + f"cute.where({CuteDSLOpOverrides._as_expr(condition)}, " + f"{CuteDSLOpOverrides._as_expr(a)}, {CuteDSLOpOverrides._as_expr(b)})" + ) + if a_cse is None and b_cse is None and cond_cse is None: + 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 pow(a: CuteDSLArg, b: CuteDSLArg): + return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} ** {b})") + + @staticmethod + # pyrefly: ignore [bad-override] + def floor(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_math_unary_op(x, "floor") + + @staticmethod + # pyrefly: ignore [bad-override] + def abs(x: CuteDSLArg) -> CuteDSLArg: + """Absolute value using CuteDSL cute.math.abs function.""" + if isinstance(x, CSEVariable): + x_dtype = x.dtype + elif isinstance(x, OpsValue) and isinstance(x.value, CSEVariable): + x_dtype = x.value.dtype + else: + x_dtype = torch.float32 + + abs_op = ( + "mlir_math.absf" + if x_dtype in (torch.float16, torch.bfloat16, torch.float32) + else "mlir_math.absi" + ) + if CuteDSLOpOverrides._is_tensor_like(x): + return CuteDSLOpOverrides._apply_unary_op( + x, + f"cute.TensorSSA({abs_op}({{x}}), {{x}}.shape, {{x}}.dtype)", + index_expr_fn=sympy.Abs, + ) + return CuteDSLOpOverrides._apply_unary_op( + x, f"{abs_op}({{x}})", index_expr_fn=sympy.Abs + ) + + @staticmethod + def neg(x: CuteDSLArg) -> CuteDSLArg: + """Negation for both TensorSSA and scalar-like expressions.""" + if CuteDSLOpOverrides._is_tensor_like(x): + return CuteDSLOpOverrides._apply_unary_op( + x, + "cute.TensorSSA(-{x}, {x}.shape, {x}.dtype)", + index_expr_fn=lambda expr: -expr, + ) + return CuteDSLOpOverrides._apply_unary_op( + x, "(-{x})", index_expr_fn=lambda expr: -expr + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def inline_asm_elementwise( + *inputs: CuteDSLArg, + 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, + scalar_sources: tuple[bool, ...] | None = None, + ) -> CuteDSLArg: + """Emit an inline PTX block elementwise over a fragment. + + The requested dtype controls the logical result and eventual storage. + E8M0 results may stay decoded as Float32 while fused consumers use them. + """ + if constraints is None: + raise NotImplementedError( + "CuteDSL inline asm requires an explicit constraint list" + ) + result_type = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get(dtype) + if result_type is None: + raise NotImplementedError( + f"CuteDSL inline asm result dtype not supported: {dtype}" + ) + + constraint_parts = [part.strip() for part in constraints.split(",")] + input_constraints = [ + part.lstrip("=&") for part in constraint_parts if not part.startswith("=") + ] + + cast_inputs = list(inputs) + if input_dtypes is not None: + for source_index, (value, input_dtype) in enumerate( + zip(inputs, input_dtypes) + ): + source_constraints = input_constraints[ + source_index * pack : (source_index + 1) * pack + ] + cse_var = CuteDSLOpOverrides._get_cse_var(value) + if ( + source_constraints + and all(constraint == "h" for constraint in source_constraints) + and input_dtype in (torch.float16, torch.bfloat16) + and (cse_var is None or cse_var.dtype != input_dtype) + ): + if cse_var is None: + cast_inputs[source_index] = CuteDSLOpOverrides._cast_expr( + CuteDSLOpOverrides._as_expr(value), input_dtype + ) + else: + cast_inputs[source_index] = CuteDSLOpOverrides.to_dtype( + value, input_dtype, use_compute_types=False + ) + + operands = ", ".join( + str(CuteDSLOpOverrides._as_expr(value)) for value in cast_inputs + ) + if scalar_sources is None: + scalar_sources = (False,) * len(inputs) + elif len(scalar_sources) != len(inputs): + raise ValueError( + f"CuteDSL inline asm received {len(scalar_sources)} scalar-source " + f"flags for {len(inputs)} inputs" + ) + scalar_sources = tuple( + source_is_scalar or CuteDSLOpOverrides._is_scalar_expr(value) + for source_is_scalar, value in zip(scalar_sources, cast_inputs) + ) + expr = ( + f"inline_asm_elementwise_intrinsic({operands}, asm={asm!r}, " + f"constraints={constraints!r}, result_type={result_type}, " + f"is_pure={is_pure!r}, pack={pack!r}, " + f"scalar_sources={scalar_sources!r})" + ) + compute_dtype = torch.float32 if dtype == torch.float8_e8m0fnu else dtype + if not any( + CuteDSLOpOverrides._get_cse_var(value) is not None for value in inputs + ): + return expr + return V.kernel.cse.generate( + V.kernel.body, + expr, + dtype=compute_dtype, + ) + + @staticmethod + def to_dtype( + x: CuteDSLArg, dtype: torch.dtype, src_dtype=None, use_compute_types=True + ) -> CuteDSLArg: + """Type conversion using CuteDSL TensorSSA.to(Type[Numeric]). + + Maps torch dtypes to cutlass.cute.typing numeric types and emits + `{x}.to(cute.typing.)`. + + Raises NotImplementedError for unsigned integer and unsupported dtypes. + """ + if use_compute_types: + dtype = upcast_compute_type(dtype) + + cute_type = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get(dtype) + if cute_type is None: + raise NotImplementedError( + f"CuteDSL dtype cast not implemented for torch dtype: {dtype}" + ) + + if isinstance(x, CSEVariable): + result_expr = f"{str(x)}.to({cute_type})" + result = V.kernel.cse.generate( + V.kernel.body, + result_expr, + bounds=x.bounds, + dtype=dtype, + shape=x.shape, + ) + if CuteDSLOpOverrides._is_scalar_expr(x): + result.is_scalar_expr = True + if ( + dtype in (torch.int32, torch.int64) + and isinstance(result, CuteDSLCSEVariable) + and isinstance(x, CuteDSLCSEVariable) + ): + result.index_expr = x.index_expr + return result + + return f"{x}.to({cute_type})" + + @staticmethod + def tanh(x0: CuteDSLArg) -> CuteDSLArg: + """Hyperbolic tangent using CuteDSL cute.math.tanh function.""" + return CuteDSLOpOverrides._apply_math_unary_op(x0, "tanh") + + # Logical operations + @staticmethod + def logical_and(x0: CuteDSLArg, x1: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x0, x1, "({a} & {b})") + + @staticmethod + def logical_or(x0: CuteDSLArg, x1: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x0, x1, "({a} | {b})") + + @staticmethod + def logical_xor(x0: CuteDSLArg, x1: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x0, x1, "({a} ^ {b})") + + # Bitwise operations (override parent class to properly CSE) + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_and(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} & {b})") + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_or(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} | {b})") + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_xor(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} ^ {b})") + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_not(x: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_unary_op(x, "(~{x})") + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_left_shift(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} << {b})") + + @staticmethod + # pyrefly: ignore [bad-override] + def bitwise_right_shift(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} >> {b})") + + @staticmethod + def logical_not(a): + """Logical NOT.""" + return CuteDSLOpOverrides._apply_unary_op(a, "({x} == 0)") + + # Comparison operations + @staticmethod + def eq(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.eq({a}, {b})") + + @staticmethod + def ne(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.ne({a}, {b})") + + @staticmethod + def lt(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.lt({a}, {b})") + + @staticmethod + def le(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.le({a}, {b})") + + @staticmethod + def gt(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.gt({a}, {b})") + + @staticmethod + def ge(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg: + return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.ge({a}, {b})") diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..cd893bc13c459a9878cd225bf1cd3adec3da1880 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_scheduling.py @@ -0,0 +1,252 @@ +# mypy: allow-untyped-defs +import hashlib +import logging +from collections.abc import Sequence +from typing import cast + +from torch._inductor.utils import Placeholder +from torch.utils._ordered_set import OrderedSet + +from ... import config +from ...codecache import code_hash, get_path +from ...ir import CuteDSLTemplateBuffer +from ...scheduler import ( + BaseSchedulerNode, + BaseScheduling, + FusedSchedulerNode, + SchedulerNode, +) +from ...select_algorithm import PartialRender +from ...utils import get_fused_kernel_name, get_kernel_metadata +from ...virtualized import V +from ..common import BackendFeature, IndentedBuffer + + +log = logging.getLogger(__name__) + + +class CuteDSLScheduling(BaseScheduling): + """ + Scheduling implementation for CuteDSL (CUTLASS Python DSL) kernels. + This class is intended to be used in combination with other schedulers, + and delegated to by CUDACombinedScheduling. + """ + + @classmethod + def get_backend_features(cls, device) -> OrderedSet[BackendFeature]: + return OrderedSet() + + @staticmethod + def is_cutedsl_template(node: BaseSchedulerNode) -> bool: + """Check if a node is a CuteDSL template.""" + return isinstance(node, SchedulerNode) and isinstance( + node.node, CuteDSLTemplateBuffer + ) + + def is_cutedsl_fused_template(self, node: BaseSchedulerNode) -> bool: + """Check if a node is a fused CuteDSL template.""" + return isinstance(node, FusedSchedulerNode) and self.is_cutedsl_template(node) + + def can_fuse_vertical( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + """ + TODO CuteDSL doesn't support vertical fusion yet. + This could be extended in the future for epilogue fusion. + """ + return False + + def can_fuse_horizontal( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + """CuteDSL doesn't support horizontal fusion yet.""" + return False + + def define_kernel( + self, src_code_str: str, node_schedule, precompile_metadata=None + ) -> str: + """Produce the kernel string + Args: + src_code_str: The finalized kernel code string + node_schedule: List of nodes in the schedule + precompile_metadata: Optional dict with shapes/dtypes for subprocess precompilation + + Note: + This is a little weird since async_compile.cutedsl() has to write the string to + a file in order to cute compile it. Feels bad to have two... + """ + wrapper = V.graph.wrapper_code + + # Use the string as the key for caching + if src_code_str in wrapper.src_to_kernel: + kernel_name = wrapper.src_to_kernel[src_code_str] + else: + fused_name = ( + get_fused_kernel_name(node_schedule, config.triton.descriptive_names) + if config.triton.descriptive_names + else "" + ) + + kernel_hash = hashlib.sha256(src_code_str.encode("utf-8")).hexdigest()[:8] + if fused_name == "fused": + kernel_name = f"cutedsl_{kernel_hash}" + else: + kernel_name = f"cutedsl_{fused_name}_{kernel_hash}" + wrapper.src_to_kernel[src_code_str] = kernel_name + src_code_str = src_code_str.replace( + str(Placeholder.KERNEL_NAME), kernel_name + ) + + _, _, kernel_path = get_path(code_hash(src_code_str), "py") + + compile_wrapper = IndentedBuffer() + compile_wrapper.writeline(f"async_compile.cutedsl({kernel_name!r}, r'''") + compile_wrapper.splice(src_code_str, strip=True) + if precompile_metadata is not None: + compile_wrapper.writeline( + f"''', precompile_metadata={precompile_metadata!r})" + ) + else: + compile_wrapper.writeline("''')") + + 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 + ) + return kernel_name + + def codegen_template( + self, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + prologue_nodes: Sequence[BaseSchedulerNode], + ): + """ + Codegen a CuteDSL template. Currently doesn't support fusion. + """ + if not self.is_cutedsl_template(template_node): + raise AssertionError( + "Template node passed to CuteDSLScheduling.codegen_template must be a " + "SchedulerNode that wraps a CuteDSLTemplateBuffer" + ) + # TODO remove when supported + if epilogue_nodes: + raise AssertionError("CuteDSL doesn't support epilogue fusion yet") + if prologue_nodes: + raise AssertionError("CuteDSL doesn't support prologue fusion yet") + + template_node = cast(SchedulerNode, template_node) + ctb: CuteDSLTemplateBuffer = cast(CuteDSLTemplateBuffer, template_node.node) + + kernel, render = ctb.make_kernel_render(ctb) # type: ignore[misc] + template_node.mark_run() + src_code = render() + # Finalize PartialRender if needed + if isinstance(src_code, PartialRender): + src_code_str = src_code.finalize_all() + else: + src_code_str = src_code + + precompile_metadata = self._build_precompile_metadata(kernel, ctb) + + with V.set_kernel_handler(kernel): + node_schedule = [template_node] + kernel_name = self.define_kernel( + src_code_str, node_schedule, precompile_metadata + ) + 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() + + def _build_precompile_metadata(self, kernel, ctb): + """Extract shapes and dtypes from kernel inputs/output for subprocess precompilation. + + Returns None if shapes are symbolic (dynamic shapes), in which case the + subprocess will skip precompilation and the kernel compiles lazily on first call. + """ + if not hasattr(kernel, "_template_input_args"): + return None + + precompile_shapes = {} + precompile_strides = {} + precompile_dtypes = {} + + try: + for arg_name, input_node in kernel._template_input_args: + template_name = arg_name.removeprefix("arg_") + size = input_node.get_size() + precompile_shapes[template_name] = [int(s) for s in size] + stride = input_node.get_stride() + precompile_strides[template_name] = [int(s) for s in stride] + precompile_dtypes[template_name] = str( + input_node.get_dtype() + ).removeprefix("torch.") + + output_size = ctb.layout.size + precompile_shapes["output"] = [int(s) for s in output_size] + output_stride = ctb.layout.stride + precompile_strides["output"] = [int(s) for s in output_stride] + precompile_dtypes["output"] = str(ctb.layout.dtype).removeprefix("torch.") + except (TypeError, RuntimeError, ValueError): + log.debug( + "Skipping CuteDSL precompile metadata: symbolic sizes cannot be " + "resolved to concrete values" + ) + return None + + device = ctb.layout.device + device_index = device.index if device.index is not None else 0 + + import torch + + device_capability = None + if torch.cuda.is_available(): + device_capability = torch.cuda.get_device_capability(device_index) + + metadata: dict[str, object] = { + "precompile_shapes": precompile_shapes, + "precompile_strides": precompile_strides, + "precompile_dtypes": precompile_dtypes, + "device_index": device_index, + "device_capability": device_capability, + } + + hw_info = self._build_hw_info(kernel) + if hw_info is not None: + metadata["hw_info"] = hw_info + + return metadata + + @staticmethod + def _build_hw_info(kernel) -> tuple[int, int] | None: + """Compute (sm_count, max_active_clusters) in the main process. + + Reads CLUSTER_M/N from kernel template kwargs and queries + HardwareInfo so subprocess workers never touch CUDA driver APIs. + Returns None if CUTLASS is unavailable or the template has no cluster config. + """ + template_kwargs = getattr(kernel, "_template_kwargs", None) + if template_kwargs is None: + return None + + cluster_m = template_kwargs.get("CLUSTER_M") + cluster_n = template_kwargs.get("CLUSTER_N") + if cluster_m is None or cluster_n is None: + return None + + try: + import cutlass.utils + + cluster_product = int(cluster_m) * int(cluster_n) + hw = cutlass.utils.HardwareInfo() + sm_count = hw.get_max_active_clusters(1) + max_active_clusters = hw.get_max_active_clusters(cluster_product) + return (sm_count, max_active_clusters) + except Exception: + log.debug( + "Could not compute hw_info for CuTe DSL precompile", exc_info=True + ) + return None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_template.py new file mode 100644 index 0000000000000000000000000000000000000000..7a67b05c530b51de66d6e50824cf376c2db3966a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_template.py @@ -0,0 +1,263 @@ +# mypy: allow-untyped-defs +import functools +import itertools +import logging +from collections.abc import Iterable +from typing import Any +from unittest.mock import patch + +from torch._inductor.utils import Placeholder, unique +from torch._inductor.virtualized import V + +from ...autotune_process import CuteDSLBenchmarkRequest, TensorMeta +from ...ir import Buffer, ChoiceCaller, CuteDSLTemplateBuffer, IRNode, Layout, TensorBox +from ..common import KernelTemplate +from .cutedsl_kernel import CuteDSLTemplateKernel + + +log = logging.getLogger(__name__) + + +class CuteDSLTemplate(KernelTemplate): + """Template for generating CuteDSL (CUTLASS Python DSL) kernels. + + Subclasses may override ``caller_type`` to attach template-specific + metadata or precompile behavior while reusing the common render and + benchmark request construction. + """ + + kernel_type: type[Any] = CuteDSLTemplateKernel + caller_type: type[Any] | None = None + index_counter = itertools.count() + all_templates: dict[str, "CuteDSLTemplate"] = {} + + def __init__( + self, + name: str, + source: str, + subgraph_fn: Any | None = None, + mask_fn: Any | None = None, + ) -> None: + super().__init__(name) + self.source = source + self.subgraph_fn = subgraph_fn + self.mask_fn = mask_fn + self.template = CuteDSLTemplate._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.source != self.source: + raise AssertionError(f"duplicate template name, {name}") + CuteDSLTemplate.all_templates[name] = self + + @staticmethod + @functools.lru_cache(None) + # pyrefly: ignore [bad-override] + def _template_from_string(source: str) -> Any: + return KernelTemplate._template_from_string(source) + + 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. + """ + try: + choices.append(self.generate(**kwargs)) + return None + except NotImplementedError as e: + log.debug("CuteDSL template choice generation failed: %s", e) + return e + except Exception as e: + log.debug("CuteDSL template choice generation error: %s", e) + return NotImplementedError(f"CuteDSL template failed: {e}") + + def generate(self, **kwargs: Any) -> ChoiceCaller: + """Generate the CuteDSL kernel caller for template autotuning.""" + input_nodes = kwargs.pop("input_nodes") + layout = kwargs.pop("layout") + mutated_inputs = kwargs.pop("mutated_inputs", None) + subgraphs = kwargs.pop("subgraphs", None) + template_kwargs = dict(kwargs) + + kernel_name = f"cutedsl_{self.name}_{next(self.index_counter)}" + + if self.template is None: + raise RuntimeError("Template compilation failed (Jinja2 required)") + + self.output_node: Buffer = Buffer(name="buf_out", layout=layout) + # Patch V.graph.get_dtype to handle the fake buf_out buffer + with patch.object( + V.graph, "get_dtype", KernelTemplate._fake_get_dtype(self.output_node) + ): + kernel = self.kernel_type( + kernel_name=kernel_name, + input_nodes=input_nodes, + output_node=self.output_node, + subgraphs=subgraphs, + ) + code = kernel.render(self.template, **kwargs) + + input_call_args = tuple(kernel.args.input_buffers.keys()) + expected_input_args = tuple(unique(x.get_name() for x in input_nodes)) + if input_call_args[: len(expected_input_args)] != expected_input_args: + raise RuntimeError( + "CuteDSL template input registration order changed while " + "collecting captured subgraph buffers. Expected template " + "inputs to be registered before captured buffers, got " + f"{input_call_args}, expected prefix {expected_input_args}." + ) + extra_capture_names = input_call_args[len(expected_input_args) :] + + # Resolve captured nodes from the graph-level side table + # (populated by realize_captures_for_cutedsl) to get view nodes. + graph_captures = getattr(V.graph, "_cutedsl_capture_nodes", {}) + capture_nodes_by_name: dict[str, Any] = {} + extra_capture_nodes = [] + for name in extra_capture_names: + node = graph_captures.get(name) + if node is None: + node = V.graph.get_buffer(name) + capture_nodes_by_name[name] = node + extra_capture_nodes.append(node) + input_nodes = list(input_nodes) + extra_capture_nodes + + kernel.set_capture_input_nodes(capture_nodes_by_name) + with kernel._patch_get_dtype_for_captures(): + _, call_args, _, _ = kernel.args.python_argdefs() + expected_args = list(input_call_args) + expected_args.append(self.output_node.get_name()) + if list(call_args)[: len(expected_args)] != expected_args: + raise RuntimeError( + "CuteDSL template benchmark argument order changed while " + "collecting dynamic scalar args. Expected prefix " + f"{expected_args}, got {list(call_args)}." + ) + extra_args = tuple( + V.graph.sizevars.optimization_hints(call_args[len(expected_args) :]) + ) + + bmreq = CuteDSLBenchmarkRequest( + kernel_name=kernel_name, + input_tensor_meta=TensorMeta.from_irnodes(input_nodes), + output_tensor_meta=TensorMeta.from_irnodes(self.output_node), + extra_args=extra_args, + source_code=code, + ) + + def make_kernel_render(out_node, hint_override: int | None = None): + """ + Factory function that creates a kernel renderer for the final output. + + This closure captures the current template and parameters, but allows + the output node to be specified later. This is used during the final + kernel selection phase when the actual output buffer is available. + """ + render_kernel = self.kernel_type( + kernel_name=str(Placeholder.KERNEL_NAME), + input_nodes=input_nodes, + output_node=out_node, + subgraphs=subgraphs, + ) + render_kernel.set_capture_input_nodes(capture_nodes_by_name) + + def render(): + return render_kernel.render(self.template, **kwargs) + + return render_kernel, render + + caller_type = self.caller_type or CuteDSLTemplateCaller + return caller_type( + name=kernel_name, + input_nodes=input_nodes, + layout=layout, + make_kernel_render=make_kernel_render, + bmreq=bmreq, + template=self, + mutated_inputs=mutated_inputs, + template_kwargs=template_kwargs, + ) + + +class CuteDSLTemplateCaller(ChoiceCaller): + """Caller for CuteDSL templates that integrates with the autotuning system.""" + + def __init__( + self, + name: str, + input_nodes: list[Buffer], + layout: Layout, + make_kernel_render: Any, + bmreq: CuteDSLBenchmarkRequest, + template: "CuteDSLTemplate", + mutated_inputs: Iterable[IRNode] | None = None, + template_kwargs: dict[str, Any] | None = None, + ): + description = self._build_description(name, template_kwargs) + super().__init__( + name=name, + input_nodes=input_nodes, + layout=layout, + description=description, + ) + self.make_kernel_render = make_kernel_render + self.bmreq = bmreq + self.template = template + self.mutated_inputs = mutated_inputs + + def _build_description( + self, name: str, template_kwargs: dict[str, Any] | None + ) -> str: + if not template_kwargs: + return f"CuteDSL template {name}" + kwargs_desc = ", ".join(f"{k}={v}" for k, v in template_kwargs.items()) + return f"CuteDSL template {name} ({kwargs_desc})" + + def __str__(self) -> str: + return f"CuteDSLTemplateCaller({self.name})" + + def benchmark(self, *args, out) -> float: + """Benchmark the kernel execution.""" + return self.bmreq.benchmark(*args, out=out) + + def output_node(self) -> TensorBox: + """Create the output node for this template choice.""" + buffer = CuteDSLTemplateBuffer( + layout=self.layout, + inputs=self.input_nodes, + make_kernel_render=self.make_kernel_render, + template=self.template, + mutated_inputs=self.mutated_inputs, + ) + # Pass KTC annotation to the buffer for encoding + if "ktc" in self.annotations: + buffer.annotations["ktc"] = self.annotations["ktc"] + return TensorBox.create(buffer) + + def call_name(self) -> str: + """Return the kernel call name.""" + return self.name + + def to_callable(self) -> Any: + """Return callable that can execute this kernel.""" + return self.make_kernel_render + + def hash_key(self) -> str: + """Return unique hash key for this choice.""" + return "-".join( + [ + self.name.rsplit("_", 1)[0], + self.bmreq.module_cache_key, + ] + ) + + def info_dict(self) -> dict[str, Any]: + """Return information about this kernel.""" + return { + "name": self.name, + "backend": "CuteDSL", + "template": self.template.name, + } diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/lane_analysis.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/lane_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..42ca1b50b0f2e40770ac399b5a2218fdab7a25b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutedsl/lane_analysis.py @@ -0,0 +1,140 @@ +# mypy: allow-untyped-defs + +import dataclasses + +import sympy + +from torch.utils._ordered_set import OrderedSet + +from ...virtualized import V + + +@dataclasses.dataclass(frozen=True, slots=True) +class LaneExprInfo: + """How an index expression changes across vectorized lanes. + + A lane is one element of a vectorized CuteDSL computation. For a 32-lane + mask/load, lane 0 is the first element in the group and lane 31 is the last. + + Attributes: + is_uniform: All lanes evaluate to the same value, e.g. for flex-flash``b_idx``. + is_contiguous: Lanes evaluate to consecutive aligned values for the + requested width, e.g. ``kv_idx + lane`` when lane 0 is aligned. + contiguous_width: Largest aligned contiguous power-of-two width proven, + or None if no vector-width contiguity is proven. + """ + + is_uniform: bool + is_contiguous: bool + contiguous_width: int | None + + +def classify_lane_expr( + expr: sympy.Expr, + lane_var: sympy.Symbol, + *, + max_width: int, + uniform_symbols: OrderedSet[sympy.Symbol] | None = None, +) -> LaneExprInfo: + """Classify how ``expr`` varies across ``lane_var`` vector lanes. + + ``max_width`` is the requested vector width. We start with this as the + maximum width to check and then decrease in powers of two trying to find a width + that satisfies contiguity across lanes. We cap since we are trying to get vectorized loads + which are at 128 and 256(B200) bits so no need to check higher. + + For example a ``lane_var = kv_idx`` and ``max_width = 8``: + + - No dependency on lane var: ``q_idx`` returns + ``LaneExprInfo(is_uniform=True, is_contiguous=False, contiguous_width=None)``. + - ``kv_idx`` at an 8-aligned group start returns + ``LaneExprInfo(is_uniform=False, is_contiguous=True, contiguous_width=8)``. + - ``kv_idx + 4`` at a 4-aligned but not 8-aligned group start returns + ``LaneExprInfo(is_uniform=False, is_contiguous=False, contiguous_width=4)``. + - ``kv_idx * 2`` returns + ``LaneExprInfo(is_uniform=False, is_contiguous=False, contiguous_width=None)``. + """ + if max_width <= 1: + return LaneExprInfo(True, False, None) + + semantic_expr = V.graph.sizevars.simplify(expr) + if uniform_symbols is not None and semantic_expr.free_symbols <= uniform_symbols: + return LaneExprInfo(True, False, None) + + lane_contiguity = V.graph.sizevars.analyze_lane_contiguity(semantic_expr, lane_var) + contiguous_width = aligned_contiguous_width( + semantic_expr, + lane_var, + max_width=max_width, + lane_contiguity=lane_contiguity, + ) + return LaneExprInfo( + is_uniform=lane_contiguity.is_uniform_for(max_width), + is_contiguous=lane_contiguity.stride == 1 and contiguous_width == max_width, + contiguous_width=contiguous_width, + ) + + +def aligned_contiguous_width( + expr: sympy.Expr, + lane_var: sympy.Symbol, + *, + max_width: int, + lane_contiguity=None, +) -> int | None: + """Return the largest aligned power-of-two contiguous lane width.""" + if not (max_width >= 2 and max_width.bit_count() == 1): + raise AssertionError(f"max_width must be a power of two >= 2, got {max_width}") + if lane_contiguity is None: + lane_contiguity = V.graph.sizevars.analyze_lane_contiguity(expr, lane_var) + start_expr = lane_group_start(expr, lane_var) + width = max_width + while width >= 2: + if ( + lane_contiguity.is_contiguous_for(width) + and V.graph.sizevars.statically_known_multiple_of(start_expr, width) + and V.graph.sizevars.statically_known_geq(start_expr, 0) + ): + return width + width //= 2 + return None + + +def lane_group_start(expr: sympy.Expr, lane_var: sympy.Symbol) -> sympy.Expr: + """Return the lane-group base value by evaluating ``expr`` at lane 0. + + For example, if ``expr = base + lane_var``, this returns ``base``. This is + useful when checking vector-load alignment: a contiguous lane expression is only + safe to vectorize when the first lane's address is sufficiently aligned. + """ + return V.graph.sizevars.simplify(expr.xreplace({lane_var: sympy.Integer(0)})) + + +def decompose_affine_lane_expr( + expr: sympy.Expr, lane_var: sympy.Symbol +) -> tuple[sympy.Expr, sympy.Expr] | None: + """Return ``(stride, base)`` when ``expr`` is affine in ``lane_var``. + + The result satisfies ``expr == stride * lane_var + base``, where neither + ``stride`` nor ``base`` depends on ``lane_var``. + For example: ``stride == 0`` means lane-uniform, ``stride == 1`` means + consecutive lanes access consecutive indices, and other strides are + non-contiguous gathers. + + Examples with ``lane_var = i``: + ``b + i`` -> ``(1, b)`` + ``b + 2 * i`` -> ``(2, b)`` + ``b`` -> ``(0, b)`` + + Returns ``None`` for non-affine expressions or when the extracted stride or + base still depends on ``lane_var``. + """ + expr = V.graph.sizevars.simplify(expr) + lane_coeff = expr.coeff(lane_var) + rest = lane_group_start(expr, lane_var) + if lane_var in lane_coeff.free_symbols or lane_var in rest.free_symbols: + return None + residual = V.graph.sizevars.simplify(expr - (lane_coeff * lane_var + rest)) + if residual != 0: + return None + return lane_coeff, rest diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fec1e0e4617a9663675b339cc9cd71f494da6967 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7d7122b9261334d69db50b0d081b3984507dcdf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/gemm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/gemm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b40acdfe153be1e30838c014a00120ac6108d84 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/gemm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e0bf60ebcf2a8c9ac26d1b0badf8d2536f5d164 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/python_evt.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/python_evt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d09124185ddab2813cd355db285b7fb841b0cf6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/python_evt.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9da1e8d2a6943cb57c7afd3b9293aea5877facd0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/serialization.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/serialization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..479a1ea45c1e73299e1fccc9e5d265b5e1635e3a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/serialization.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5bae7ec3e8cac717aafc58287af981d04c805bb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bc84c936503f94bb2fc0c6f6a866484afd70b5c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/cache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..18fc758392e54e3cee0220d8915cc3a8a8a87e63 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/cache.py @@ -0,0 +1,123 @@ +# mypy: allow-untyped-defs +import functools +import hashlib +import inspect +import json +import logging +import os +import time +from typing import Any + +import torch._inductor.config as config +from torch._inductor.codecache import cutlass_key +from torch._inductor.codegen.cutlass import serialization, utils +from torch._inductor.codegen.cutlass.serialization import ( + get_cutlass_operation_serializer, +) +from torch._inductor.runtime.cache_dir_utils import cache_dir +from torch._inductor.utils import clear_on_fresh_cache + + +log = logging.getLogger(__name__) + + +CONFIG_PREFIX: str = "configs" + + +def get_config_request_key( + arch: str, + toolkit_version: str, + instantiation_level: str, +) -> str: + """ + Return a key for the full ops, based on cutlass key, arch, toolkit version, instantiation level, and serialization.py file hash. + """ + + # Get hash of serialization.py and cutlass_utils.py files using their module file paths + def get_file_hash(file_module): + file_path = inspect.getfile(file_module) + with open(file_path, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + serialization_hash = get_file_hash(serialization) + cutlass_utils_hash = get_file_hash(utils) + + hash_target = "-".join( + [ + cutlass_key().hex(), + arch, + toolkit_version, + instantiation_level, + serialization_hash, + cutlass_utils_hash, + ] + ) + return hashlib.sha256(hash_target.encode("utf-8")).hexdigest()[0:8] + + +def _generate_config_filename(request_key: str) -> str: + """ + Generate a filename for the full ops. + """ + return f"{CONFIG_PREFIX}_{request_key}.json" + + +@clear_on_fresh_cache +@functools.cache +def maybe_fetch_ops(device_type: str) -> list[Any] | None: + """ + Fetch ops from databases. + """ + if config.force_disable_caches: + return None + + # setup + arch: str = utils.cutlass_arch(device_type) + version: str = utils.toolkit_version(device_type) + if device_type == "cuda": + # get_cuda_version might return "12.4.0" or "12.4" + # but we want to use "12.4" + version = ".".join(version.split(".")[:2]) + instantiation_level: str = config.cutlass.cutlass_instantiation_level + + # filename and filepath + request_key: str = get_config_request_key(arch, version, instantiation_level) + filename: str = _generate_config_filename(request_key) + filepath: str = os.path.join(cache_dir(), filename) + + # try fetch + serialized_ops: list[str] | None = None + start_time = time.time() + if os.path.isfile(filepath): + # locally + try: + with open(filepath) as f: + serialized_ops = json.load(f) + + if not isinstance(serialized_ops, list): + raise AssertionError( + f"Expected serialized ops is a list, got {type(serialized_ops)}" + ) + except Exception: + log.warning( + "Failed to load CUTLASS config %s from local cache", + filename, + exc_info=True, + ) + serialized_ops = None + elif config.is_fbcode(): + from torch._inductor.fb.cutlass_remote_cache import ( + maybe_fetch_cutlass_configs_from_remote, + ) + + # from remote + serialized_ops = maybe_fetch_cutlass_configs_from_remote(filepath) + + if serialized_ops is None: + return None + + # deserialize + serializer = get_cutlass_operation_serializer() + full_ops = [serializer.deserialize(x) for x in serialized_ops] # type: ignore[union-attr] + log.info("Loaded ops from %s cache in %.3fs", filename, time.time() - start_time) + return full_ops diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/gemm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/gemm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..6ebc194b041a2a419a9770a2e8c2cc85c7edf216 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/gemm_template.py @@ -0,0 +1,2157 @@ +# mypy: allow-untyped-defs +import copy +import enum +import functools +import logging +import re +import time +from abc import ABC, abstractmethod +from typing import Any + +import torch +import torch.utils._pytree as pytree +from torch._dynamo.utils import counters +from torch._inductor.autotune_process import TensorMeta +from torch._inductor.codegen.cutlass.cache import maybe_fetch_ops +from torch._inductor.codegen.wrapper import PythonWrapperCodegen +from torch._inductor.runtime.runtime_utils import dynamo_timed +from torch._inductor.scheduler import BaseSchedulerNode +from torch._inductor.select_algorithm import create_inputs_key +from torch._inductor.utils import clear_on_fresh_cache + +from ... import ir +from ...config import cutlass as inductor_cutlass_config +from ...ir import ( + Buffer, + ChoiceCaller, + CUTLASSTemplateBuffer, + FixedLayout, + FlexibleLayout, + IRNode, + Layout, + ReinterpretView, +) +from ...utils import is_dynamic, Placeholder, sympy_product +from ...virtualized import V +from ..common import IndentedBuffer +from ..cuda import cuda_env +from . import utils as cutlass_utils +from .kernel import CUTLASSTemplateKernel +from .python_evt import CutlassEVTCodegen, scaled_mm_evt +from .template import CUTLASSTemplate +from .utils import ( + ACCUMULATOR_DTYPES, + dtype_match, + torch_dtype_to_cutlass_type, + XW_DTYPES, +) + + +GemmOperation = Any +EVTArgRenames = Any + +log = logging.getLogger(__name__) + +# Jinja template for GEMM Kernel, used by the CUTLASSGemm3xTemplate class below. +GEMM_TEMPLATE_CUTLASS_3X = r""" +{{template.header().getvalue()}} +{{template.globals().getvalue()}} +{{epilogue_visitor_tree}} +{{instance_definition}} +// When workspace_size is not a nullptr, populates requested workspace_size and returns. +// Otherwise, computes the Gemm kernel using the given workspace ptr. +extern "C" { +PT_EXPORT {{kernel_call_signature}} { + try { + using ElementComputeEpilogue = {{instance_type}}::ElementAccumulator; + using coord_t = cutlass::gemm::GemmCoord::Index; + static cutlass::KernelHardwareInfo hw_info; + if (hw_info.sm_count == 0) { + hw_info.sm_count = cutlass::KernelHardwareInfo::query_device_multiprocessor_count(0); + CUTLASS_TRACE_HOST("Query result for SM count per device: " << hw_info.sm_count); + } + {{dynamic_cluster}} + {{instance_type}}::Arguments arguments; + {{template.render_gemm_arguments(argument_template, epilogue_template, should_swap_xw, + X, W, Bias, Y, alpha, beta, kernel, epilogue_args)}} + {{instance_type}} gemm_op; + if (workspace_size) { + *workspace_size = gemm_op.get_workspace_size(arguments); + return 0; + } + // check for null pointers after workspace size, since querying workspace size doesn't require valid data pointers +#ifndef CUTLASS_BACKEND_DISABLE_CHECKS + { + auto status = gemm_op.can_implement(arguments); + CUTLASS_CHECK(status); + } +#endif +#ifdef CUTLASS_DEBUG_TRACE_LEVEL +#if CUTLASS_DEBUG_TRACE_LEVEL == 1 + { + // Print the maximum number of active blocks per SM for the kernel if CUTLASS_DEBUG_TRACE_LEVEL == 1 + // we don't need a print statement, it's happening inside the function. + gemm_op.maximum_active_blocks(); + } +#endif +#endif + { + auto status = gemm_op.initialize(arguments, workspace, stream); + CUTLASS_CHECK(status); + } + { + auto status = gemm_op(stream); + CUTLASS_CHECK(status); + } + } + catch (std::exception& e) { + std::cerr << "Runtime error: " << e.what() << std::endl; + return -1; + } + catch (...) { + return -1; + } + return 0; +} +} + +// configuration name: {{op_conf_name}} +""" + +# Jinja template for Cutlass 3.x GEMM Kernel arguments, used by the CUTLASSGemmTemplate class below. +GEMM_ARGS_CUTLASS_3X = r""" + // Initialize GemmUniversal3xInstance arguments. + arguments = { + {{template.gemm_mode()}}, // GemmUniversalMode mode + { + static_cast({{M}}), + static_cast({{N}}), + static_cast(K), + static_cast(B) + }, // ProblemShape problem_shape + { + {{template.cutlass_type_cast(X, kernel.ptr(X))}}, // ElementA const* ptr_A + { + {{template.cute_int(kernel.stride(X, -2), "stride_x0")}}, + {{template.cute_int(kernel.stride(X, -1), "stride_x1")}}, + {{template.cute_int(kernel.batch_stride(X), "batch_stride_x")}} + }, // StrideA dA + {{template.cutlass_type_cast(W, kernel.ptr(W))}}, // ElementB const* ptr_B + { + {{template.cute_int(kernel.stride(W, -1), "stride_w1")}}, + {{template.cute_int(kernel.stride(W, -2), "stride_w0")}}, + {{template.cute_int(kernel.batch_stride(W), "batch_stride_w")}} + }, // StrideB dB + }, // MainloopArguments mainloop + {{epilogue_arguments}}, + hw_info + }; + arguments.scheduler.max_swizzle_size = swizzle; +""" + +# Jinja template for Cutlass 3.x GEMM Kernel arguments if epilogue fusion is applied, +# used by the CUTLASSGemmTemplate class below. +GEMM_ARGS_CUTLASS_3X_EPILOGUE = r""" + // see https://tinyurl.com/4rk89z48 + { + {{epilogue_args}}, // thread, typename FusionCallbacks::Arguments ( EVT ) or ThreadEpilogueOp::Params (non-EVT ) + {{template.cutlass_type_cast(Bias, kernel.ptr(Bias))}}, // ElementC const* ptr_C + { + {{template.cute_int(kernel.stride(Bias, -2, 1), "stride_bias0")}}, + {{template.cute_int(kernel.stride(Bias, -1, 1), "stride_bias1")}}, + {{template.cute_int(kernel.batch_stride(Bias), "batch_stride_bias")}} + }, // StrideC dC + {{template.cutlass_type_cast(Y, kernel.ptr(Y))}}, // ElementD const* ptr_D + { + {{template.cute_int(kernel.stride(Y, -2), "stride_y0")}}, + {{template.cute_int(kernel.stride(Y, -1), "stride_y1")}}, + {{template.cute_int(kernel.batch_stride(Y), "batch_stride_y")}} + }, // StrideD dD + }, // EpilogueArguments epilogue +""" + +# Jinja template for GEMM Kernel, used by the CUTLASS2xGemmTemplate class below. +GEMM_TEMPLATE_CUTLASS_2X = r""" +{{template.header().getvalue()}} +{{template.globals().getvalue()}} +{{instance_definition}} +// When workspace_size is not a nullptr, populates requested workspace_size and returns. +// Otherwise, computes the Gemm kernel using the given workspace ptr. +extern "C" { +PT_EXPORT {{kernel_call_signature}} { + try { + int B = {{kernel.size(Y, 0, -3, default_value=1)}}; + using ElementComputeEpilogue = {{instance_type}}::ElementAccumulator; + using coord_t = cutlass::gemm::GemmCoord::Index; + static cutlass::KernelHardwareInfo hw_info; + if (hw_info.sm_count == 0) { + hw_info.sm_count = cutlass::KernelHardwareInfo::query_device_multiprocessor_count(0); + CUTLASS_TRACE_HOST("Query result for SM count per device: " << hw_info.sm_count); + } + {{instance_type}}::Arguments arguments; + {{template.render_gemm_arguments(instance_type, argument_template, epilogue_template, should_swap_xw, + X, W, Bias, Meta, Y, alpha, beta, kernel, epilogue_args)}} + {{instance_type}} gemm_op; + if (workspace_size) { + *workspace_size = gemm_op.get_workspace_size(arguments); + return 0; + } + + // check for null pointers after workspace size, since querying workspace size doesn't require valid data pointers +#ifndef CUTLASS_BACKEND_DISABLE_CHECKS + { + auto status = gemm_op.can_implement(arguments); + CUTLASS_CHECK(status); + } +#endif +#ifdef CUTLASS_DEBUG_TRACE_LEVEL +#if CUTLASS_DEBUG_TRACE_LEVEL == 1 + { + // Print the maximum number of active blocks per SM for the kernel if CUTLASS_DEBUG_TRACE_LEVEL == 1 + // we don't need a print statement, it's happening inside the function. + gemm_op.maximum_active_blocks(); + } +#endif +#endif + + { + auto status = gemm_op.initialize(arguments, workspace, stream); + CUTLASS_CHECK(status); + } + { + auto status = gemm_op(stream); + CUTLASS_CHECK(status); + } + } + catch (std::exception& e) { + std::cerr << "Runtime error: " << e.what() << std::endl; + return -1; + } + catch (...) { + return -1; + } + return 0; +} +} +""" + +# Jinja template for Cutlass 2.x GEMM Kernel arguments, used by the CUTLASS2xGemmTemplate class below. +GEMM_ARGS_CUTLASS_2X = r""" + int64_t batch_stride_x = {{kernel.stride(X, -3)}}; + int64_t row_stride_x = {{kernel.row_or_column_stride(X)}}; + int64_t batch_stride_w = {{kernel.stride(W, -3)}}; + int64_t row_stride_w = {{kernel.row_or_column_stride(W)}}; + int64_t batch_stride_bias = {{kernel.stride(Bias, -3)}}; + int64_t row_stride_bias = {{kernel.row_or_column_stride(Bias)}}; + int64_t batch_stride_y = {{kernel.stride(Y, -3)}}; + int64_t row_stride_y = {{kernel.row_or_column_stride(Y)}}; + // Initialize GemmUniversalInstance arguments. + arguments = { + {{template.gemm_mode()}}, // GemmUniversalMode mode + { + static_cast(M), + static_cast(N), + static_cast(K) + }, // GemmCoord problem_size + {{split_k if split_k > 1 else 'B'}}, // int batch_count + {ElementComputeEpilogue({{alpha}}), ElementComputeEpilogue({{beta}})}, // typename EpilogueOutputOp::Params epilogue + {{template.cutlass_type_cast(X, kernel.ptr(X))}}, // void const * ptr_A + {{template.cutlass_type_cast(W, kernel.ptr(W))}}, // void const * ptr_B + {{template.cutlass_type_cast(Bias, kernel.ptr(Bias))}}, // void const * ptr_C + {{template.cutlass_type_cast(Y, kernel.ptr(Y))}}, // void * ptr_D + batch_stride_x, // int64_t batch_stride_A + batch_stride_w, // int64_t batch_stride_B + batch_stride_bias, // int64_t batch_stride_C + batch_stride_y, // int64_t batch_stride_D + row_stride_x, // typename LayoutA::Stride::LongIndex lda + row_stride_w, // typename LayoutB::Stride::LongIndex ldb + row_stride_bias, // typename LayoutC::Stride::LongIndex ldc + row_stride_y, // typename LayoutC::Stride::LongIndex ldd + }; +""" + +GEMM_ARGS_SPARSE_CUTLASS_2X = r""" + using TensorRefA = cutlass::TensorRef<{{instance_type}}::ElementA, + {{instance_type}}::LayoutA>; + using TensorRefB = cutlass::TensorRef<{{instance_type}}::ElementB, + {{instance_type}}::LayoutB>; + using TensorRefC = cutlass::TensorRef<{{instance_type}}::ElementC, + {{instance_type}}::LayoutC>; + using TensorRefE = cutlass::TensorRef<{{instance_type}}::ElementE, + {{instance_type}}::LayoutE>; + // Note that "X" and "W" names may be misleading here. Namely, for + // sparse GEMM, the first argument is always sparse, while typically + // weight matrix, implied by name "W" will be sparse in + // applications. Thus, just remember that here: "X" refers to first + // argument, that is sparse, and "W" to second, that is dense. + TensorRefA X_ref({{template.cutlass_type_cast(X, kernel.ptr(X))}}, {{kernel.row_or_column_stride(X)}}); + TensorRefB W_ref({{template.cutlass_type_cast(W, kernel.ptr(W))}}, {{kernel.row_or_column_stride(W)}}); + TensorRefC Y_ref({{template.cutlass_type_cast(Y, kernel.ptr(Y))}}, {{kernel.row_or_column_stride(Y)}}); + TensorRefE Meta_ref({{template.cutlass_sparse_meta_type_cast(Meta, kernel.ptr(Meta))}}, + TensorRefE::Layout::packed({ {{kernel.size(Meta, 0)}}, {{kernel.size(Meta, 1)}} })); + // Initialize GemmSparse arguments. + arguments = { + { + static_cast(M), + static_cast(N), + static_cast(2 * K), + }, // GemmCoord problem_size + X_ref, // TensorRef ref_A + W_ref, // TensorRef ref_B + Y_ref, // TensorRef ref_C + Y_ref, // TensorRef ref_D + Meta_ref, // TensorRef ref_E + {ElementComputeEpilogue({{alpha}}), ElementComputeEpilogue({{beta}})}, // typename EpilogueOutputOp::Params epilogue, + }; +""" + +# Additional includes which are necessary if the standalone test / debug runner is generated as well +GEMM_STANDALONE_RUNNER_ADDITIONAL_INCLUDES = r""" +#ifdef GENERATE_STANDALONE_RUNNER +#include "cutlass/util/distribution.h" +#include "cutlass/util/host_tensor.h" +#include "cutlass/util/packed_stride.hpp" +#include "cutlass/util/tensor_view_io.h" +#include "cutlass/util/reference/device/gemm_complex.h" +#include "cutlass/util/reference/device/tensor_compare.h" +#include "cutlass/util/reference/device/tensor_fill.h" +#include +#endif +""" + +# Jinja template for the standalone runner that may be generated as part of the code. +GEMM_STANDALONE_RUNNER_TEMPLATE = r""" +#ifdef GENERATE_STANDALONE_RUNNER +/// Helper to initialize a block of device data +template +bool initialize_block( + cutlass::DeviceAllocation& block, + uint64_t seed, float max=1.0, float min=-1.0) { + if (block.size()<=0) return false; + Element scope_max(static_cast(max)), scope_min(static_cast(min)); + cutlass::reference::device::BlockFillRandomUniform( + (Element*)block.get(), block.size(), seed, scope_max, scope_min); + + return true; +} + +{% if Meta is defined and Meta is not none %} +template +bool initialize_block_meta( + cutlass::DeviceAllocation& block, + uint64_t seed) { + if (block.size()<=0) return false; + cutlass::reference::device::BlockFillRandomSparseMeta( + (Element*)block.get(), block.size(), seed, {{instance_type}}::kMetaSizeInBits); + return true; +} +{% endif %} + +extern "C" int run_standalone(uint64_t seed, int repetitions) { + std::cout << "Starting GEMM Standalone test run with seed " << seed << std::endl; + size_t workspace_size = 0; + size_t* workspace_size_ptr = &workspace_size; + + int M = {{kernel.get_layout_args()[0]}}; + int N = {{kernel.get_layout_args()[1]}}; + int K = {{kernel.get_layout_args()[2]}}; + int B = {{kernel.get_layout_args()[3]}}; + int lda = {{kernel.get_layout_args()[4]}}; + int ldb = {{kernel.get_layout_args()[5]}}; + int ldc = {{kernel.get_layout_args()[6]}}; + int ldd = {{kernel.get_layout_args()[7]}}; + uint8_t swizzle = {{kernel.runtime_arg_values[0]}}; + + using ElementA = {{kernel.cutlass_dtype(X)}}; + using ElementB = {{kernel.cutlass_dtype(W)}}; + using ElementC = {{kernel.cutlass_dtype(Bias, default_dtype='uint8_t')}}; // may not be void + using ElementD = {{kernel.cutlass_dtype(Y)}}; + {% if Meta is defined and Meta is not none %} + using ElementE = {{kernel.cutlass_dtype(Meta)}}; + {% endif %} + + cutlass::DeviceAllocation X_data({{kernel.max_valid_index(X)+1}}); + initialize_block(X_data, seed++); + cutlass::DeviceAllocation W_data({{kernel.max_valid_index(W)+1}}); + initialize_block(W_data, seed++); + cutlass::DeviceAllocation Bias_data({{kernel.max_valid_index(Bias)+1}}); + initialize_block(Bias_data, seed++); + cutlass::DeviceAllocation Y_data({{kernel.max_valid_index(Y)+1}}); + {% if Meta is defined and Meta is not none %} + cutlass::DeviceAllocation Meta_data({{kernel.max_valid_index(Meta)+1}}); + initialize_block_meta(Meta_data, seed++); + {% endif %} + + cutlass::DeviceAllocation workspace_data; + // Call once with workspace_size_ptr set to get workspace size + + std::cout << "Calling once to get workspace size" << std::endl; + {{test_call_statement}}; + // Allocate workspace if necessary + if (workspace_size > 0) { + workspace_data.reset(workspace_size); + std::cout << "Allocated workspace size of " << workspace_size << " bytes" << std::endl; + } + std::cout << "Calling Kernel as {{test_call_statement}};" << std::endl; + workspace_size_ptr = nullptr; + for (int i=0; i None: + """ + Args: + input_nodes (List[Buffer]): List of input nodes of the GEMM kernel. + layout (Layout): Layout type of the resulting output node. + alpha (float): The scaling factor for the product of the inputs in the GEMM operation. + beta (float): The scaling factor applied to the output matrix. + input_reorder (Optional[List[int]]): Specifies the reordering of the input nodes. If not provided, + no reordering is performed. Defaults to None. + use_fast_accum (Optional[bool]): enable/disable tensor-core fast accumulation (only available in `CUTLASS3xGemmTemplate` and Hopper GPUs) + """ + super().__init__( + str(Placeholder.KERNEL_NAME), input_nodes, layout, input_reorder + ) + self.alpha = alpha + self.beta = beta + self.use_fast_accum = use_fast_accum + if not (2 <= len(input_nodes) <= 5): + raise AssertionError(f"expected 2 to 5 input nodes, got {len(input_nodes)}") + if not self._are_inputs_layout_compatible( + [node.get_layout() for node in input_nodes] + ): + raise AssertionError("input nodes have incompatible layouts") + + self.cache_key: str = create_inputs_key(self.input_nodes) + + @staticmethod + @abstractmethod + def add_cutlass_gemm_choices( + choices: list[ChoiceCaller], + layout: ir.Layout, + input_nodes: list[Buffer], + alpha: float | int = 1, + beta: float | int = 0, + input_reorder: list[int] | None = None, + use_fast_accum: bool | None = None, + **extra_kwargs, + ) -> None: + raise NotImplementedError + + @staticmethod + @abstractmethod + def _get_supported_ops() -> "list[cutlass_library.gemm_operation.GemmOperation]": # type: ignore[name-defined] # noqa: F821 + raise NotImplementedError + + @staticmethod + @abstractmethod + def _has_tma_epilogue(self) -> bool: + raise NotImplementedError + + @abstractmethod + def _get_template(self) -> str: + raise NotImplementedError + + @abstractmethod + def _get_template_args( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> tuple[str, str | None]: + raise NotImplementedError + + @abstractmethod + def _are_inputs_layout_compatible(self, layouts: list[Layout]) -> bool: + raise NotImplementedError + + @abstractmethod + def _shape_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + raise NotImplementedError + + @abstractmethod + def _alignment_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + raise NotImplementedError + + @abstractmethod + def _set_bias_layout_and_alignment( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + raise NotImplementedError + + @abstractmethod + def _define_gemm_instance( + self, + op: GemmOperation, + evt_name: str | None = None, + ) -> tuple[str, str]: + raise NotImplementedError + + @abstractmethod + def _get_extra_inputs_and_names( + self, + op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821 + ) -> tuple[Buffer | None, list[Buffer | None], list[str]]: + raise NotImplementedError + + @abstractmethod + def _update_arg_names_for_test_call_statement( + self, + arg_names: list[str], + input_nodes: list[Buffer], + ) -> list[str]: + raise NotImplementedError + + def _add_cutlass_gemm_choices( + self, + choices: list[ChoiceCaller], + layout: ir.Layout, + input_nodes: list[Buffer], + alpha: float | int = 1, + beta: float | int = 0, + input_reorder: list[int] | None = None, + **extra_kwargs, + ) -> None: + """ + Adds Cutlass GEMM configurations choices to the auto-tuning list. + + This function mutates the passed list of choices by appending the choices for Cutlass GEMM configs to it. + + Args: + choices (list): The list to which choices are appended. + layout (ir.Layout): The layout configuration. + input_nodes (list): The list of input nodes. + alpha (float,int): Scaling factor, defaults to 1. + beta (float,int): Offset, defaults to 0. + input_reorder (list, optional): Order of the inputs, defaults to None. + **extra_kwargs: Additional keyword arguments. + + """ + + ops = self.gen_ops() + + # pre-computation + layout_repr: str = str(layout) + input_tensor_meta: TensorMeta | list[TensorMeta] = TensorMeta.from_irnodes( + self.input_nodes + ) + # When input_reorder is set (e.g. [2, 0, 1] for addmm), the kernel + # function signature is reordered (e.g. from [X, W, Bias] to + # [Bias, X, W]). input_tensor_meta must follow the same order + # because subprocess benchmarking creates tensors from this metadata + # and passes them positionally to the compiled kernel. Without this + # reorder the kernel receives mismatched pointers/strides, causing + # out-of-bounds GPU memory access for large shapes. + if self.input_reorder is not None and isinstance(input_tensor_meta, list): + input_tensor_meta = [input_tensor_meta[idx] for idx in self.input_reorder] + output_tensor_meta: TensorMeta | list[TensorMeta] = TensorMeta.from_irnodes( + self.output_node + ) + + with dynamo_timed("CUTLASSGemmTemplate.maybe_append_choice"): + device_config = self._device_cutlass_config + for name, op in ops: + for swizzle in device_config.cutlass_max_profiling_swizzle_options: + description = f"{name} swizzle={swizzle}" + self.maybe_append_choice( + choices, + op=op, + name=name, + description=description, + input_key=self.cache_key, + layout_repr=layout_repr, + input_tensor_meta=input_tensor_meta, + output_tensor_meta=output_tensor_meta, + swizzle=swizzle, + ) + + if len(ops) == 0: + log.info( + "No suitable Cutlass GEMM configs found, fallbacks used " + "( len(ops)=%d, output_layout=%s, input_layouts=%s, input_strides=%s )", + len(ops), + layout, + [node.get_layout() for node in input_nodes], + [node.get_stride() for node in input_nodes], + ) + log.debug( + "Added %d Cutlass gemm configs.", + len(ops), + ) + + def header(self) -> IndentedBuffer: + """ + Returns a buffer containing CUDA C++ code for the header section of the CUTLASS GEMM template. + This section primarily includes the necessary header files. + + Returns: + IndentedBuffer: An instance of IndentedBuffer that contains the generated CUDA C++ header code. + """ + res = super().header() + res.splice( + """ + #include "cutlass/gemm/gemm.h" + #include "cutlass/gemm/device/gemm_universal.h" + #include "cutlass/gemm/device/gemm_universal_adapter.h" + #include "cutlass/gemm/kernel/gemm_universal.hpp" + #include "cutlass/gemm/collective/collective_builder.hpp" + #include "cutlass/epilogue/collective/collective_builder.hpp" + #include "cutlass/epilogue/collective/default_epilogue.hpp" + #include "cutlass/epilogue/thread/linear_combination.h" + #include "cutlass/epilogue/thread/activation.h" + #include "cutlass/gemm/dispatch_policy.hpp" + #include "cutlass/gemm/kernel/tile_scheduler.hpp" + #include "cutlass/tensor_ref.h" + #include "cutlass/util/distribution.h" + #include "cutlass/util/packed_stride.hpp" + #include "cutlass/util/tensor_view_io.h" + """ + ) + if self.device_type != "xpu": + # XPU SYCL-TLA does not support sparse gemm yet + res.splice( + """ + #include "cutlass/gemm/device/gemm_sparse.h" + """ + ) + if inductor_cutlass_config.generate_test_runner and not is_dynamic( + *self.input_nodes, self.output_node + ): + res.splice(GEMM_STANDALONE_RUNNER_ADDITIONAL_INCLUDES) + return res + + @staticmethod + def cutlass_layout(torch_layout: ir.Layout) -> "cutlass_lib.LayoutType | None": # type: ignore[name-defined] # noqa: F821 + """ + Converts an ir.Layout instance into the corresponding cutlass_library.LayoutType enum value + (RowMajor, ColumnMajor, or None if no matching value is found ). + + Args: + torch_layout (ir.Layout): The layout that needs to be looked up. + + Returns: + cutlass_lib.LayoutType: The converted layout corresponding to the `torch_layout` or None if no matching + value is found. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.library as cutlass_lib + + if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1): + return cutlass_lib.LayoutType.RowMajor + elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-2], 1): + return cutlass_lib.LayoutType.ColumnMajor + else: + return None + + @staticmethod + def flip_cutlass_layout( + cutlass_layout: "cutlass_lib.LayoutType", # type: ignore[name-defined] # noqa: F821 + ) -> "cutlass_lib.LayoutType": # type: ignore[name-defined] # noqa: F821 + """Helper method: Flips a given cutlass layout (cutlass_lib.LayoutType) from RowMajor + to ColumnMajor or vice versa""" + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.library as cutlass_lib + + if cutlass_layout == cutlass_lib.LayoutType.RowMajor: + return cutlass_lib.LayoutType.ColumnMajor + else: + return cutlass_lib.LayoutType.RowMajor + + @staticmethod + @functools.lru_cache(32) + def layout_match( + torch_layout: ir.Layout, + cutlass_layout: "cutlass_lib.LayoutType", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + """Helper Method: Determines whether a given torch layout matches a given Cutlass layout""" + return CUTLASSGemmTemplate.cutlass_layout(torch_layout) == cutlass_layout + + @staticmethod + def set_layout(tensor_desc: "TensorDescription", torch_layout: ir.Layout) -> None: # type: ignore[name-defined] # noqa: F821 + """ + Helper method: Sets the layout of a given tensor description to match the given torch layout + """ + if CUTLASSGemmTemplate.layout_match(torch_layout, tensor_desc.layout): + return + tensor_desc.layout = CUTLASSGemmTemplate.cutlass_layout(torch_layout) + + @staticmethod + def set_alignment(torch_layout, op_element) -> bool: + """ + Helper method to update the alignment of a given CUTLASS GEMM op operand's element. + + This method modifies the alignment of the given Cutlass GEMM op operand's element to match the + layout of the corresponding ir.Buffer node. + + Args: + torch_layout: The layout of the corresponding ir.Buffer node. + op_element: The Cutlass GEMM op operand's element whose alignment is to be updated. + + Returns: + bool: True if the alignment was successfully updated, False otherwise. + """ + alignment = cutlass_utils.get_max_alignment(torch_layout) + if torch.cuda.is_available(): + cuda_arch = cuda_env.get_cuda_arch() + cuda_arch = cutlass_utils._normalize_cuda_arch(cuda_arch) + if cuda_arch and int(cuda_arch) >= 90 and alignment < op_element.alignment: + return False + + op_element.alignment = alignment + return True + + @staticmethod + def should_swap_XW( + bias: IRNode, + ) -> bool: + """ + Helper method to determine whether we should do an explicit transpose by switching the order of the + matmul operands. This might be necessary when we can't otherwise arrive at the right memory + layout for the given Bias operand. + + Note: This method is a workaround for CUDA Errors that seemingly non-deterministically + occurred in practice in some CUTLASS GEMM Kernels with Linear epilogues that have a bias term. + it might make sense to check on newer Cutlass releases whether it makes sense to keep + returning True in certain cases or whether it becomes unnecessary. + """ + # If bias is row major, swap all M and N dimensions + if ( + bias is not None + and len(bias.get_stride()) >= 2 + and bias.get_stride()[-1] in (0, 1) + ): + log.debug("GEMM Layout swapped X and W -> explicit transpose") + return True + return False + + @staticmethod + def swap_XW( + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> "cutlass_library.gemm_op.GemmOperation": # type: ignore[name-defined] # noqa: F821 + """ + Swap operands X and W (aka operands A and B) of the GEMM operation. This + requires transposing the operands, which is done by swapping the strides. + Note that we don't change the apparent external layout, just the operand layout. + this is intentional. + """ + new_op = copy.deepcopy(op) + new_op.A.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.A.layout) + new_op.B.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.B.layout) + new_op.A, new_op.B = new_op.B, new_op.A + new_op.C.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.C.layout) + new_op.D.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.D.layout) + return new_op + + def fix_op_layout( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + X: Buffer, + W: Buffer, + Bias: Buffer | None, + Y: Buffer | ReinterpretView, + ) -> "cutlass_library.gemm_op.GemmOperation": # type: ignore[name-defined] # noqa: F821 + # This is a workaround to deal with cases where the input layouts have changed + # between autotuning and rendering. This happens if the inputs layout + # are FlexibleLayout instances. In this case, we need to update the + # op's input layouts. It is a hack, because now the op + # we benchmarked is not the same as the op we render, + # but there is no simple way to fix this in the autotuner, since that would + # potentially disable other optimizations. + a_layout = X.get_layout() + b_layout = W.get_layout() + c_layout = Bias.get_layout() if Bias is not None else None + + d_layout = copy.deepcopy(Y.get_layout()) + match_list = [ + CUTLASSGemmTemplate.layout_match(buf.get_layout(), op_layout) + for buf, op_layout in zip( + (X, W, Bias, Y), + (op.A.layout, op.B.layout, op.C.layout, op.D.layout), + ) + if buf is not None + ] + all_match = all(match_list) + if all_match: + return op + log.warning( + f"Cutlass GEMM Layout change: Input and/or output layouts have changed between autotuning/retuning and call to render on {self}. Applying workaround. This can lead to suboptimal performance. Match List: {match_list}" # noqa: G004 + ) + new_op = copy.deepcopy(op) + + if a_layout is not None: + new_op.A.layout = CUTLASSGemmTemplate.cutlass_layout(a_layout) + if b_layout is not None: + new_op.B.layout = CUTLASSGemmTemplate.cutlass_layout(b_layout) + if c_layout is not None: + new_op.C.layout = CUTLASSGemmTemplate.cutlass_layout(c_layout) + new_op.C.element = cutlass_utils.torch_dtype_to_cutlass_type(c_layout.dtype) + if d_layout is not None: + new_op.D.layout = CUTLASSGemmTemplate.cutlass_layout(d_layout) + return new_op + + def _dtype_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + """ + Checking dtypes of A, B, acc, D here. + + Empirically speaking, CUTLASS2x ops have same dtype for C and D. + """ + X = self.input_nodes[0] + W = self.input_nodes[1] + + accumulator_torch_dtype = cutlass_utils.get_accumulator_dtype( + [X.get_dtype(), W.get_dtype()], + ) + if not ( + cutlass_utils.dtype_match(X.get_dtype(), op.A.element) + and cutlass_utils.dtype_match(W.get_dtype(), op.B.element) + and cutlass_utils.dtype_match( + self.output_node.get_layout().dtype, op.D.element + ) + and cutlass_utils.dtype_match( + accumulator_torch_dtype, op.accumulator_type() + ) + ): + return False + + return True + + @classmethod + def global_filter_ops( + cls, + ops: list["cutlass_library.gemm_op.GemmOperation"], # type: ignore[name-defined] # noqa: F821 + ) -> list["cutlass_library.gemm_op.GemmOperation"]: # type: ignore[name-defined] # noqa: F821 + """ + Filter ops without using information about the torch op, input nodes and output node. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.library as cutlass_lib # type: ignore[import] + + # Skip simt kernels + ops = [ + op + for op in ops + if op.tile_description.math_instruction.opcode_class + != cutlass_lib.OpcodeClass.Simt + ] + + # only keep the set of row x column ops + # for other layout, we modify in place in filter_op, after deepcopy + ops = [ + op + for op in ops + if op.A.layout.name == "RowMajor" and op.B.layout.name == "ColumnMajor" + ] + + # filter by supported accumulator types + ops = [ + op + for op in ops + if any( + dtype_match(torch_dtype, op.accumulator_type()) + for torch_dtype in ACCUMULATOR_DTYPES + ) + ] + + # check if dtypes of A and B are supported + ops = [ + op + for op in ops + if any(dtype_match(torch_dtype, op.A.element) for torch_dtype in XW_DTYPES) + and any(dtype_match(torch_dtype, op.B.element) for torch_dtype in XW_DTYPES) + ] + + return ops + + def filter_op( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> "cutlass_library.gemm_op.GemmOperation": # type: ignore[name-defined] # noqa: F821 + """ + Helper method: + + Determines whether a given Cutlass GEMM op definition is suitable for the current + input / output of the operation that this template is supposed to implement. + + Takes memory layout, dtype and support for EVT operations into account, + and filters potentially problematic ops. + + Returns None if the op is not suitable, otherwise returns the op to be used, which might + have been mutated. + """ + + if op.gemm_kind not in self._get_supported_ops(): + return None + + X = self.input_nodes[0] + W = self.input_nodes[1] + + # Filter ops according to the shape match. + if not self._shape_match(op): + return None + + # Filter ops by dtypes. + if not self._dtype_match(op): + return None + + # Filter ops by alignment. + if not self._alignment_match(op): + log.debug( + "Skipping due to alignment mismatch. op: %s", op.configuration_name() + ) + return None + + # only use stream k for static shape + if op.tile_scheduler.name == "StreamK": + static_shape = PythonWrapperCodegen.statically_known_list_of_ints_or_none( + tuple(X.get_size()) + tuple(W.get_size()) + ) + if not static_shape: + return None + + # Update op. + op = copy.deepcopy(op) + + # set layouts for X and W + self.set_layout(op.A, X.get_layout()) + self.set_layout(op.B, W.get_layout()) + + # Set output layout. + op.D.layout = CUTLASSGemmTemplate.cutlass_layout(self.output_node.get_layout()) + + # Filter ops by alignments and set alignments. + status = ( + self.set_alignment(X.get_layout(), op.A) + and self.set_alignment(W.get_layout(), op.B) + and self.set_alignment(self.output_node.get_layout(), op.D) + ) + if not status: + log.debug( + "Skipping due to alignment setting failure. op: %s", + op.configuration_name(), + ) + return None + + if inductor_cutlass_config.cutlass_tma_only and not self._has_tma_epilogue(op): + return None + + # Set epilogue. + # TODO: update epilogue functor according to epilogues. + op.element_epilogue = op.accumulator_type() + + if ( + self.use_fast_accum is not None + and int(cutlass_utils._normalize_cuda_arch(cuda_env.get_cuda_arch())) == 90 + ): + is_op_fast_accum = "fastaccum" in op.configuration_name() + if self.use_fast_accum ^ is_op_fast_accum: + return None + + # Set bias layout and alignment. + status = self._set_bias_layout_and_alignment(op) + if not status: + log.debug( + "Skipping due to bias layout and alignment setting failure. op: %s", + op.configuration_name(), + ) + return None + + # Apply regex filters at the end when configuration name doesn't change anymore + if inductor_cutlass_config.cutlass_op_allowlist_regex: + if not re.search( + inductor_cutlass_config.cutlass_op_allowlist_regex, + op.configuration_name(), + ): + return None + if inductor_cutlass_config.cutlass_op_denylist_regex is not None: + if re.search( + inductor_cutlass_config.cutlass_op_denylist_regex, + op.configuration_name(), + ): + return None + + # `_procedural_name` is decorated with @functools.cached_property in cutlass, and its value is + # cached based on the key `self`. After we modify some attributes of + # `self` (e.g., layout or alignment), the `self` itself doesn’t change, so the + # cached value remains stale. We therefore need to clear the cached value so that + # `_procedural_name` can be recomputed with the updated attributes. + del op._procedural_name + return op + + def gen_ops(self) -> "list[tuple[str, cutlass_gemm_op.GemmOperation]]": # type: ignore[name-defined] # noqa: F821 + """ + Creates a list of Cutlass GemmOperation instances that match the operation this template is designed to represent. + The matching is carried out with respect to the input and output specifications of the operation. + + No function arguments. + + Returns: + List[tuple[str, cutlass_gemm_op.GemmOperation]]: A list of (cutlass_name, GemmOperation) + tuples that are compatible with the operation requirements of this template. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.gemm_operation as cutlass_gemm_op + + if self.cache_key in self.filtered_ops_cache: + log.debug("Using cached ops for %s", self.cache_key) + return self.filtered_ops_cache[self.cache_key] + + counters["inductor"]["cutlass_filtered_ops_cache_miss"] += 1 + + with dynamo_timed("CUTLASSGemmTemplate.maybe_fetch_ops"): + maybe_ops = maybe_fetch_ops(self.device_type) + if maybe_ops is None: + log.debug("Cannot fetch ops from cache, generating ops from scratch") + full_ops = cutlass_utils.gen_ops(self.device_type) + ops = pytree.tree_flatten(full_ops)[0] + else: + log.debug("Using cached ops from cache") + ops = maybe_ops + + ops = self.global_filter_ops(ops) + + res: dict[str, cutlass_gemm_op.GemmOperation] = {} + start_time = time.time() + for op in ops: + # if changed, need to also change CUTLASS_OPERATION_KIND + if not isinstance(op, cutlass_gemm_op.GemmOperation): + raise AssertionError(f"expected GemmOperation, got {type(op).__name__}") + filter_res = self.filter_op(op) + if ( + filter_res is not None + and res.get(filter_res.configuration_name()) is None + ): + res[filter_res.configuration_name()] = filter_res + log.info( + "Got cutlass configs: total number of ops: %d. Filtering took %.2f seconds", + len(res), + time.time() - start_time, + ) + sorted_res = sorted(res.items()) + device_config = self._device_cutlass_config + ret_res = sorted_res[: device_config.cutlass_max_profiling_configs] + if len(self.filtered_ops_cache) < 50: + self.filtered_ops_cache[self.cache_key] = ret_res + else: + log.debug("Not caching ops since filtered_ops_cache has reached size 50.") + return ret_res + + def gemm_mode(self) -> str: + """ + Returns a Cutlass GEMM mode string for the current operation, dependent on whether this op implements + a batched GEMM or a simple GEMM without batch dimension. + + Returns: + str: A string indicating the Cutlass GEMM mode. If the output node has more than two dimensions, + "cutlass::gemm::GemmUniversalMode::kBatched" is returned, otherwise + "cutlass::gemm::GemmUniversalMode::kGemm" is returned. + """ + sizes = self.output_node.get_size() + if len(sizes) > 2: + return "cutlass::gemm::GemmUniversalMode::kBatched" + else: + return "cutlass::gemm::GemmUniversalMode::kGemm" + + def _dynamic_cluster_block(self, op: "cutlass_gemm_op.GemmOperation") -> str: # type: ignore[name-defined] # noqa: F821 + """ + Temporary workaround for CUTLASS GEMMs that encode cluster shape as runtime values. + + For dynamic-cluster kernels, CUTLASS expects `KernelHardwareInfo.cluster_shape` and + `KernelHardwareInfo.cluster_shape_fallback` to be populated with valid runtime values. + Today we provide a single global preferred/fallback pair (configurable via env), + which is sufficient for correctness but is not performance-optimal. + + Note: This is intentionally minimal because this code path is transitional. Cluster-shape + selection should ultimately be handled in the CuTe/DSL implementation rather than + investing heavily in the legacy CUTLASS template pipeline. + """ + shape = getattr(getattr(op, "tile_description", None), "cluster_shape", None) + if not shape or len(shape) < 2 or (shape[0] > 0 and shape[1] > 0): + return "" + + preferred = inductor_cutlass_config.cutlass_dynamic_cluster_shape + fallback = inductor_cutlass_config.cutlass_dynamic_cluster_fallback + + cluster_k = shape[2] if len(shape) > 2 and shape[2] > 0 else preferred[2] + preferred = (preferred[0], preferred[1], cluster_k) + fallback_k = fallback[2] if len(fallback) > 2 and fallback[2] > 0 else cluster_k + fallback = (fallback[0], fallback[1], fallback_k) + + return ( + f" hw_info.cluster_shape = {{{preferred[0]}, {preferred[1]}, {preferred[2]}}};\n" + f" hw_info.cluster_shape_fallback = {{{fallback[0]}, {fallback[1]}, {fallback[2]}}};" + ) + + def render( # type: ignore[override] + self, + kernel: CUTLASSTemplateKernel, + op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821 + template_buffer_node: CUTLASSTemplateBuffer | None = None, + epilogue_nodes: list[BaseSchedulerNode] | None = None, + **kwargs, + ) -> str: + """ + The primary entry point for the code rendering process used in this template. + Renders the Cutlass based CUDA/XPU C++ code for the GEMM Kernel that this template is designed to implement, + including potentially fused epilogues. + + Args: + kernel (CUTLASSTemplateKernel): The kernel to be rendered. + op (cutlass_gemm_op.GemmOperation, optional): A GEMM operation that is required to be compatible with the + input and output definitions as well as a possible epilogue. Defaults to None. + **kwargs: Additional keyword arguments. Currently unused. + + Returns: + str: Cutlass based CUDA/XPU C++ code fragment as a string, to be used by the current + CUTLASSTemplateKernel or autotuning code. + + Note: + All inputs and their corresponding buffer addresses and names take precedence over previously + passed inputs to the template at construction time. However, they should be layout compatible. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.gemm_operation as cutlass_gemm_op + import cutlass_library.library as cutlass_lib + + if not isinstance(op, cutlass_gemm_op.GemmOperation): + raise AssertionError( + "op argument is required and has to be an instance of GemmOperation" + ) + + if epilogue_nodes: + if self.device_type == "cuda" and not self._has_tma_epilogue(op): + raise NotImplementedError( + "Non-TMA epilogue visitor tree is not supported in NV-Cutlass." + ) + + if not (len(self.input_nodes) >= 2 and self.output_node is not None): + raise AssertionError( + "expected at least 2 input nodes and a non-None output node" + ) + X, W = self.input_nodes[0], self.input_nodes[1] + for input_node in self.input_nodes: + if not isinstance(X.layout, FixedLayout): + input_node.freeze_layout() + + Y = self.output_node + if template_buffer_node is not None: + Y = template_buffer_node + + Bias, extra_inputs, extra_names = self._get_extra_inputs_and_names(op) + + # Define Kernel call signature + # Important: This step also populates Kernel name to node mapping data structures, + # which are required further below ( for example by the template renderer ) + inputs = [X, W, Bias, *extra_inputs] + names = ["X", "W", "Bias", *extra_names] + ["Y"] + names_str = ",".join(names) + if self.input_reorder is not None: + input_reorder = self.input_reorder + else: + input_reorder = None + + # The layouts might have changed between autotuning and this call if they were FlexibleLayout + # we need to adapt, which might lead to suboptimal performance. + op = self.fix_op_layout(op, X, W, Bias, Y) + + # to make op mutable without affecting others + op = copy.deepcopy(op) + is_scaled_mm = len(self.input_nodes) in (4, 5) + if Bias is not None and not is_scaled_mm: + if Bias.get_dtype() != X.get_dtype(): + raise AssertionError( + f"expected Bias dtype {X.get_dtype()}, got {Bias.get_dtype()}" + ) + # This might have been set to void during filtering, when the assumption was still that there's no C + # operand + op.C.element = op.A.element + + if op.C.element != op.D.element: + raise AssertionError( + f"Expect C and D to have the same dtype, found {op.C.element} and {op.D.element}" + ) + + argument_template, epilogue_template = self._get_template_args(op) + should_swap_xw: bool = False + if Bias is not None and self._has_tma_epilogue(op): + if ( + op.epilogue_schedule + != cutlass_lib.EpilogueScheduleType.EpilogueTransposed + and self.should_swap_XW(Bias) + ): + # TMA epilogue requires bias vector in column major to get best perf. + op = self.swap_XW(op) + should_swap_xw = True + + name_to_buffer = {node.get_name(): node for node in self.input_nodes} + # handle the fake output buffer during lowering + name_to_buffer[Y.get_name()] = Y # type: ignore[assignment] + + if epilogue_nodes or is_scaled_mm: + if epilogue_nodes: + ( + input_names, + output_names, + var_name_to_buffer_name, + evt_py_code, + ) = CutlassEVTCodegen.ir_to_evt_python_code( + Y.get_name(), epilogue_nodes, V.kernel.removed_buffers + ) + + # TODO: mlazos remove this by returning buffer metadata from + # ir_to_evt_python code + for name, buf in ( + V.graph.name_to_buffer | V.graph.graph_inputs + ).items(): + if name not in name_to_buffer: + name_to_buffer[name] = buf # type: ignore[assignment] + + D_output_name = var_name_to_buffer_name["D"] + D_output_buffer = name_to_buffer[D_output_name] + Y = D_output_buffer # type: ignore[assignment] + # Interestingly, I don't think the rest of the layout matters here since we + # use the properties of the Y buffer to fill in D's properties in the epilogue + # args. This is needed though because it defines types expected in the epilogue args. + op.D.element = cutlass_utils.torch_dtype_to_cutlass_type( + D_output_buffer.get_dtype() + ) + + # When the D output buffer has a compatible reshape of the template + # output (e.g., [16, 512, 3072] vs [8192, 3072]), use the template's + # layout for EVT since CUTLASS operates on the 2D GEMM output shape. + if ( + template_buffer_node is not None + and D_output_buffer.get_size() != template_buffer_node.get_size() + ): + name_to_buffer[D_output_name] = template_buffer_node + + # Apply the same normalization to external read inputs. EVT + # propagates shapes against the 2D (M, N) accumulator, so a + # higher-rank read with the same number of elements (e.g. a bias + # whose shape is a compatible reshape of the GEMM output) must be + # viewed as the 2D template shape. This is only valid for + # contiguous reads, where the row-major flatten is + # memory-equivalent and thus numerically identical. + if template_buffer_node is not None: + template_size = list(template_buffer_node.get_size()) + for name in input_names: + buf = name_to_buffer[name] + buf_layout = buf.get_layout() + if ( + list(buf.get_size()) != template_size + and buf_layout.is_contiguous() + and V.graph.sizevars.statically_known_equals( + sympy_product(buf.get_size()), + sympy_product(template_size), + ) + ): + new_layout = FixedLayout( + buf_layout.device, + buf_layout.dtype, + template_size, + FlexibleLayout.contiguous_strides(template_size), + ) + name_to_buffer[name] = ReinterpretView( # type: ignore[assignment] # pyrefly: ignore[unsupported-operation] + data=buf, layout=new_layout + ) + + if not output_names: + raise AssertionError("There should be at least one write") + + epilogue_inputs = [name_to_buffer[name] for name in input_names] + # Use D_output_buffer directly for the D output entry in outputs, + # not name_to_buffer[D_output_name] which may have been replaced + # with template_buffer_node for EVT layout purposes. + outputs = [ + D_output_buffer if name == D_output_name else name_to_buffer[name] + for name in output_names + ] + else: # Scaled MM, we read the two scale matrices (and optional bias) and write a single output + bias = None if len(self.input_nodes) < 5 else self.input_nodes[4] + bias_name = bias.get_name() if bias else None + + ( + evt_read_names, + var_name_to_buffer_name, + evt_py_code, + ) = scaled_mm_evt( + self.input_nodes[2].get_name(), # scale_A + self.input_nodes[3].get_name(), # scale_B + bias_name, + Y.get_name(), + ) + + input_names = list(evt_read_names) + output_names = [] # We only need Y + epilogue_inputs = [self.input_nodes[2], self.input_nodes[3]] + if bias: + epilogue_inputs.append(bias) + outputs = [] + + acc_dtype = cutlass_utils.get_accumulator_dtype( + [X.get_dtype(), W.get_dtype()] + ) + if not acc_dtype: + raise AssertionError("Could not determine accumulator dtype") + + evt_name, evt_args, evt_code, evt_arg_renames = self._render_evt( + op, + evt_py_code, + var_name_to_buffer_name, + name_to_buffer, + Y.get_dtype(), + acc_dtype, + ) + + inputs = [ + X, + W, + Bias, + *epilogue_inputs, # type: ignore[list-item] + Y, + *extra_inputs, + ] + # Extend input_reorder to cover epilogue inputs, Y, and extra_inputs + # at their natural positions (identity mapping for new entries) + if input_reorder is not None: + base_len = len(input_reorder) + if not (base_len <= len(inputs)): + raise AssertionError( + "input_reorder must be a prefix mapping for the current input list" + ) + num_new = len(inputs) - base_len + if num_new > 0: + input_reorder = input_reorder + list( + range(base_len, base_len + num_new) + ) + input_names = [evt_arg_renames.get(name) for name in input_names] + output_names = [evt_arg_renames.get(name) for name in output_names] + + names_str = ",".join( + ["X", "W", "Bias", *input_names, "Y", *output_names, *extra_names] + ) + else: + evt_name = None + outputs = [Y] + evt_args = f"{{ElementComputeEpilogue({self.alpha}), ElementComputeEpilogue({self.beta})}}" + evt_code = "" + + kernel_call_signature = kernel.def_kernel( + inputs=inputs, # type: ignore[arg-type] + outputs=outputs, # type: ignore[arg-type] + names_str=names_str, + input_reorder=input_reorder, + ) + + test_call_statement = self.test_call_statement(kernel, inputs, names_str) + + instance_definition, instance_type = self._define_gemm_instance(op, evt_name) + dynamic_cluster = self._dynamic_cluster_block(op) + + options = { + "alpha": self.alpha, + "beta": self.beta, + "X": X, + "W": W, + "Y": Y, + "kernel_call_signature": kernel_call_signature, + "Bias": Bias, + "epilogue_template": epilogue_template, + "argument_template": argument_template, + "should_swap_xw": should_swap_xw, + "template": self, + "kernel": kernel, + "instance_definition": instance_definition, + "instance_type": instance_type, + "input_reorder": self.input_reorder, + "epilogue_args": evt_args, + "test_call_statement": test_call_statement, + "op_conf_name": op.configuration_name(), + "epilogue_visitor_tree": evt_code, + "dynamic_cluster": dynamic_cluster, + } + options.update(dict(zip(extra_names, extra_inputs))) + res = self._template_from_string(self._get_template()).render(**options) + if inductor_cutlass_config.generate_test_runner and not is_dynamic( + X, W, Y, Bias + ): + test_runner_code = self._template_from_string( + GEMM_STANDALONE_RUNNER_TEMPLATE + ).render(**options) + res += "\n\n" + test_runner_code + + # splice to remove trailing spaces in each line + buf = IndentedBuffer() + buf.splice(res) + return buf.getvalue() + + def test_call_statement( + self, + kernel, + input_nodes, + names_str: str = "", + ) -> str: + """ + Helper method to render the Cutlass CUDA/XPU C++ code required for calling the GEMM operation in the standalone + test runner that might also be generated along with the rest of the code, if the corresponding config is + enabled. + + Returns a C++ statement that calls the GEMM operation with the correct arguments. + """ + _, __, arg_types = kernel.args.cpp_argdefs(cutlass_utils.DTYPE_TO_CUTLASS_TYPE) + arg_names = [name.strip() for name in names_str.strip().split(",")] + arg_names = self._update_arg_names_for_test_call_statement( + arg_names, input_nodes + ) + arguments = [ + f"(({arg_type}){arg_name}_data.get())" + for arg_type, arg_name in zip(arg_types, arg_names) + ] + return f"{kernel.kernel_name}({', '.join(arguments)}, M, N, K, B, lda, ldb, ldc, ldd, 0, 0, 0, swizzle, workspace_size_ptr, (uint8_t*)workspace_data.get(), 0);" + + def _render_evt( + self, + op: GemmOperation, + evt_py_code: str, + buffer_renames: dict[str, str], + name_to_buffer: dict[str, Buffer], + output_dtype: torch.dtype, + accumulator_dtype: torch.dtype, + ) -> tuple[str, str, str, EVTArgRenames]: # type: ignore[name-defined] + raise NotImplementedError("_render_evt in CUTLASSGemmTemplate not implemented") + + +class CUTLASS3xGemmTemplate(CUTLASSGemmTemplate): + """ + CUTLASS 3x GEMM Template, which is used to generate CUTLASS GEMM kernels + including those which allow flexible fusions with epilogues. + """ + + @staticmethod + def add_cutlass_gemm_choices( + choices: list[ChoiceCaller], + layout: ir.Layout, + input_nodes: list[Buffer], + alpha: float | int = 1, + beta: float | int = 0, + input_reorder: list[int] | None = None, + use_fast_accum: bool | None = None, + **extra_kwargs, + ) -> None: + template = CUTLASS3xGemmTemplate( + input_nodes, + layout, + alpha, + beta, + input_reorder, + use_fast_accum, + ) + template._add_cutlass_gemm_choices( + choices, layout, input_nodes, alpha, beta, input_reorder, **extra_kwargs + ) + + @staticmethod + @functools.lru_cache(1) + def _get_supported_ops() -> "list[cutlass_library.gemm_operation.GemmOperation]": # type: ignore[name-defined] # noqa: F821 + import cutlass_library.library as cutlass_lib + + return [cutlass_lib.GemmKind.Universal3x] + + def _get_template(self) -> str: + return GEMM_TEMPLATE_CUTLASS_3X + + def _get_template_args( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> tuple[str, str | None]: + return (GEMM_ARGS_CUTLASS_3X, GEMM_ARGS_CUTLASS_3X_EPILOGUE) + + @staticmethod + def _has_tma_epilogue( # type: ignore[arg-type,name-defined] + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined,arg-type] # noqa: F821 + ) -> bool: # type: ignore[name-defined] + """Helper method: Determine whether a given Cutlass GEMM op has a TMA Epilogue""" + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.library as cutlass_lib + + result = False + if op.gemm_kind == cutlass_lib.GemmKind.Universal3x: + epilogue_schedule_str = str(op.epilogue_schedule).split(".")[-1] + result = epilogue_schedule_str.lower().startswith("tma") + return result + + @staticmethod + def supports_epilogue_fusion(op: GemmOperation, device_type: str) -> bool: + if device_type == "xpu": + return True + return CUTLASS3xGemmTemplate._has_tma_epilogue(op) + + def _are_inputs_layout_compatible(self, layouts: list[Layout]) -> bool: + """ + Evaluates whether input layouts are compatible for General Matrix Multiply (GEMM). + + This function checks compatibility of A, B, and possibly C operand layouts for + a General Matrix Multiply (GEMM) operation, expressed as 'alpha * matmul(A, B) + beta * C'. + It verifies requirements such as matching data types, minimum rank, and suitability + for broadcasting, as defined by PyTorch operations like `torch.matmul`, `torch.aten.mm`, + `addmm`, `bmm`, `baddbmm`, etc. + + Args: + layouts (List[Layout]): List containing 2 or 3 Layout objects representing + the input matrices A, B, and possibly C. + + Returns: + bool: True if layouts are GEMM compatible, otherwise False. + """ + if not (2 <= len(layouts) <= 5): + raise AssertionError(f"expected 2 to 5 layouts, got {len(layouts)}") + # Check if A and B are compatible + A_layout, B_layout = layouts[:2] + if len(A_layout.size) < 1: + return False + if len(B_layout.size) < 1: + return False + A_size = list(V.graph.sizevars.guarding_hints_or_throw(A_layout.size)) + B_size = list(V.graph.sizevars.guarding_hints_or_throw(B_layout.size)) + if len(A_size) < 2: + A_size.insert(0, 1) + if len(B_size) < 2: + A_size.insert(1, 1) + # Are batch dims broadcastable? + while len(A_size) < len(B_size): + A_size.insert(0, 1) + while len(B_size) < len(A_size): + B_size.insert(0, 1) + K = max(A_size[-1], B_size[-2]) + M = A_size[-2] + N = B_size[-1] + if K != A_size[-1] and A_size[-1] != 1: + return False + if K != B_size[-2] and B_size[-1] != 1: + return False + # check batch dim broadcastable + for i in range(len(A_size) - 2): + if A_size[i] != B_size[i] and A_size[i] != 1 and B_size[i] != 1: + return False + if len(layouts) == 3: + C_layout = layouts[2] + C_size = list(V.graph.sizevars.guarding_hints_or_throw(C_layout.size)) + while len(C_size) < len(A_size): + C_size.insert(0, 1) + # check batch dims + for i in range(len(A_size) - 2): + bd = max(A_size[i], B_size[i]) + if bd != C_size[i] and C_size[i] != 1: + return False + if len(C_size) > len(A_size): + # This may happen if the last elements of C are contiguous and + # their multiplied size equals the last dim size of B + if M != C_size[len(A_size) - 2] and C_size[len(A_size) - 2] != 1: + return False + remaining_size = 1 + for i in range(len(A_size) - 1, len(C_size)): + remaining_size *= C_size[i] + if N != remaining_size and remaining_size != 1: + return False + return True + if len(C_size) != len(A_size): + raise AssertionError( + f"expected C and A to have same rank, got {len(C_size)} and {len(A_size)}" + ) + if M != C_size[-2] and C_size[-2] != 1: + return False + if N != C_size[-1] and C_size[-1] != 1: + return False + return True + + def _render_evt( + self, + op: GemmOperation, + evt_py_code: str, + var_name_to_buffer_name: dict[str, str], + name_to_buffer: dict[str, Buffer], + output_dtype: torch.dtype, + accumulator_dtype: torch.dtype, + ) -> tuple[str, str, str, EVTArgRenames]: + from .lib_extensions.evt_extensions import create_example_tensors, trace + + acc_dtype = torch_dtype_to_cutlass_type(accumulator_dtype) + output_dtype = torch_dtype_to_cutlass_type(output_dtype) + + # TODO: size_hint_fn is passed to both create_example_tensors (just for + # tracing examples) and trace -> _render_argument_type -> _get_arg_from_node + # where stride values are baked as C++ literals into the generated CUTLASS + # argument struct. For the latter, accessing hint is wrong: even for + # backed symbols we access the hint without installing a guard, so the + # generated strides could be incorrect for different dynamic shape inputs. + # guarding_hint_or_throw would be wrong here — it does not install + # guards either. This should use guard_int to properly guard on the values. + examples = create_example_tensors( + var_name_to_buffer_name, + name_to_buffer, # type: ignore[arg-type] + V.graph.sizevars.optimization_hint, + ) + evt_name, evt_args, evt_code, arg_renames = trace( + evt_py_code, + examples, + acc_dtype, + output_dtype, + op.tile_description, # type: ignore[attr-defined] + op.epilogue_schedule, # type: ignore[attr-defined] + {k: name_to_buffer[v] for k, v in var_name_to_buffer_name.items()}, # type: ignore[arg-type,misc] + V.graph.sizevars.guarding_hint_or_throw, + kernel_schedule=op.kernel_schedule, + device_type=self.device_type, + ) + + return ( + evt_name, + evt_args, + evt_code, + arg_renames, + ) + + def _shape_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + return True + + def _alignment_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + return True + + def _set_bias_layout_and_alignment( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + import cutlass_library.library as cutlass_lib + + has_bias = len(self.input_nodes) == 3 and self.input_nodes[2] is not None + if has_bias: + Bias = self.input_nodes[2] + # bias dtype + op.C.element = cutlass_utils.torch_dtype_to_cutlass_type( + Bias.get_layout().dtype + ) + + # Bias layout + bias_layout = CUTLASSGemmTemplate.cutlass_layout(Bias.get_layout()) + op.C.layout = bias_layout + + # Bias alignment + status = self.set_alignment(Bias.get_layout(), op.C) + if not status: + return False + else: + op.C.element = cutlass_lib.DataType.void + return True + + def _define_gemm_instance( + self, + op: GemmOperation, + evt_name: str | None = None, + ) -> tuple[str, str]: + """Defines and renders the Cutlass / CUDA/XPU C++ code for a given GEMM operation instance. + + This function uses the Cutlass library to generate key parts of the codegen process. General Matrix Multiply + forms a core part of a number of scientific applications, so this efficient and adaptable implementation is + crucial. + + Args: + op (cutlass_library.gemm_op.GemmOperation): This is the core GEMM operation that we are defining and rendering. + + Returns: + tuple[str, str]: A tuple where the first part is a string that constitutes the defined GEMM operation in C++ + code (render) and the second part is the string that specifies the operation type. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.library as cutlass_lib + + from .lib_extensions import gemm_operation_extensions as gemm_extensions + + emitter = gemm_extensions.EmitGemmUniversal3xInstanceWithEVT( + evt_name=evt_name, device_type=self.device_type + ) # type: ignore[call-arg] + + if not hasattr(op, "epilogue_functor") or not isinstance( + op.epilogue_functor, enum.Enum + ): + op = copy.deepcopy(op) + op.epilogue_functor = cutlass_lib.EpilogueFunctor.LinearCombination + + op_def = emitter.emit(op) + pattern = re.compile(r"\s*struct\s(.*?)\s:") + decl = [line for line in op_def.split("\n") if "struct " in line][-1] + + match = pattern.match(decl) + if match is None: + raise RuntimeError("Invalid Gemm config: \n" + op_def) + op_type = match.groups()[0] + if op.gemm_kind == cutlass_lib.GemmKind.Universal3x: + # Append KERNEL_NAME to the struct name to ensure uniqueness across + # compiled .so files. When multiple kernels share the same GEMM core + # but have different epilogues (e.g., LinearCombination vs EVT), they + # produce identical struct names. On SYCL/XPU this causes the runtime + # to dispatch the wrong binary; on CUDA it avoids potential symbol + # collisions. KERNEL_NAME gets replaced with a unique per-.so hash + # in scheduling.py. + unique_op_type = f"{op_type}_{Placeholder.KERNEL_NAME}" + op_def = op_def.replace(f"struct {op_type} :", f"struct {unique_op_type} :") + op_def += f"\n using {unique_op_type}_device_type = cutlass::gemm::device::GemmUniversalAdapter<{unique_op_type}>;\n" + op_type = f"{unique_op_type}_device_type" + + return op_def, op_type + + def _get_extra_inputs_and_names( + self, + op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821 + ) -> tuple[Buffer | None, list[Buffer | None], list[str]]: + Bias = self.input_nodes[2] if len(self.input_nodes) == 3 else None + inputs: list[Buffer | None] = [] + names: list[str] = [] + return (Bias, inputs, names) + + def _update_arg_names_for_test_call_statement( + self, + arg_names: list[str], + input_nodes: list[Buffer], + ) -> list[str]: + if input_nodes[2] is None: + del arg_names[2] + else: + # Reorder them as Bias, A, B + if self.input_reorder is not None: + arg_names[0 : len(self.input_reorder)] = [ + arg_names[i] for i in self.input_reorder + ] + return arg_names + + def render_gemm_arguments( + self, + argument_template: str, + epilogue_template: str, + should_swap_xw: bool, + X: IRNode, + W: IRNode, + Bias: IRNode, + Y: IRNode, + alpha: float, + beta: float, + kernel: CUTLASSTemplateKernel, + epilogue_args, + ) -> str: + """ + Render the Cutlass CUDA/XPU C++ code required for passing arguments to the GEMM operation. + + Args: + argument_template (str): Template for the GEMM operation arguments. + epilogue_template (str): Template for the epilogue arguments. + should_swap_xw (bool): Determines whether X, W operands should be swapped. If True, applies an explicit + transpose operation to X and W. + X (IRNode): The X input tensor. + W (IRNode): The W input tensor. + Bias (IRNode): The bias tensor. + Y (IRNode): The output tensor. + alpha (float): Scaling factor for the product of the inputs. + beta (float): Scaling factor for the output tensor. + kernel (CUTLASSTemplateKernel): CUDA/XPU Template kernel for the operation. + epilogue_args (any): Additional arguments for the epilogue state. + + Returns: + str: A block of CUDA/XPU C++ code as a string, ready to be used as arguments for the GEMM operation. + + Note: If `should_swap_xw` is True, a transpose operation will be applied to the X, W, Bias, and Y + tensors. This operation also implies the M and N dimensions of Bias and GEMM output to be swapped + before the function call. + """ + options = { + "alpha": alpha, + "beta": beta, + "X": X, + "W": W, + "Y": Y, + "Bias": Bias, + "template": self, + "kernel": kernel, + "M": "M", + "N": "N", + "epilogue_args": epilogue_args, + } + if epilogue_template is None: + raise AssertionError("expected epilogue_template to be non-None") + + if should_swap_xw: + # Swap + def clone_with_transposed_stride(node: IRNode) -> IRNode: + old_layout = node.get_layout() + new_stride = list(old_layout.stride) # type: ignore[union-attr] + new_stride[-2], new_stride[-1] = new_stride[-1], new_stride[-2] + if old_layout.device is None: + raise AssertionError("expected old_layout.device to be non-None") + new_layout = FixedLayout( + old_layout.device, + old_layout.dtype, + list(old_layout.size), # type: ignore[union-attr] + new_stride, + old_layout.offset, # type: ignore[union-attr] + ) + return Buffer(name=node.get_name(), layout=new_layout) + + new_X = clone_with_transposed_stride(X) + new_W = clone_with_transposed_stride(W) + new_Bias = clone_with_transposed_stride(Bias) + new_Y = clone_with_transposed_stride(Y) + options["X"], options["W"], options["Bias"], options["Y"] = ( + new_W, + new_X, + new_Bias, + new_Y, + ) + options["M"], options["N"] = "N", "M" + + epilogue_arguments = self._template_from_string(epilogue_template).render( + **options + ) + arguments = self._template_from_string(argument_template).render( + epilogue_arguments=epilogue_arguments, **options + ) + + return arguments + + +class CUTLASS2xGemmTemplate(CUTLASSGemmTemplate): + """CUTLASS 2x GEMM Template, which is used to generate CUTLASS 2x GEMM kernels""" + + def __init__( + self, + input_nodes: list[Buffer], + layout: Layout, + alpha: float, + beta: float, + input_reorder: list[int] | None = None, + ): + super().__init__(input_nodes, layout, alpha, beta, input_reorder) + + @staticmethod + def add_cutlass_gemm_choices( + choices: list[ChoiceCaller], + layout: ir.Layout, + input_nodes: list[Buffer], + alpha: float | int = 1, + beta: float | int = 0, + input_reorder: list[int] | None = None, + use_fast_accum: bool | None = False, + **extra_kwargs, + ) -> None: + template = CUTLASS2xGemmTemplate( + input_nodes, layout, alpha, beta, input_reorder + ) + template._add_cutlass_gemm_choices( + choices, layout, input_nodes, alpha, beta, input_reorder, **extra_kwargs + ) + + @staticmethod + def _get_supported_ops() -> "list[cutlass_library.gemm_operation.GemmOperation]": # type: ignore[name-defined] # noqa: F821 + import cutlass_library.library as cutlass_lib + + return [cutlass_lib.GemmKind.Universal, cutlass_lib.GemmKind.Sparse] + + @staticmethod + def _has_tma_epilogue(self) -> bool: + return False + + def _get_template(self) -> str: + return GEMM_TEMPLATE_CUTLASS_2X + + def _get_template_args( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> tuple[str, str | None]: + import cutlass_library.library as cutlass_lib + + if op.gemm_kind == cutlass_lib.GemmKind.Sparse: + return (GEMM_ARGS_SPARSE_CUTLASS_2X, None) + + return (GEMM_ARGS_CUTLASS_2X, None) + + def _are_inputs_layout_compatible(self, layouts: list[Layout]) -> bool: + """ + Evaluates whether input layouts are compatible for set of operations supported by this class. + + Args: + layouts (List[Layout]): List containing Layout objects representing + the input matrices. + + Returns: + bool: True if layouts are GEMM compatible, otherwise False. + """ + if not (len(layouts) == 2 or len(layouts) == 3): + raise AssertionError(f"expected 2 or 3 layouts, got {len(layouts)}") + # Check if A and B are compatible + A_layout, B_layout = layouts[:2] + if len(A_layout.size) != 2: + return False + if len(B_layout.size) != 2: + return False + A_size = [int(i) for i in A_layout.size] + B_size = [int(i) for i in B_layout.size] + K = max(A_size[1], B_size[0]) + return (K == A_size[1] or K == 2 * A_size[1]) and K == B_size[0] + + def _shape_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + import cutlass_library.library as cutlass_lib + + X, W = self.input_nodes[0], self.input_nodes[1] + + if op.gemm_kind == cutlass_lib.GemmKind.Sparse: + return X.get_size()[1] * 2 == W.get_size()[0] + + return X.get_size()[1] == W.get_size()[0] + + def _alignment_match( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + import cutlass_library.library as cutlass_lib + + if op.gemm_kind != cutlass_lib.GemmKind.Sparse: + return True + + # SparseGemm in CUTLASS has specific alignment check that for + # small k could make some of the choices throw kMisalignedOperand + # CUTLASS error when run, see: + # https://github.com/NVIDIA/cutlass/blob/e01b9b5029b7caca5a43c29f7d2714d7cf1dcae8/include/cutlass/gemm/kernel/sparse_gemm.h#L198-L200 + # So, let's skip these choices if that would be the case. + X = self.input_nodes[0] + return (X.get_size()[1] * 2) % op.tile_description.tile_shape[2] == 0 + + def _set_bias_layout_and_alignment( + self, + op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821 + ) -> bool: + import cutlass_library.library as cutlass_lib + + if op.gemm_kind == cutlass_lib.GemmKind.Sparse: + op.C.layout = op.D.layout + return True + + if len(self.input_nodes) >= 3 and self.input_nodes[2] is not None: + Bias = self.input_nodes[2] + bias_layout = CUTLASSGemmTemplate.cutlass_layout(Bias.get_layout()) + if bias_layout != op.D.layout: + # For cutlass2, bias and output layout must match + return False + if not self.set_alignment(Bias.get_layout(), op.C): + return False + else: + op.C.layout = op.D.layout + return True + + def _define_gemm_instance( + self, + op: GemmOperation, + evt_name: str | None = None, + ) -> tuple[str, str]: + """Defines and renders the Cutlass / CUDA C++ code for a given GEMM operation instance. + + This function uses the Cutlass library to generate key parts of the codegen process. General Matrix Multiply + forms a core part of a number of scientific applications, so this efficient and adaptable implementation is + crucial. + + Args: + op (cutlass_library.gemm_op.GemmOperation): This is the core GEMM operation that we are defining and rendering. + + Returns: + tuple[str, str]: A tuple where the first part is a string that constitutes the defined GEMM operation in C++ + code (render) and the second part is the string that specifies the operation type. + """ + if not cutlass_utils.try_import_cutlass(): + raise AssertionError("could not import cutlass") + import cutlass_library.gemm_operation as cutlass_gemm_op + import cutlass_library.library as cutlass_lib + + if op.gemm_kind == cutlass_lib.GemmKind.Sparse: + emitter = cutlass_gemm_op.EmitSparseGemmInstance() + else: + emitter = cutlass_gemm_op.EmitGemmInstance() + op_def = emitter.emit(op) + op_def = op_def.replace( + "cutlass::gemm::device::Gemm", "cutlass::gemm::device::GemmUniversal" + ) + if op.gemm_kind != cutlass_lib.GemmKind.Sparse: + op_def = op_def.replace("false,", "") + pattern = re.compile(r"\s*using\s(.*?)\s=") + decl = op_def.split("\n")[2] + + match = pattern.match(decl) + if match is None: + raise RuntimeError("Invalid Gemm config: \n" + op_def) + op_type = match.groups()[0] + return op_def, op_type + + def _get_extra_inputs_and_names( + self, + op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821 + ) -> tuple[Buffer | None, list[Buffer | None], list[str]]: + import cutlass_library.library as cutlass_lib + + if op.gemm_kind == cutlass_lib.GemmKind.Sparse: + Bias = None + Meta = self.input_nodes[2] + else: + Bias = None if len(self.input_nodes) == 2 else self.input_nodes[2] + Meta = None + inputs = [Meta] + names = ["Meta"] + return (Bias, inputs, names) + + def _update_arg_names_for_test_call_statement( + self, + arg_names: list[str], + input_nodes: list[Buffer], + ) -> list[str]: + if input_nodes[3] is None: + del arg_names[3] + if input_nodes[2] is None: + del arg_names[2] + return arg_names + + def render_gemm_arguments( + self, + instance_type: str, + argument_template: str, + epilogue_template: str, + should_swap_xw: bool, + X: IRNode, + W: IRNode, + Bias: IRNode, + Meta: IRNode, + Y: IRNode, + alpha: float, + beta: float, + kernel: CUTLASSTemplateKernel, + epilogue_args, + ) -> str: + """ + Render the Cutlass CUDA C++ code required for passing arguments to the GEMM operation. + + Args: + instance_type (str): GEMM instance type. + argument_template (str): Template for the GEMM operation arguments. + epilogue_template (str): Template for the epilogue arguments. + should_swap_xw (bool): Determines whether X, W operands should be swapped. If True, applies an explicit + transpose operation to X and W. + X (IRNode): The X input tensor. + W (IRNode): The W input tensor. + Bias (IRNode): The bias tensor. + Meta (IRNode): The meta tensor. + Y (IRNode): The output tensor. + alpha (float): Scaling factor for the product of the inputs. + beta (float): Scaling factor for the output tensor. + kernel (CUTLASSTemplateKernel): CUDA Template kernel for the operation. + epilogue_args (any): Additional arguments for the epilogue state. + + Returns: + str: A block of CUDA C++ code as a string, ready to be used as arguments for the GEMM operation. + + Note: If `should_swap_xw` is True, a transpose operation will be applied to the X, W, Bias, and Y + tensors. This operation also implies the M and N dimensions of Bias and GEMM output to be swapped + before the function call. + """ + options = { + "instance_type": instance_type, + "alpha": alpha, + "beta": beta, + "X": X, + "W": W, + "Y": Y, + "Bias": Bias, + "Meta": Meta, + "template": self, + "kernel": kernel, + "M": "M", + "N": "N", + "epilogue_args": epilogue_args, + } + + if epilogue_template is None: + arguments = self._template_from_string(argument_template).render( + split_k=1, **options + ) + return arguments + + epilogue_arguments = self._template_from_string(epilogue_template).render( + **options + ) + arguments = self._template_from_string(argument_template).render( + epilogue_arguments=epilogue_arguments, **options + ) + + return arguments diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..4602a72d5ee15b8dd572ccb73911f8e9d08f3970 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/kernel.py @@ -0,0 +1,723 @@ +# mypy: allow-untyped-defs +import functools +import itertools +import logging +from collections import defaultdict +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any, Literal, TYPE_CHECKING + +from sympy import Expr, symbols + +import torch._inductor.config as config +from torch import dtype as torch_dtype +from torch._inductor.codegen.common import get_device_op_overrides +from torch._inductor.codegen.cpp_wrapper_cpu import CppWrapperCpu +from torch._inductor.scheduler import BaseSchedulerNode +from torch._inductor.utils import do_bench_using_profiling, OrderedSet, Placeholder +from torch.utils._sympy.value_ranges import ValueRanges + +from .utils import DTYPE_TO_CUTLASS_TYPE + + +if TYPE_CHECKING: + from .template import ArgInfo + +from ...autotune_process import CUTLASSBenchmarkRequest +from ...ir import ( + Buffer, + ChoiceCaller, + CUTLASSTemplateBuffer, + IRNode, + Layout, + PrimitiveInfoType, + TensorBox, +) +from ...utils import sympy_product +from ...virtualized import V +from ..common import ( + CSEVariable, + IndentedBuffer, + Kernel, + OpOverrides, + WorkspaceArg, + WorkspaceZeroMode, +) +from ..cpp_utils import CppPrinter, DTYPE_TO_CPP + + +if TYPE_CHECKING: + from torch._inductor.codegen.cutlass.template import CUTLASSTemplate + +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 + + +ValidLayoutSymbols = Literal["M", "N", "K", "B", "lda", "ldb", "ldc", "ldd"] +ValidLayoutAttrs = Literal["size", "stride"] + + +@dataclass(frozen=True) +class LayoutArg: + node: IRNode + symbol: ValidLayoutSymbols + attr: ValidLayoutAttrs + dim: int + + def matches(self, node, attr, dim) -> bool: + return self.node == node and self.attr == attr and self.dim == dim + + +class CUTLASSKernel(Kernel): + """ + Baseclass for Cutlass based Kernels + """ + + overrides = OpOverrides # type: ignore[assignment] + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.layout_args: dict[str, list[LayoutArg]] = defaultdict(list) + self.size_args: list[Expr | int] = [] + # Mapping from arg name to IRNode. + self.named_nodes: dict[str, IRNode] = {} + + def find_symbol(self, node: IRNode, attr: ValidLayoutAttrs, dim: int) -> str | None: + arg = self.find_layout_arg(node, attr, dim) + return arg.symbol if arg else None + + def find_layout_arg( + self, node: IRNode, attr: ValidLayoutAttrs, dim: int + ) -> LayoutArg | None: + matches = [ + arg + for arg in itertools.chain.from_iterable(self.layout_args.values()) + if arg.matches(node, attr, dim) + ] + if len(matches) >= 1: + # Verify all matches have the same node, attribute, and dimension + # And if they come from the same node, whichever symbol we use is fine. + # if in runtime the logic changes, this would trigger guard + first_match = matches[0] + if not all( + match.node == first_match.node + and match.attr == first_match.attr + and match.dim == first_match.dim + for match in matches + ): + raise AssertionError("All matching layout args should be identical") + return first_match + attr_values = node.get_size() if attr == "size" else node.get_stride() + if dim >= len(attr_values): + return None + expr = attr_values[dim] + fallback_matches = [] + for arg in itertools.chain.from_iterable(self.layout_args.values()): + if arg.attr != attr: + continue + if arg.node.get_name() != node.get_name(): + continue + arg_values = ( + arg.node.get_size() if arg.attr == "size" else arg.node.get_stride() + ) + if arg.dim >= len(arg_values): + continue + if arg_values[arg.dim] == expr: + fallback_matches.append(arg) + if fallback_matches: + return fallback_matches[0] + return None + + def add_layout_arg( + self, symbol: ValidLayoutSymbols, node: IRNode, attr: ValidLayoutAttrs, dim: int + ): + arg = LayoutArg(node, symbol, attr, dim) + self.layout_args[symbol].append(arg) + + def init_layout_args(self) -> None: + X = self.named_nodes["X"] + W = self.named_nodes["W"] + Y = self.named_nodes["Y"] + Bias = self.named_nodes.get("Bias", None) + x_mdim = _normalize_idx(-2, len(X.get_size())) + x_kdim = _normalize_idx(-1, len(X.get_size())) + w_kdim = _normalize_idx(-2, len(W.get_size())) + w_ndim = _normalize_idx(-1, len(W.get_size())) + y_mdim = _normalize_idx(-2, len(Y.get_size())) + y_ndim = _normalize_idx(-1, len(Y.get_size())) + self.add_layout_arg("M", X, "size", x_mdim) + self.add_layout_arg("K", X, "size", x_kdim) + self.add_layout_arg("K", W, "size", w_kdim) + self.add_layout_arg("N", W, "size", w_ndim) + self.add_layout_arg("M", Y, "size", y_mdim) + self.add_layout_arg("N", Y, "size", y_ndim) + if len(X.get_size()) > 2: + self.add_layout_arg("B", X, "size", 0) + + lda_dim = self.find_ld_idx(X) + ldb_dim = self.find_ld_idx(W) + ldc_dim = self.find_ld_idx(Bias) if Bias else None + ldd_dim = self.find_ld_idx(Y) + self.add_layout_arg("lda", X, "stride", lda_dim) + self.add_layout_arg("ldb", W, "stride", ldb_dim) + if Bias is not None and ldc_dim is not None: + self.add_layout_arg("ldc", Bias, "stride", ldc_dim) + self.add_layout_arg("ldd", Y, "stride", ldd_dim) + + def get_layout_args(self) -> tuple[Expr | int, ...]: + X = self.named_nodes["X"] + W = self.named_nodes["W"] + Y = self.named_nodes["Y"] + Bias = self.named_nodes.get("Bias", None) + mdim = _normalize_idx(-2, len(X.get_size())) + ndim = _normalize_idx(-1, len(W.get_size())) + kdim = _normalize_idx(-1, len(X.get_size())) + + def get_ld(node) -> Expr | int: + dim = self.find_ld_idx(node) + return node.get_stride()[dim] + + M = X.get_size()[mdim] + N = W.get_size()[ndim] + K = X.get_size()[kdim] + B = X.get_size()[0] if len(X.get_size()) > 2 else 1 + LDA = get_ld(X) + LDB = get_ld(W) + LDC = get_ld(Bias) if Bias else 0 + LDD = get_ld(Y) + return (M, N, K, B, LDA, LDB, LDC, LDD) + + def get_dynamic_shape_args(self) -> list[Expr | int]: + return [*self.get_layout_args(), *self.size_args] + + def get_offset_args(self) -> list[Expr]: + return [node.get_layout().offset for node in self.named_nodes.values()] + + @staticmethod + def find_ld_idx(node: IRNode) -> int: + strides = node.get_stride() + # Handle 1D tensor case + if V.graph.sizevars.statically_known_equals(strides[-1], 1): + return _normalize_idx(-2, len(strides)) + + if not V.graph.sizevars.statically_known_equals(strides[-2], 1): + raise AssertionError(strides[-2]) + return _normalize_idx(-1, len(strides)) + + +class CUTLASSTemplateKernel(CUTLASSKernel): + """ + Template kernels defined by Cutlass in C++. + """ + + def __init__( + self, + kernel_name: str, + runtime_arg_info: list["ArgInfo"], + runtime_arg_values: list[Any], + device_type: str = "cuda", # type: ignore[assignment] + ) -> None: + """ + Initializes a new instance of the CUTLASSTemplateKernel class. + + Args: + kernel_name (str): The name of the kernel. + """ + super().__init__() + self.kernel_name = kernel_name + self.runtime_arg_info = runtime_arg_info + self.runtime_arg_values = runtime_arg_values + self.device_type = device_type + self.device_codegen = get_device_op_overrides(self.device_type) + self._EXTRA_CPP_ARGS = f"size_t* workspace_size, uint8_t* workspace, {self.device_codegen.cpp_stream_type()} stream" + + def check_not_null(self, node: IRNode) -> str: + """ + Generates code to check that a node is not null. + """ + if node is None: + return "" + + size_str = self.size(node, 0, -1) + name_str = self.arg_name(node) + if name_str is None: + return "" + + res = IndentedBuffer(initial_indent=2) + res.tabwidth = 1 + res.splice( + f""" + {{ + if (!{name_str}) {{ + int64_t {name_str}_size = {size_str}; + if ({name_str}_size > 0) {{ + throw std::runtime_error("input {name_str} is null but size is not 0!"); + }} + }} + }} + """ + ) + return res.getvalue() + + def get_signature(self) -> str: + return self.signature + + def _collect_unbound_layout_free_symbols(self, node: IRNode) -> OrderedSet[Expr]: + free_symbols: OrderedSet[Expr] = OrderedSet() + for attr_name, values in ( + ("size", node.get_size()), + ("stride", node.get_stride()), + ): + attr = attr_name # help mypy narrow the Literal argument below + for dim, expr in enumerate(values): + if not isinstance(expr, Expr): + continue + if self.find_layout_arg(node, attr, dim) is not None: + continue + for symbol in expr.free_symbols: + free_symbols.add(symbol) # type: ignore[arg-type] + return free_symbols + + def def_kernel( + self, + inputs: list[IRNode], + outputs: list[IRNode], + 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]. + additional_size_args: Additional size arguments for epilogue inputs + """ + # NB: name order matters here, it's used to match up offsets + 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 is not None: + if len(inputs) != len(input_reorder): + raise AssertionError( + f"expected len(inputs) == len(input_reorder), got " + f"{len(inputs)} != {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: + # NB: named nodes must be populated in the order of names + self.named_nodes[name] = node + self.args.output_buffers[node.get_name()] = name + + arg_defs, *_ = self.args.cpp_argdefs(DTYPE_TO_CUTLASS_TYPE) + + self.init_layout_args() + free_symbols: OrderedSet[Expr] = OrderedSet() + for node in self.named_nodes.values(): + free_symbols |= self._collect_unbound_layout_free_symbols(node) + size_vars = ["M", "N", "K", "B", "lda", "ldb", "ldc", "ldd"] + size_vars.extend(str(s) for s in free_symbols) + self.size_args.extend(free_symbols) + size_args = [f"const int {s}" for s in size_vars] + offset_args = [f"const int {name}_offset" for name in self.named_nodes] + runtime_arg_decls = ",".join( + [f"{arg.ty} {arg.name}" for arg in self.runtime_arg_info] + ) + if runtime_arg_decls: + runtime_arg_decls += ", " + + signature = ( + f"int {self.kernel_name}({', '.join(arg_defs + size_args + offset_args)},\ + {runtime_arg_decls}{self._EXTRA_CPP_ARGS})" + ) + self.signature = signature + return signature + + def call_kernel( + self, + name: str, + node: "CUTLASSTemplateBuffer", # 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 CUTLASSTemplateBuffer 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 + # We always originally initialize name with "KERNEL_NAME". So, we + # we replace with the real kernel name passed as an arg to this function. + self.signature = self.signature.replace(str(Placeholder.KERNEL_NAME), name) + _, call_args, arg_types = self.args.cpp_argdefs(DTYPE_TO_CUTLASS_TYPE) + else: + _, call_args, _, arg_types = self.args.python_argdefs() + + dynamic_shape_args = self.get_dynamic_shape_args() + offset_args = self.get_offset_args() + call_args.extend(dynamic_shape_args) # type: ignore[arg-type] + call_args.extend(offset_args) # type: ignore[arg-type] + for arg in self.runtime_arg_values: + call_args.append(str(arg)) + arg_types.extend("const int" for _ in dynamic_shape_args) + arg_types.extend("const int" for _ in offset_args) + for arg in self.runtime_arg_info: + arg_types.append(arg.ty) + # dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar + for i in range(len(call_args)): + if V.graph.is_unspec_arg(call_args[i]): + call_args[i] = call_args[i] + ".item()" + elif isinstance(arg_types[i], torch_dtype): + call_args[i] = ( + call_args[i] + if V.graph.cpp_wrapper + else f"c_void_p({call_args[i]}.data_ptr())" + ) + + # 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. + # workspace_size is here. + call_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) + workspace = str(ws.outer_name) + call_args.append( + workspace + if V.graph.cpp_wrapper + else f"c_void_p({workspace}.data_ptr())" + ) + else: + ws = None + call_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, + call_args, + triton=False, + arg_types=arg_types, + ) + if ws: + wrapper.generate_workspace_deallocation(ws) + + def dtype(self, node: IRNode) -> str | None: + """ + Generates code which represents dtype of a given node. + """ + + if node is None: + return "void" + return DTYPE_TO_CPP.get(node.get_layout().dtype) + + def cutlass_dtype(self, node: IRNode, default_dtype="void") -> str | None: + # Helper method, called into from CUTLASSGemmTemplate + if node is None: + return default_dtype + from torch._inductor.codegen.cutlass.template import CUTLASSTemplate + + return CUTLASSTemplate._DTYPE_TO_CUTLASS[node.get_layout().dtype] + + def max_valid_index(self, node: IRNode, default=-1): + # Helper method, called into from CUTLASSGemmTemplate + if node is None: + return default + max_valid_offset = 0 + for i in range(len(node.get_size())): + max_valid_offset += (node.get_size()[i] - 1) * node.get_stride()[i] + return max_valid_offset + + def ptr(self, node: IRNode) -> str: + """ + Generates code which represents pointer of a given node. + """ + + if node is None: + return "nullptr" + arg_name = self.arg_name(node) + if arg_name is None: + return "nullptr" + return f"{arg_name} + {arg_name}_offset" + + def size( + self, + node: IRNode, + start_index: int, + end_index: int | None = None, + default_value: int = 0, + ) -> str: + """ + Hook called from template code to get the size of an arg. + Generates code which represents size of a given node in [start_index, end_index). + If node is None, returns default_value. + + TODO: Will add needed args to pass it in if it is dynamic. + """ + + if node is None: + return str(default_value) + + start_index = _normalize_idx(start_index, len(node.get_size())) + if end_index is None: + end_index = start_index + end_index = _normalize_idx(end_index, len(node.get_size())) + sizes = [ + self.find_symbol(node, "size", dim=i) or node.get_size()[i] + for i in range(start_index, end_index + 1) + ] + if len(sizes) == 0: + return str(default_value) + + sizes = [symbols(v) if isinstance(v, str) else v for v in sizes] + val = sympy_product(sizes) + return val + + def stride(self, node: IRNode, index: int, default_value: int = 0) -> str: + """ + Hook called from template code to get the stride of an arg. + Generates code which represents stride of a given node at index. + If node is None, returns default_value. + + TODO: Will add needed args to pass it in if it is dynamic. + """ + + if node is None: + return str(default_value) + + index = _normalize_idx(index, len(node.get_size())) + if index < 0: + return str(default_value) + + stride = node.get_stride()[index] + if V.graph.sizevars.statically_known_leq(stride, 1): + return str(stride) + return self.find_symbol(node, "stride", dim=index) or str(stride) + + def batch_stride(self, node: IRNode, default_value: int = 0) -> str: + """ + Hook called from template code to get the batch stride of an arg. + Returns 0 if batch dim is not present. + + This method assumes that batch stride is the largest stride. + """ + + if node is None: + return str(default_value) + + if len(node.get_size()) < 3: + return str(default_value) + + batch_stride = node.get_stride()[0] + if V.graph.sizevars.statically_known_leq(batch_stride, 1): + return str(batch_stride) + + return "{}*{}".format( + self.find_symbol(node, "size", dim=1) or node.get_size()[1], + self.find_symbol(node, "size", dim=2) or node.get_size()[2], + ) + + def row_or_column_stride(self, node: IRNode, default_value: int = 0) -> str: + """ + Hook called from template code to get the row or column stride of an arg. + This is required by some CUTLASS 2.X APIs. + If the node is in row_major, it returns stride[-2]. + If the node is in column_major, it returns stride[-1]. + + TODO: Will add needed args to pass it in if it is dynamic. + """ + + if node is None or len(node.get_stride()) < 2: + return str(default_value) + + stride0 = node.get_stride()[-1] + stride1 = node.get_stride()[-2] + if stride0 == 1: + return cexpr(self.rename_indexing(stride1)) + elif stride1 == 1: + return cexpr(self.rename_indexing(stride0)) + else: + raise RuntimeError( + f"At least 1 stride should be 1. Strides: {node.get_stride()=}" + ) + + def load(self, name: str, index: Expr, mode: Any = None) -> CSEVariable: + """ + Mock load function for memory planning to optimize allocations properly. + """ + return self.create_cse_var(name, bounds=ValueRanges.unknown()) + + def store(self, name: str, index: Expr, value: Any, mode: Any = None) -> None: + """ + Mock store function for memory planning to optimize allocations properly. + """ + self.store_buffer_names.add(name) + + +class CUTLASSTemplateCaller(ChoiceCaller): + """ + CUTLASSTemplateCaller + + This class represents a caller for CUTLASS template kernels. It is a subclass of ChoiceCaller. + Attributes: + name (str): The name of the caller. + category (str): The category of the caller. + bmreq (CUTLASSBenchmarkRequest): The benchmark request for the caller. + template_buffer (CUTLASSTemplateBuffer): The template buffer for the caller. + """ + + def __init__( + self, + name: str, + category: str, + input_nodes: list[Buffer], + layout: Layout, + make_kernel_render: Callable[ + [CUTLASSTemplateBuffer, list[BaseSchedulerNode] | None], + tuple[CUTLASSTemplateKernel, functools.partial[str]], + ], + bmreq: CUTLASSBenchmarkRequest, + supports_epilogue_fusion: bool, + template: "CUTLASSTemplate", # type: ignore[name-defined] + info_kwargs: dict[str, PrimitiveInfoType | list[PrimitiveInfoType]] | None, # type: ignore[type-arg] + description: str, + ) -> None: + super().__init__(name, input_nodes, layout, description) + self.category = category + self.make_kernel_render = make_kernel_render + self.bmreq = bmreq + self.supports_epilogue_fusion = supports_epilogue_fusion + self.template = template + self.info_kwargs = info_kwargs + + def precompile(self) -> None: + if self.bmreq is None: + raise AssertionError("expected self.bmreq to not be None") + self.bmreq.precompile() + + def benchmark(self, *args, out) -> float: + if self.bmreq is None: + raise AssertionError("expected self.bmreq to not be None") + 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"CUTLASSTemplateCaller(source_file={self.bmreq.source_file})" + + def call_name(self) -> str: + return f"cutlass_template_kernels.{self.name}" + + def kernel_hash_key(self) -> str: + """ + Return kernel hash key that does not depend on swizzle. + """ + return "-".join( + [ + self.category, + self.bmreq.hash_key, + ] + ) + + def hash_key(self) -> str: + """ + Return kernel hash key that does not depend on swizzle. + """ + swizzle_str: str = ( + str(self.info_kwargs.get("swizzle")) + if isinstance(self.info_kwargs, dict) + else "None" + ) + return "-".join( + [ + self.category, + self.bmreq.hash_key, + swizzle_str, + ] + ) + + def info_dict(self) -> dict[str, PrimitiveInfoType | list[PrimitiveInfoType]]: + """ + Information returned here is logged to the autotune log file when that is enabled. + + In general, we should avoid calling this function as it is expensive to compute, + and can add up very fast. + """ + if self.info_kwargs is not None and "op" in self.info_kwargs: + op: Any = self.info_kwargs["op"] + return { + "backend": "CUDA", + "op_type": type(op).__name__, + "op_conf_name": str(op.configuration_name()), + "op_arch": str(op.arch), + "tile_shape": str(op.tile_description.tile_shape), + "epilogue_schedule": str(op.epilogue_schedule), + "kernel_schedule": str(op.kernel_schedule), + "element_accumulator": str(op.accumulator_type()), + "op_name": str(op.procedural_name()), + "instruction_shape": str( + op.tile_description.math_instruction.instruction_shape + ), + "swizzle": str(self.info_kwargs["swizzle"]), + } + else: + return {"backend": "CUDA", "op_type": "unknown"} + + def output_node(self) -> TensorBox: + self.bmreq.update_workspace_size() + buffer = CUTLASSTemplateBuffer( + layout=self.layout, + inputs=self.input_nodes, + make_kernel_render=self.make_kernel_render, + workspace_size=self.bmreq.workspace_size, + supports_epilogue_fusion=self.supports_epilogue_fusion, + 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/cutlass/lib_extensions/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01661a5584d36bf048aac64192aacdbeb9fa1f24 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/evt_extensions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/evt_extensions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e44d1ffb1c402135c2350844fded95a9e17c656b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/evt_extensions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/gemm_operation_extensions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/gemm_operation_extensions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cdd3dc73756862a65b487b7c8a904b8d6648e92 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/gemm_operation_extensions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7383d6262ad2f308da3b3cbc2b26ca2885cc6600 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e12a86af8ab0ab8d7d7b2d8bf37ec6dec861e0ff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__init__.py @@ -0,0 +1,6 @@ +import torch + + +__version__ = torch.version.cuda + +from .cuda import * # noqa: F403 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdcdccc807e441b1f70547d7dd0145edeba9aa97 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cuda.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cuda.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..798b6e3235b2375296b7386b31c0208f8f3271cd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cuda.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cudart.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cudart.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f9ec76c0bfd6152e147611a3b3b3414b27937f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cudart.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cuda.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..ad41f04fc897e33f4530eb42c76a104def58f413 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cuda.py @@ -0,0 +1,24 @@ +# mypy: disable-error-code="no-untyped-def" +# flake8: noqa +import torch + + +class CUdeviceptr: + pass + + +class CUstream: + def __init__(self, v): + pass + + +class CUresult: + CUDA_SUCCESS = True + + +class nvrtc: + pass + + +def cuDeviceGetCount(): + return (CUresult.CUDA_SUCCESS, torch.cuda.device_count()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cudart.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cudart.py new file mode 100644 index 0000000000000000000000000000000000000000..ca2ee5f1f6163d7b20336d6102ce5d8f97880c87 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cudart.py @@ -0,0 +1,17 @@ +# mypy: disable-error-code="no-untyped-def" +import torch.cuda + + +class cudaError_t: + cudaSuccess = True + + +def cudaFree(n): + return (cudaError_t.cudaSuccess,) + + +def cudaGetDeviceProperties(d): + class DummyError: + value = False + + return (DummyError(), torch.cuda.get_device_properties(d)) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8aefb6171b682f062cfe57a1876f51b280f120cc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__init__.py @@ -0,0 +1,2 @@ +# mypy: disable-error-code="var-annotated" +Dot = None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e2ba9c4d9dead34fd58a75525658f4350a7998e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f0378d35a9c442559373f035e45de19b2be927cd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__init__.py @@ -0,0 +1,3 @@ +# typing: ignore +# flake8: noqa +from .special import * diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..164fd26384eca8064b73f1bc37d84f1ff8d290c2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/special.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/special.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73e4cb98294e06a4304d555e64901bcac8a1fd5d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/special.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/special.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/special.py new file mode 100644 index 0000000000000000000000000000000000000000..79af3029aa0b18d0ad55633f8cca8af8b76b520b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/special.py @@ -0,0 +1,2 @@ +# mypy: disable-error-code="var-annotated" +erf = None diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/evt_extensions.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/evt_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..666e09d3be718ff81baa6622524cd0f1b36e6371 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/evt_extensions.py @@ -0,0 +1,371 @@ +from collections.abc import Callable +from typing import Any + +from sympy import Expr + +from torch._inductor.ir import ( + ComputedBuffer, + InputBuffer, + is_contiguous_strides_for_shape, +) +from torch.utils._ordered_set import OrderedSet + +from ..utils import cutlass_arch, torch_dtype_to_cutlass_type, try_import_cutlass + + +EpilogueFunctor = Any # EpilogueFunctor local class defined in _trace +Buffer = ComputedBuffer | InputBuffer +CutlassTupleType = Any # cutlass.backend.c_types.tuple_factory_..TupleType +CutlassVisitorType = Any # cutlass.backend.c_types.visitor_factory..VisitorType +CutlassArgType = ( + Any # Can be a CutlassTupleType, CutlassVisitorType, EmptyByte, or ctype.c_void_p +) + + +if try_import_cutlass(): + import ast + import ctypes + import textwrap + + from cutlass_cppgen.backend.c_types import ( # type: ignore[import-not-found] + EmptyByte, + ) + from cutlass_cppgen.backend.epilogue import ( # type: ignore[import-not-found] + dtype2ctype, + ) + from cutlass_cppgen.backend.evt import ( # type: ignore[import-not-found] + backend as evt_backend, + EpilogueFunctorVisitor, + ) + from cutlass_cppgen.backend.evt.backend.emitter_base import ( # type: ignore[import-not-found] + FusionCallbacks, + ) + from cutlass_cppgen.backend.evt.backend.sm100_emitter import ( # type: ignore[import-not-found] + Sm100CollectiveEpilogue, + ) + from cutlass_cppgen.backend.evt.frontend import ( # type: ignore[import-not-found] + PythonASTFrontend, + ) + from cutlass_cppgen.backend.evt.ir.tensor import ( # type: ignore[import-not-found] + Tensor as CutlassTensor, + ) + from cutlass_library import ( + DataType, + EpilogueScheduleType, + LayoutType, + TileDescription, + ) + + from torch._inductor.utils import IndentedBuffer + + _CUTLASS_C_DTYPES = OrderedSet(dtype2ctype.values()) # type: ignore[var-annotated] + + class EVTArgRenames: + """Handles mapping buffer names to variable names in the cpp kernel signature and body""" + + def __init__(self) -> None: + self.buf_renames: dict[str, str] = {} + + def new_name(self, name: str) -> str: + if name in self.buf_renames: + return self.buf_renames[name] + else: + new_name = f"ptr_{len(self.buf_renames)}" + self.buf_renames[name] = new_name + return new_name + + def get(self, name: str) -> str: + return self.buf_renames.get(name, name) + + def create_example_tensors( + var_name_to_buffer_name: dict[str, str], + name_to_buffer: dict[str, Buffer], + size_hint_fn: Callable[[Expr | int], int], + ) -> dict[str, CutlassTensor]: + def cutlass_tensor_from_buffer( + buffer: Buffer, + ) -> CutlassTensor: + shape = buffer.get_layout().size + stride = buffer.get_layout().stride + shape = tuple(size_hint_fn(x) for x in shape) + stride = tuple(size_hint_fn(x) for x in stride) + + is_row_major = is_contiguous_strides_for_shape(stride, shape) + is_column_major = is_contiguous_strides_for_shape(stride[::-1], shape[::-1]) + + if not is_row_major and not is_column_major: + raise RuntimeError( + f"Cannot create example tensor for {buffer.get_name()} with \ +non-contiguous layout, received stride: {stride} and shape: {shape}" + ) + + return CutlassTensor( + shape=shape, + layout_tag=( + LayoutType.RowMajor if is_row_major else LayoutType.ColumnMajor + ), + element=torch_dtype_to_cutlass_type(buffer.get_layout().dtype), + ) + + return { + key: cutlass_tensor_from_buffer(name_to_buffer[name]) + for key, name in var_name_to_buffer_name.items() + } + + def trace( + fn_src: str, + example_tensors: dict[str, CutlassTensor], + accum_type: DataType, + output_type: DataType, + tile_description: TileDescription, + epilogue_schedule: EpilogueScheduleType, + name_to_buffer: dict[str, Buffer], + size_hint_fn: Callable[[Expr | int], int], + kernel_schedule: Any | None = None, + device_type: str = "cuda", + **kwargs: dict[str, Any], + ) -> tuple[str, str, str, EVTArgRenames]: + arch = int(cutlass_arch(device_type)) + if device_type == "cuda" and arch < 90: + raise AssertionError("For CUDA, only SM90+ is supported for EVT") + epilogue_functor = _trace(fn_src, example_tensors, arch, **kwargs) + visitor = EpilogueFunctorVisitor(arch, epilogue_functor) + fusion_callbacks = FusionCallbacks(visitor.graph, arch, emit_CD=False) + arch_prefix = "xe" if device_type == "xpu" else "sm" + + if device_type == "xpu" or arch < 100: + try: + evt_emitter = getattr(evt_backend, f"{arch_prefix}{arch}_emitter") + CollectiveEpilogue = evt_emitter.CollectiveEpilogue + except AttributeError as e: + raise NotImplementedError( + f"EVT backend is not supported on Arch {arch_prefix}{arch}." + ) from e + + collective_epilogue = CollectiveEpilogue( + tile_description, + epilogue_schedule, + accum_type, + output_type, + fusion_callbacks, + ) + else: + collective_epilogue = Sm100CollectiveEpilogue( + tile_description=tile_description, + kernel_schedule=kernel_schedule, + epilogue_schedule=epilogue_schedule, + element_accumulator=accum_type, + element_d=output_type, + fusion_callbacks=fusion_callbacks, + ) + evt_name, evt_code = collective_epilogue.emit() + evt_args, arg_renames = _render_argument_type( + epilogue_functor, name_to_buffer, size_hint_fn + ) + return evt_name, evt_args, evt_code, arg_renames + + # Based off of + # https://github.com/NVIDIA/cutlass/blob/df18f5e4f5de76bed8be1de8e4c245f2f5ec3020/python/cutlass/epilogue/epilogue.py#L117 + # This is modified to enable directly passing the source code of the epilogue vs getting it from a bona-fide python function + # The reason for this is that inspect.getsource does not work with functions defined at runtime via exec/eval + def _trace( + fn_src: str, + example_tensors: dict[str, CutlassTensor], + cc: int, + **kwargs: Any, + ) -> EpilogueFunctor: + class EpilogueFunctor(PythonASTFrontend): + def __init__(self, cc: int, **kwargs: Any): + self.source = textwrap.dedent(fn_src) + super().__init__(cc, **kwargs) + + def parse( + self, + example_inputs: dict[str, CutlassTensor], + ) -> None: + self.example_inputs = example_inputs + self.ast = ast.parse(self.source) + # pyrefly: ignore [missing-attribute] + self.visit(self.ast) + + epilogue_functor = EpilogueFunctor(cc=cc, **kwargs) + epilogue_functor.trace(example_tensors) + return epilogue_functor + + def _render_argument_type( + epilogue_functor: EpilogueFunctor, + name_to_buffer: dict[str, Buffer], + size_hint_fn: Callable[[Expr | int], int], + ) -> tuple[str, EVTArgRenames]: + epilogue_thread_type = epilogue_functor.epilogue_thread_type + arg_renames = EVTArgRenames() + + # Fragile, but this is the only way to guarantee t is expected type because t is a local class + def is_nested_visitor_type(t: type) -> bool: + return ( + ".".join([t.__module__, t.__qualname__]) + == "cutlass_cppgen.backend.c_types.visitor_factory..VisitorType" + ) + + buffer = IndentedBuffer() + with buffer.set_tabwidth(2): + + def get_constant_value(name: str) -> float | int | None: + dag_ir = getattr(epilogue_functor, "dag_ir", None) + if dag_ir is not None: + try: + node_meta = dag_ir.get_node_meta(name) + except Exception: + node_meta = None + if node_meta is not None: + tensor_meta = getattr(node_meta, "tensor", None) + if isinstance(tensor_meta, dict) and tensor_meta.get( + "is_constant" + ): + return tensor_meta.get("tensor") + + # Immediate constants are encoded as "imm__k" where + # the first underscore in stands in for the decimal point + # (e.g. "imm_0_044715_k1" -> 0.044715). dag_ir meta is the primary + # source; this name parsing is a best-effort fallback. + if not name.startswith("imm_"): + return None + + value_part, _, _ = name[len("imm_") :].rpartition("_k") + if not value_part: + return None + try: + return float(value_part.replace("_", ".", 1)) + except ValueError: + return None + + def render_argument_type( + name: str, + t: CutlassArgType, + constant_value: float | int | None = None, + ) -> None: + if constant_value is None and name not in name_to_buffer: + # An imm_* node is an immediate constant whose value we + # failed to recover (dag_ir meta missing AND name parsing + # failed, e.g. an unsupported encoding). Emitting an empty + # struct here would silently drop the constant and produce a + # numerically wrong kernel, so fail loudly instead. + if name.startswith("imm_"): + raise RuntimeError( + f"Could not recover the value of immediate constant " + f"node {name!r} for the CUTLASS EVT epilogue. " + f"Refusing to emit an empty argument that would " + f"silently drop the constant." + ) + # Other non-buffer nodes (e.g. autogen_identity_*/compute_* + # placeholders) legitimately render as an empty struct, + # matching CUTLASS reference EVT kernels. + buffer.writeline(f"{{}}, /* {name} */") + return + if issubclass(t, ctypes.c_byte): + buffer.writeline(f"{{}}, /* {name} */") + else: + fields = [ + ( + fname, + _get_arg_from_node( + ty, + name_to_buffer.get(name), + size_hint_fn, + arg_renames, + constant_value, + ), + ) + for fname, ty in t._fields_ + ] + field_strs = [ + f"/* {fname} */ {str(field)}" for fname, field in fields + ] + buffer.writeline(f"{{{', '.join(field_strs)}}}, /* {name} */") + + def render_thread_type(name: str, t: CutlassArgType) -> None: + if is_nested_visitor_type(t): + buffer.writeline(f"{{ /* {name} */") + with buffer.indent(): + for name, inner_t in t._fields_: + render_thread_type(name, inner_t) + buffer.writeline("},") + else: + render_argument_type(name, t, get_constant_value(name)) + + # unroll the recursion once to address special case formatting + # namely, no ending comma and no indentation for the outermost thread type + buffer.writeline("{ /* thread */") + with buffer.indent(3): + if is_nested_visitor_type(epilogue_thread_type): + with buffer.indent(): + for name, inner_t in epilogue_thread_type._fields_: + render_thread_type(name, inner_t) + else: + render_argument_type("thread", epilogue_thread_type) + buffer.writeline("}") + + return buffer.getvalue(), arg_renames + + def _get_arg_from_node( + arg_ty: type, + node: Buffer | None, + size_hint_fn: Callable[[Expr | int], int], + arg_renames: EVTArgRenames, + constant_value: float | int | None = None, + ) -> str: + from ..template import CUTLASSTemplate + + # Today, arguments are either a pointer to the + # node's memory, a stride tuple, the datatype + # Once again, need to check for local class type for stride tuple + if ( + str(arg_ty) + == ".TupleType'>" + ): + if constant_value is not None: + raise NotImplementedError( + "Immediate constants do not use tuple argument types" + ) + DEFAULT_STRIDE_LEN = 3 + if node is None: + raise AssertionError("node must not be None for tuple argument types") + if len(node.get_layout().stride) > DEFAULT_STRIDE_LEN: + raise AssertionError( + f"expected stride length <= {DEFAULT_STRIDE_LEN}, " + f"got {len(node.get_layout().stride)}" + ) + stride = [size_hint_fn(x) for x in node.get_layout().stride] + for _ in range(DEFAULT_STRIDE_LEN - len(stride)): + stride.append(0) + + def render_stride(x: int) -> str: + # Handle EBO for 0 and 1 + if x == 0: + return "_0{}" + elif x == 1: + return "_1{}" + else: + return str(x) + + return f"{{{', '.join([render_stride(x) for x in stride])}}}" + + elif issubclass(arg_ty, ctypes.c_void_p): + if constant_value is not None: + return "nullptr" + if node is None: + raise AssertionError("node must not be None for pointer argument") + name = arg_renames.new_name(node.get_name()) + return f"({CUTLASSTemplate._DTYPE_TO_CUTLASS[node.get_layout().dtype]}*) ({name} + {name}_offset)" + elif ( + arg_ty in _CUTLASS_C_DTYPES + ): # Assumption: this is the element dtype, this holds for all cutlass ir nodes currently + if constant_value is not None: + return str(constant_value) + if node is None: + raise AssertionError("node must not be None for dtype argument") + return f"{CUTLASSTemplate._DTYPE_TO_CUTLASS[node.get_layout().dtype]}(0)" + elif issubclass(arg_ty, EmptyByte): + return "{}" + + raise NotImplementedError(f"Unsupported arg type: {arg_ty}") diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/gemm_operation_extensions.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/gemm_operation_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..dc0aba5f1413c3fed6ced83f23b3e9895e140358 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/gemm_operation_extensions.py @@ -0,0 +1,418 @@ +# mypy: ignore-errors +from ..utils import try_import_cutlass + + +# copied / modified from original at +# https://github.com/NVIDIA/cutlass/blob/8783c41851cd3582490e04e69e0cd756a8c1db7f/tools/library/scripts/gemm_operation.py#L658 + +if try_import_cutlass(): + import enum + + from cutlass_library.gemm_operation import * # noqa: F403 + from cutlass_library.library import * # noqa: F403 + + _LOGGER = logging.getLogger(__name__) + + class EmitGemmUniversal3xInstanceWithEVT: + """Responsible for emitting a CUTLASS 3.x template definition""" + + def __init__(self, operation_suffix="", evt_name=None, device_type="cuda"): + self.operation_suffix = operation_suffix + self.includes = [ + "cutlass/cutlass.h", + "cutlass/gemm/gemm.h", + "cutlass/numeric_types.h", + "cutlass/gemm/kernel/gemm_universal.hpp", + "cutlass/gemm/collective/collective_builder.hpp", + "cutlass/epilogue/collective/collective_builder.hpp", + ] + self.builtin_epilogue_functor_template = """${epilogue_functor}< + ${element_d}, + ${element_epilogue}, + ${element_c}, + ${element_epilogue} + >""" + self.evt_name = evt_name + self.device_type = device_type + self.gemm_template = """ +using ${operation_name}_epilogue = +typename cutlass::epilogue::collective::CollectiveBuilder< + ${arch}, ${opcode_class_epi}, + cute::Shape, + cute::Shape<${cluster_shape_m}, ${cluster_shape_n}, ${cluster_shape_k}>, + ${epi_tile_mn}, + ${element_accumulator}, ${element_epilogue}, + ${element_c}, ${layout_c}, ${align_c}, + ${element_d}, ${layout_d}, ${align_d}, + ${epilogue_schedule}, + ${epilogue_functor} +>::CollectiveOp; + +${mixed_dtype_prepare_code} + +using ${operation_name}_mainloop = +typename cutlass::gemm::collective::CollectiveBuilder< + ${arch}, ${opcode_class_main}, + ${element_a}, ${layout_a}, ${align_a}, + ${element_b}, ${layout_b}, ${align_b}, + ${element_accumulator}, + cute::Shape, + cute::Shape<${cluster_shape_m}, ${cluster_shape_n}, ${cluster_shape_k}>, + ${stages}, + ${kernel_schedule} +>::CollectiveOp; + +// Gemm operator ${operation_name} +using ${operation_name}_base = cutlass::gemm::kernel::GemmUniversal< + ${problem_shape}, + ${operation_name}_mainloop, + ${operation_name}_epilogue, + ${tile_scheduler}>; + +// Define named type +struct ${operation_name} : +public ${operation_name}_base { }; + + """ + + # + def instance_template(self): + return """ +${compile_guard_start} +{ + using GemmKernel = cutlass::gemm::device::GemmUniversalAdapter<${operation_name}>; + manifest.append( + new ${gemm_kind}("${operation_name}")); +} +${compile_guard_end} + """ + + def emit_block_scale_epilogue_functor(self, operation): + block_scaled_template = """ + ${epilogue_functor}< + ${epi_vs}, + ${element_d}, + ${element_accumulator}, + ${element_sfd}, + ${layout_sfd}, + ${element_c}, + ${element_scalar} + > + """ + block_scaled_values = { + "epi_vs": str(operation.ScaleFactorVectorSize), + "element_d": str(DataTypeTag[operation.D.element]), + "element_sfd": str(DataTypeTag[operation.ScaleFactorD.element]), + "layout_sfd": LayoutTag[operation.ScaleFactorD.layout], + "epilogue_functor": EpilogueFunctor3xTag[ + EpilogueFunctor3x.LinearCombinationBlockScaleFactor + ], + "element_accumulator": str(DataTypeTag[operation.accumulator_type()]), + "element_scalar": str(DataTypeTag[operation.accumulator_type()]), + "element_c": str(DataTypeTag[operation.C.element]), + } + return SubstituteTemplate(block_scaled_template, block_scaled_values) + + @staticmethod + def pointerize_if_grouped(operation, layout): + return layout if not is_grouped(operation.gemm_kind) else layout + "* " + + @staticmethod + def problem_shape(operation): + gemm_shape_type = "cute::Shape" + grouped_gemm_shape_type = "cute::Shape" + grouped_gemm_shape_type = ( + "cutlass::gemm::GroupProblemShape<" + grouped_gemm_shape_type + ">" + ) + + return ( + gemm_shape_type + if not is_grouped(operation.gemm_kind) + else grouped_gemm_shape_type + ) + + def emit(self, operation): + """Given a gem operation, emits a template definition of the operation""" + + opcode_class_main = operation.tile_description.math_instruction.opcode_class + opcode_class_epi = opcode_class_main + + tile_shape = operation.tile_description.tile_shape + instruction_shape = ( + operation.tile_description.math_instruction.instruction_shape + ) + cluster_m = operation.tile_description.cluster_shape[0] + cluster_n = operation.tile_description.cluster_shape[1] + + tile_shape_m, tile_shape_n, tile_shape_k = tile_shape + + # account for static/dynamic cluster shapes + cta_m = tile_shape[0] // cluster_m if cluster_m > 0 else tile_shape[0] + cta_n = tile_shape[1] // cluster_n if cluster_n > 0 else tile_shape[1] + + # Shape passed to epilogue builder + is_sm100_kernel = operation.arch == 100 + if is_sm100_kernel: + cta_m_per_mma_instruction = ( + 2 if "2sm" in operation.procedural_name() else 1 + ) + if cluster_m <= 0: + cta_m = cta_m // cta_m_per_mma_instruction + + if opcode_class_main in [ + OpcodeClass.TensorOp, + OpcodeClass.BlockScaledTensorOp, + ]: + tile_shape_m = instruction_shape[0] + tile_shape_n = instruction_shape[1] + + # stage count set to zero indicates builder automatic stage selection + if operation.tile_description.stages > 0: + stage_count_string = f"cutlass::gemm::collective::StageCount<\ +{str(operation.tile_description.stages)}>" + else: + stage_count_string = ( + f"cutlass::gemm::collective::StageCountAutoCarveout(\ +sizeof(typename {str(operation.procedural_name())}_epilogue::SharedStorage))>" + ) + if self.device_type == "xpu": + stage_count_string = "cutlass::gemm::collective::StageCountAuto" + + epi_tile_mn = "cutlass::epilogue::collective::EpilogueTileAuto" + + ( + instance_layout_A, + instance_layout_B, + instance_layout_C, + instance_layout_D, + ) = ( + operation.A.layout, + operation.B.layout, + operation.C.layout, + operation.D.layout, + ) + + # 3.0 profiler integration only supports trivial epilogues for now + epilogue_vector_length = 1 + + # Support built-in epilogue functors or user-defined functions + if isinstance(operation.epilogue_functor, enum.Enum): + values = { + "element_epilogue": str(DataTypeTag[operation.element_epilogue]), + "epilogue_functor": EpilogueFunctor3xTag[ + operation.epilogue_functor + ], + } + epilogue_functor = SubstituteTemplate( + self.builtin_epilogue_functor_template, values + ) + + if ( + is_block_scaled(operation.gemm_kind) + and operation.ScaleFactorD.element != DataType.void + ): + epilogue_functor = self.emit_block_scale_epilogue_functor(operation) + else: + epilogue_functor = self.epilogue_functor.emit_declaration() + + if ( + is_block_scaled(operation.gemm_kind) + and operation.ScaleFactorD.element != DataType.void + ): + epilogue_functor = self.emit_block_scale_epilogue_functor(operation) + + # + # Cutlass3x complex kernels' ElementA(B) is a tuple in collective mainloop builder, + # e.g. cute::tuple, Transform : cute::identity / cute::conjugate. + element_a = ( + DataTypeTag[operation.A.element] + if not operation.is_complex() + else f"cute::tuple<{str(DataTypeTag[operation.A.element])},\ +{str(ComplexTransformTag3x[operation.A.complex_transform])}>" + ) + element_b = ( + DataTypeTag[operation.B.element] + if not operation.is_complex() + else f"cute::tuple<{str(DataTypeTag[operation.B.element])},\ +{str(ComplexTransformTag3x[operation.B.complex_transform])}>" + ) + epilogue_schedule_type = EpilogueScheduleTag[operation.epilogue_schedule] + + if opcode_class_main == OpcodeClass.BlockScaledTensorOp: + is_no_smem_epilogue = operation.epilogue_schedule in [ + EpilogueScheduleType.NoSmemWarpSpecialized1Sm, + EpilogueScheduleType.NoSmemWarpSpecialized2Sm, + ] + grouped = is_grouped(operation.gemm_kind) + if cta_n == 256 and operation.kernel_schedule == to_grouped_schedule( + KernelScheduleType.Nvf4TmaWarpSpecialized1SmSm100, grouped + ): + epi_tile_mn = "cute::Shape" + if not is_no_smem_epilogue: + epilogue_schedule_type = EpilogueScheduleTag[ + to_grouped_schedule( + EpilogueScheduleType.TmaWarpSpecialized1Sm, grouped + ) + ] + if cta_n == 256 and operation.kernel_schedule == to_grouped_schedule( + KernelScheduleType.Nvf4TmaWarpSpecialized2SmSm100, grouped + ): + epi_tile_mn = "cute::Shape" + if not is_no_smem_epilogue: + epilogue_schedule_type = EpilogueScheduleTag[ + to_grouped_schedule( + EpilogueScheduleType.TmaWarpSpecialized2Sm, grouped + ) + ] + element_a = f"cute::tuple<{str(element_a)},{str(DataTypeTag[operation.ScaleFactorA])}>" + element_b = f"cute::tuple<{str(element_b)},{str(DataTypeTag[operation.ScaleFactorB])}>" + + operation_name_str = operation.procedural_name() + layout_a_str = LayoutTag[instance_layout_A] + layout_b_str = LayoutTag[instance_layout_B] + mixed_dtype_prepare_code = "" + if operation.mixed_input_mode is not None: + A_dtype = operation.A.element + B_dtype = operation.B.element + A_dtype_bits = DataTypeSize[A_dtype] + B_dtype_bits = DataTypeSize[B_dtype] + is_A_dtype_narrow = A_dtype_bits < B_dtype_bits + if is_A_dtype_narrow: + narrow_dtype, wide_dtype = (A_dtype, B_dtype) + narrow_dtype_bits, wide_dtype_bits = (A_dtype_bits, B_dtype_bits) + else: + narrow_dtype, wide_dtype = (B_dtype, A_dtype) + narrow_dtype_bits, wide_dtype_bits = (B_dtype_bits, A_dtype_bits) + + narrow_tag = DataTypeTag[narrow_dtype] + wide_tag = DataTypeTag[wide_dtype] + scale_tag = DataTypeTag[wide_dtype] + zero_tag = DataTypeTag[wide_dtype] + + do_shuffle = False + value_shuffle_str = "" + if narrow_dtype_bits == 4 and wide_dtype_bits == 16: + value_shuffle_str = "cute::Layout, \ +cute::Stride>" + do_shuffle = True + if narrow_dtype_bits == 8 and wide_dtype_bits == 16: + value_shuffle_str = "cute::Layout, \ +cute::Stride>" + do_shuffle = True + do_shuffle = operation.mixed_input_shuffle and do_shuffle + + if do_shuffle: + if is_A_dtype_narrow: + stride_narrow_str = ( + f"cutlass::detail::TagToStrideA_t<{layout_a_str}>" + ) + layout_a_str = f"{operation_name_str}_LayoutNarrowReordered" + else: + stride_narrow_str = ( + f"cutlass::detail::TagToStrideB_t<{layout_b_str}>" + ) + layout_b_str = f"{operation_name_str}_LayoutNarrowReordered" + # The {operation_name_str}_ prefixes in mixed_dtype_prepare_code and + # layout_{a, b}_str are to prevent errors in Windows platform unity build + mixed_dtype_prepare_code = f""" + using {operation_name_str}_StrideNarrow = {stride_narrow_str}; + using {operation_name_str}_ValueShuffle = {value_shuffle_str}; + static constexpr int {operation_name_str}_NumShuffleAtoms = 1; + using {operation_name_str}_MmaAtomShape = \ +cute::Layout>>; + using {operation_name_str}_LayoutAtomQuant = \ +decltype(cutlass::compute_memory_reordering_atom<{wide_tag}, {operation_name_str}_MmaAtomShape, \ +{operation_name_str}_ValueShuffle>()); + using {operation_name_str}_LayoutNarrowReordered = \ +decltype(cute::tile_to_shape({operation_name_str}_LayoutAtomQuant{{}}, \ +cute::Layout, {operation_name_str}_StrideNarrow>{{}})); + """ + + mixed_input_modes_to_element = { + MixedInputMode.ConvertOnly: narrow_tag, + MixedInputMode.ScaleOnly: f"cute::tuple<{narrow_tag}, {scale_tag}>", + MixedInputMode.ScaleWithZeroPoint: f"cute::tuple<{narrow_tag}, {scale_tag}, {zero_tag}>", + } + narrow_element = mixed_input_modes_to_element.get( + operation.mixed_input_mode, narrow_tag + ) + + if narrow_dtype == DataType.s4 and ( + wide_dtype == DataType.e4m3 or wide_dtype == DataType.e5m2 + ): + narrow_element = ( + f"cute::tuple<{narrow_tag}, cutlass::Array<{scale_tag}, 8>>" + ) + + if is_A_dtype_narrow: + element_a = narrow_element + else: + element_b = narrow_element + + if self.evt_name: + epilogue_functor = self.evt_name + + if self.device_type == "xpu": + arch = f"cutlass::arch::Xe{operation.arch}" + else: + arch = f"cutlass::arch::Sm{operation.arch}" + + values = { + "operation_name": operation_name_str, + "operation_suffix": self.operation_suffix, + "problem_shape": self.problem_shape(operation), + "element_a": element_a, + "layout_a": self.pointerize_if_grouped(operation, layout_a_str), + "element_b": element_b, + "layout_b": self.pointerize_if_grouped(operation, layout_b_str), + "element_c": DataTypeTag[operation.C.element], + "layout_c": self.pointerize_if_grouped( + operation, LayoutTag[instance_layout_C] + ), + "element_d": DataTypeTag[operation.D.element], + "layout_d": self.pointerize_if_grouped( + operation, LayoutTag[instance_layout_D] + ), + "element_accumulator": DataTypeTag[operation.accumulator_type()], + "opcode_class_main": OpcodeClassTag[opcode_class_main], + "opcode_class_epi": OpcodeClassTag[opcode_class_epi], + "arch": arch, + "tile_shape_m": str(tile_shape_m), + "tile_shape_n": str(tile_shape_n), + "tile_shape_k": str(tile_shape_k), + "cluster_shape_m": "cute::_" + + str(operation.tile_description.cluster_shape[0]) + if operation.tile_description.cluster_shape[0] > 0 + else "int", + "cluster_shape_n": "cute::_" + + str(operation.tile_description.cluster_shape[1]) + if operation.tile_description.cluster_shape[1] > 0 + else "int", + "cluster_shape_k": "cute::_" + + str(operation.tile_description.cluster_shape[2]) + if operation.tile_description.cluster_shape[2] > 0 + else "int", + "instruction_shape_m": str(instruction_shape[0]), + "instruction_shape_n": str(instruction_shape[1]), + "instruction_shape_k": str(instruction_shape[2]), + "kernel_schedule": str(KernelScheduleTag[operation.kernel_schedule]), + "epilogue_schedule": str(epilogue_schedule_type), + "epi_tile_mn": epi_tile_mn, + "epilogue_functor": epilogue_functor, + "stages": stage_count_string, + "align_a": str(operation.A.alignment), + "align_b": str(operation.B.alignment), + "align_c": str(operation.C.alignment), + "align_d": str(operation.D.alignment), + "transform_a": ComplexTransformTag[operation.A.complex_transform], + "transform_b": ComplexTransformTag[operation.B.complex_transform], + "math_operation": MathOperationTag[ + operation.tile_description.math_instruction.math_operation + ], + "epilogue_vector_length": str(epilogue_vector_length), + "element_epilogue": str(DataTypeTag[operation.element_epilogue]), + "tile_scheduler": str(TileSchedulerTag[operation.tile_scheduler]), + "mixed_dtype_prepare_code": mixed_dtype_prepare_code, + } + + return SubstituteTemplate(self.gemm_template, values) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/python_evt.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/python_evt.py new file mode 100644 index 0000000000000000000000000000000000000000..ef472ff97f08e94369f3d7c5dd5b6e27f003f092 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/python_evt.py @@ -0,0 +1,663 @@ +import ast +import itertools +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from contextlib import contextmanager +from dataclasses import dataclass +from os import linesep +from typing import Any + +import sympy + +import torch +import torch._inductor.virtualized as virtualized +from torch._inductor.ir import ComputedBuffer, Pointwise +from torch._inductor.ops_handler import DefaultHandler, WrapperHandler +from torch._inductor.scheduler import BaseSchedulerNode +from torch._inductor.utils import DelayReplaceLine, IndentedBuffer, OrderedSet +from torch._inductor.virtualized import OpsValue + +from ...virtualized import V + + +_ACCUMULATOR_ARG_NAME = "accum" + +# 1/sqrt(2) (M_SQRT1_2), the constant Inductor's gelu decomposition multiplies +# the input by before applying erf. +_GELU_ERF_INV_SQRT2 = 0.7071067811865476 + + +def _is_close_constant(node: ast.expr, value: float, tol: float = 1e-6) -> bool: + return ( + isinstance(node, ast.Constant) + and isinstance(node.value, (int, float)) + and not isinstance(node.value, bool) + and abs(float(node.value) - value) < tol + ) + + +def _mult_factors(node: ast.expr) -> list[ast.expr]: + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mult): + return _mult_factors(node.left) + _mult_factors(node.right) + return [node] + + +def _match_call(node: ast.expr, name: str) -> "ast.Call | None": + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == name + and len(node.args) == 1 + ): + return node + return None + + +def _same(a: ast.expr, b: ast.expr) -> bool: + return ast.dump(a) == ast.dump(b) + + +def _match_gelu_erf(node: ast.expr) -> "ast.expr | None": + """Match gelu's erf decomposition ``x * 0.5 * (1 + erf(x / sqrt(2)))`` and + return the inner argument ``x``. Matching is commutativity-aware for the + multiplications and the addition. + """ + factors = _mult_factors(node) + if len(factors) != 3: + return None + half = next((f for f in factors if _is_close_constant(f, 0.5)), None) + if half is None: + return None + rest = [f for f in factors if f is not half] + + def match_one_plus_erf(f: ast.expr) -> "ast.expr | None": + # Match ``1 + erf(x / sqrt(2))`` and return ``x``. + if not (isinstance(f, ast.BinOp) and isinstance(f.op, ast.Add)): + return None + operands = [f.left, f.right] + if not any(_is_close_constant(o, 1.0) for o in operands): + return None + erf_call = next( + (c for c in (_match_call(o, "erf") for o in operands) if c is not None), + None, + ) + if erf_call is None: + return None + erf_factors = _mult_factors(erf_call.args[0]) + if len(erf_factors) != 2 or not any( + _is_close_constant(g, _GELU_ERF_INV_SQRT2) for g in erf_factors + ): + return None + return next( + g for g in erf_factors if not _is_close_constant(g, _GELU_ERF_INV_SQRT2) + ) + + # ``x`` may itself be an addition (e.g. gelu(accum + bias)), so identify the + # ``1 + erf(...)`` factor by structure rather than assuming it is the only Add. + for i, f in enumerate(rest): + erf_x = match_one_plus_erf(f) + if erf_x is not None and _same(erf_x, rest[1 - i]): + return rest[1 - i] + return None + + +def _match_silu(node: ast.expr) -> "ast.expr | None": + """Match SiLU decomposition ``x / (1 + exp(0.0 - x))`` and return ``x``. + + Inductor decomposes silu(x) as x / (1 + exp(-x)). With our neg() op + emitting (0.0 - x), the generated code is: x / (1.0 + exp((0.0 - x))). + """ + # Must be a division: x / denom + if not (isinstance(node, ast.BinOp) and isinstance(node.op, ast.Div)): + return None + x = node.left + denom = node.right + + # denom must be: 1.0 + exp(neg_x) or exp(neg_x) + 1.0 + if not (isinstance(denom, ast.BinOp) and isinstance(denom.op, ast.Add)): + return None + + operands = [denom.left, denom.right] + one = next((o for o in operands if _is_close_constant(o, 1.0)), None) + if one is None: + return None + exp_part = next((o for o in operands if o is not one), None) + if exp_part is None: + return None + + # exp_part must be exp(neg_x) + exp_call = _match_call(exp_part, "exp") + if exp_call is None: + return None + neg_x = exp_call.args[0] + + # neg_x must be (0.0 - x) where x matches the numerator + if ( + isinstance(neg_x, ast.BinOp) + and isinstance(neg_x.op, ast.Sub) + and _is_close_constant(neg_x.left, 0.0) + and _same(neg_x.right, x) + ): + return x + + # Also handle unary minus: -x + if isinstance(neg_x, ast.UnaryOp) and isinstance(neg_x.op, ast.USub): + if _same(neg_x.operand, x): + return x + + return None + + +@dataclass(frozen=True) +class _ActivationPattern: + # ``name`` must be a functor the CUTLASS EVT frontend binds natively (see + # ``ast_op_to_bindings`` in the cutlass python_ast frontend). + name: str + # Cheap substring guard so we only parse epilogues that may contain the + # decomposition (a primitive that the activation expands into). + trigger: str + match: Callable[[ast.expr], "ast.expr | None"] + + +# Activations that Inductor decomposes but CUTLASS can emit as a single functor. +# Add new entries here to re-fuse additional decomposed activations. +_ACTIVATION_PATTERNS: tuple[_ActivationPattern, ...] = ( + _ActivationPattern("gelu", "erf", _match_gelu_erf), + _ActivationPattern("silu", "0.0 -", _match_silu), +) + + +def _fuse_activations(code: str) -> str: + """Re-compose decomposed activations back into single CUTLASS functor calls. + + Inductor lowers activations such as ``aten.gelu`` into + primitive ops (``erf``, ``sigmoid``, ``mul``, ...) before reaching CUTLASS + codegen. The CUTLASS EVT frontend natively supports a number of activation + functors, so we pattern-match each decomposition (``_ACTIVATION_PATTERNS``) + and fold it back into a single activation node. This enables fusion for + activations whose primitives are unsupported (e.g. the ``erf`` in gelu) and + reduces the compute-node count for the rest. + """ + active = [p for p in _ACTIVATION_PATTERNS if p.trigger in code] + if not active: + return code + try: + tree = ast.parse(code) + except SyntaxError: + return code + if not tree.body or not isinstance(tree.body[0], ast.FunctionDef): + return code + func = tree.body[0] + + assigns: dict[str, ast.expr] = {} + for stmt in func.body: + if ( + isinstance(stmt, ast.Assign) + and len(stmt.targets) == 1 + and isinstance(stmt.targets[0], ast.Name) + ): + assigns[stmt.targets[0].id] = stmt.value + + _EMPTY_SET: OrderedSet[str] = OrderedSet() + + def inline(node: ast.expr, seen: OrderedSet[str] | None = None) -> ast.expr: + if seen is None: + seen = _EMPTY_SET + # Fully inline temporary assignments so the expression tree only refers + # to function parameters (accum / read buffers) and literal constants. + if isinstance(node, ast.Name) and node.id in assigns: + if node.id in seen: + return node + return inline(assigns[node.id], seen | OrderedSet([node.id])) + if isinstance(node, ast.BinOp): + return ast.BinOp( + left=inline(node.left, seen), + op=node.op, + right=inline(node.right, seen), + ) + if isinstance(node, ast.UnaryOp): + return ast.UnaryOp(op=node.op, operand=inline(node.operand, seen)) + if isinstance(node, ast.Call): + return ast.Call( + func=node.func, + args=[inline(a, seen) for a in node.args], + keywords=[], + ) + return node + + changed = False + for stmt in func.body: + if ( + isinstance(stmt, ast.Assign) + and len(stmt.targets) == 1 + and isinstance(stmt.targets[0], ast.Name) + ): + inlined = inline(stmt.value) + for pattern in active: + x = pattern.match(inlined) + if x is not None: + stmt.value = ast.Call( + func=ast.Name(id=pattern.name, ctx=ast.Load()), + args=[x], + keywords=[], + ) + changed = True + break + + if not changed: + return code + + # The folded assignment no longer references the decomposition temporaries, + # so drop the now-dead intermediates (the CUTLASS frontend builds a compute + # node for every assignment it sees). The frontend emits ``return`` dedented + # to module level (a sibling of the function def in Python 3.12), so seed + # liveness from every Return in the tree, not only those inside ``func.body``. + live: OrderedSet[str] = OrderedSet() + for node in ast.walk(tree): + if isinstance(node, ast.Return) and node.value is not None: + live.update(n.id for n in ast.walk(node.value) if isinstance(n, ast.Name)) + + kept: list[ast.stmt] = [] + for stmt in reversed(func.body): + if ( + isinstance(stmt, ast.Assign) + and len(stmt.targets) == 1 + and isinstance(stmt.targets[0], ast.Name) + ): + if stmt.targets[0].id not in live: + continue + live.update(n.id for n in ast.walk(stmt.value) if isinstance(n, ast.Name)) + kept.append(stmt) + func.body = list(reversed(kept)) + + folded = ast.unparse(ast.fix_missing_locations(tree)) + + # After dead-code elimination, any activation primitive that served as a + # trigger (e.g. erf) should no longer appear in the live code -- it was + # consumed by the pattern match and eliminated. If one still appears, the + # fold was incomplete (e.g. a standalone erf not part of a known pattern); + # bail out and return the original code so the CUTLASS frontend rejects the + # epilogue cleanly rather than emitting an unsupported functor. + for p in active: + if p.trigger in folded: + return code + + return folded + + +def scaled_mm_evt( + scale_A_name: str, scale_B_name: str, bias_name: str | None, output_name: str +) -> tuple[list[str], dict[str, Any], str]: + evt_read_names = [scale_A_name, scale_B_name] + var_name_to_buffer_name = {n: n for n in [scale_A_name, scale_B_name]} + var_name_to_buffer_name["D"] = output_name + var_name_to_buffer_name[_ACCUMULATOR_ARG_NAME] = output_name + expr = f"accum * {scale_A_name} * {scale_B_name}{linesep}" + if bias_name: + expr = f"({expr}) + {bias_name}" + evt_read_names.append(bias_name) + var_name_to_buffer_name[bias_name] = bias_name + + evt_py_code = f"def fn(accum, {','.join(evt_read_names)}):{linesep}\ + D = {expr}{linesep}\ + return D{linesep}" + + return evt_read_names, var_name_to_buffer_name, evt_py_code + + +class CutlassEVTOpsMixIn: + @staticmethod + def _infix_bin_op(op: str, a: str, b: str) -> str: + return f"{a} {op} {b}" + + @staticmethod + def _prefix_bin_op(op: str, a: str, b: str) -> str: + return f"{op}({a}, {b})" + + @staticmethod + def _prefix_un_op(op: str, a: str) -> str: + return f"{op}({a})" + + @staticmethod + def to_dtype( + x: str, + dtype: Any, + src_dtype: torch.dtype | None = None, + use_compute_types: bool = False, + ) -> str: + return x + + @staticmethod + def constant(value: Any, dtype: Any) -> str: + # Return the constant as a Python float literal so the EVT python code + # string can embed it directly (e.g. for the 0.5 and 1/sqrt(2) factors + # in gelu). The CUTLASS EVT frontend will render it as a C++ scalar. + # Only numeric constants appear here (Inductor does not lower non-numeric + # constants into pointwise epilogues). + return str(float(value)) + + @staticmethod + def neg(x0: str) -> str: + # Use subtraction from zero instead of unary minus because the + # CUTLASS PythonASTFrontend has visit_BinOp but no visit_UnaryOp. + return f"(0.0 - {x0})" + + @staticmethod + def mul(x0: str, x1: str) -> str: + return CutlassEVTOpsMixIn._infix_bin_op("*", x0, x1) + + @staticmethod + def truediv(x0: str, x1: str) -> str: + return CutlassEVTOpsMixIn._infix_bin_op("/", x0, x1) + + @staticmethod + def ge(x0: str, x1: str) -> str: + raise NotImplementedError + + @staticmethod + def add(x0: str, x1: str) -> str: + return CutlassEVTOpsMixIn._infix_bin_op("+", x0, x1) + + @staticmethod + def relu(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("relu", x0) + + @staticmethod + def sigmoid(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("sigmoid", x0) + + @staticmethod + def sub(x0: str, x1: str) -> str: + return CutlassEVTOpsMixIn._infix_bin_op("-", x0, x1) + + @staticmethod + def tanh(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("tanh", x0) + + @staticmethod + def exp(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("exp", x0) + + @staticmethod + def erf(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("erf", x0) + + @staticmethod + def silu(x0: str) -> str: + return CutlassEVTOpsMixIn._prefix_un_op("silu", x0) + + +class MockCutlassHandler(CutlassEVTOpsMixIn, WrapperHandler): + """Passthrough handler for cutlass ops, used for running epilogue nodes for memory planning""" + + +class _AssignmentFormatter(DefaultHandler): + def __init__(self, parent_handler: "CutlassEVTCodegen"): + self.parent_handler = parent_handler + + def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any: + # Handle op dispatch here + if hasattr(self.parent_handler, name): + fn = getattr(self.parent_handler, name) + line = fn(*args, **kwargs) + if name in ("load", "store"): + return OpsValue(line) + else: + var = self.parent_handler._tmp_var() + line = DelayReplaceLine( + var, + lambda: "D" + if var == self.parent_handler.last_stored_var_name + else var, + f"{var} = {line}", + ) + self.parent_handler.body.writeline(line) + return OpsValue(var) + else: + raise NotImplementedError(name) + + +class CutlassEVTCodegen(CutlassEVTOpsMixIn): + """ + Notes: + * Used by CUTLASSGemmTemplate. + * This class should not be instantiated by users, it is intended to be used + by calling CutlassEVTCodegen.ir_to_evt_python_code(...) + which instantiates this class as an ops handler for virtualized.V.ops.[op-name] + * Extend this with more _op_ nodes to add support for new pointwise operations. + """ + + def __init__(self, accumulator_node_name: str, removed_buffers: OrderedSet[str]): + """ + + Initializes a CutlassEVTEpilogueArgumentFormatter object. Do not instantiate directly. + Use the CutlassEVTCodegen.ir_to_evt_python_code static method. + + Args: + accumulator_node_name: The name of the accumulator node which should contain + the Matmul result before fusion according to the IR graph. + epilogue_nodes: The list of scheduler nodes to be fused into the epilogue + """ + self.accumulator_node_name: str = accumulator_node_name # + self.body: IndentedBuffer = IndentedBuffer(1) # The body buffer for codegen + self.var_counter: Iterator[int] = itertools.count() + self.store_name_to_value: dict[ + str, OpsValue + ] = {} # Aliases for subexpression functors + self.reads: OrderedSet[str] = OrderedSet([]) + # Used for creating example tensors + self.var_name_to_buffer_name: dict[str, str] = { + _ACCUMULATOR_ARG_NAME: accumulator_node_name + } + self.removed_buffers: OrderedSet[str] = removed_buffers + self.cur_node: ComputedBuffer | None = None + self.name_to_buffer = V.graph.name_to_buffer | V.graph.graph_inputs + for name in V.graph.constants: + # pyrefly: ignore [unsupported-operation] + self.name_to_buffer[name] = V.graph.add_tensor_constant( + V.graph.constants[name], name + ) + self.is_D_assigned = False + self.D_var_name = None + + if accumulator_node_name not in removed_buffers: + # cannot return accumulator directly, so alias it + var = self._tmp_var() + self.body.writeline(f"{var} = {_ACCUMULATOR_ARG_NAME}") + self.store(accumulator_node_name, value=OpsValue(var)) + + @staticmethod + def ir_to_evt_python_code( + cutlass_template_node_name: str, + epilogue_nodes: list[BaseSchedulerNode], + removed_buffers: OrderedSet[str], + fn_name: str = "fn", + as_standalone_function: bool = False, + ) -> tuple[list[str], list[str], dict[str, Any], str]: + codegen = CutlassEVTCodegen(cutlass_template_node_name, removed_buffers) + handler = _AssignmentFormatter(codegen) + + with virtualized.V.set_ops_handler(handler): + for s_node in epilogue_nodes: + node = s_node.node + if not isinstance(node, ComputedBuffer): + raise AssertionError( + f"expected node to be a ComputedBuffer, got {type(node)}" + ) + with codegen.set_cur_node(node): + index_vars = CutlassEVTCodegen.get_index_vars(node) + node.get_store_function()(index_vars) + + codegen.finalize() + + return ( + codegen.get_reads(), + codegen.get_writes(), + codegen.get_renames(), + codegen.get_value( + fn_name=fn_name, + as_standalone_function=as_standalone_function, + ), + ) + + def get_value( + self, + fn_name: str = "fn", + as_standalone_function: bool = False, + ) -> str: + ret = self._render_return_statement() + if as_standalone_function: + ret = " " + ret + return _fuse_activations( + linesep.join( + [ + self._render_input_signature(fn_name), + self.body.getvalue(), + ret, + ] + ) + ) + + def finalize(self) -> None: + # Rename the last store to D + # no other code references this store + # to workaround https://github.com/NVIDIA/cutlass/issues/2288 + # Note: the delayed line will automatically rewrite the last assignment to + # be to D + buffer_name = self.var_name_to_buffer_name[self.last_stored_var_name] + self.var_name_to_buffer_name.pop(self.last_stored_var_name) + self.var_name_to_buffer_name["D"] = buffer_name + self.store_name_to_value[buffer_name] = OpsValue("D") + + @contextmanager + def set_cur_node(self, node: ComputedBuffer) -> Generator[None, Any, Any]: + prev_node = self.cur_node + try: + self.cur_node = node + yield + finally: + self.cur_node = prev_node + + def get_renames(self) -> dict[str, str]: + return dict(self.var_name_to_buffer_name) + + def get_reads(self) -> list[str]: + return list(self.reads.difference(self.store_name_to_value.keys())) + + def get_writes(self) -> list[str]: + return list(self.store_name_to_value.keys()) + + def load(self, name: str, index: Any) -> str: + self._check_indexing(name, index) + if name in self.store_name_to_value: + return self.store_name_to_value[name].value + elif name == self.accumulator_node_name: + return _ACCUMULATOR_ARG_NAME + else: + self.reads.add(name) + self.var_name_to_buffer_name[name] = name + return name + + def store( + self, name: Any, index: Any = None, value: Any = None, mode: Any = None + ) -> None: + if name not in self.removed_buffers: + if index: + self._check_indexing(name, index) + if value.value == _ACCUMULATOR_ARG_NAME: + raise AssertionError("Cannot store accumulator arg name") + self.var_name_to_buffer_name[value.value] = name + self.store_name_to_value[name] = value + self.last_stored_var_name = value.value + return None + + def _get_cur_node(self) -> ComputedBuffer: + if not self.cur_node: + raise AssertionError("expected cur_node to be set") + return self.cur_node + + @staticmethod + def get_index_vars(node: ComputedBuffer) -> Sequence[sympy.Expr]: + data = node.data + # TODO mlazos: relax this, cutlass supports reductions and other ops + if not isinstance(data, Pointwise): + raise AssertionError(f"expected data to be Pointwise, got {type(data)}") + return data._index(data.ranges) + + def _get_current_index_vars(self) -> Sequence[sympy.Expr]: + return self.get_index_vars(self._get_cur_node()) + + def _check_indexing(self, name: str, index: sympy.Expr) -> None: + # We only support indexing that matches the layout today because + # CUTLASS doesn't support arbitrary indexing + buffer_name = ( + self.accumulator_node_name if name == _ACCUMULATOR_ARG_NAME else name + ) + buffer = self.name_to_buffer[buffer_name] + index_strides = V.graph.sizevars.stride_vars( + index, self._get_current_index_vars() + ) + stride = buffer.get_layout().stride + if not self._stride_compatible(stride, index_strides): + raise NotImplementedError( + f"Unsupported indexing for {name} with index {index}, index strides {index_strides}, and layout stride {stride}" + ) + + def _stride_compatible( + self, left: Iterable[sympy.Expr], right: Iterable[sympy.Expr] + ) -> bool: + def _provably_equal_or_zero(a: sympy.Expr, b: sympy.Expr) -> bool: + # sympy.Eq can return an unevaluated Equality object; only accept + # cases sympy can prove true. + if a == b: + return True + if V.graph.sizevars.statically_known_equals(a, b): + return True + if V.graph.sizevars.statically_known_equals(a, 0): + return True + if V.graph.sizevars.statically_known_equals(b, 0): + return True + return ( + sympy.Eq(a, b) is sympy.true + or sympy.Eq(a, 0) is sympy.true + or sympy.Eq(b, 0) is sympy.true + ) + + left_list = list(left) + right_list = list(right) + # Same length: direct comparison + if len(left_list) == len(right_list): + return all( + _provably_equal_or_zero(lv, rv) for lv, rv in zip(left_list, right_list) + ) + # Different lengths: allow compatible reshapes where trailing strides match. + # This handles view/reshape between template output and consumer, e.g., + # buffer strides [3072, 1] vs index strides [1572864, 3072, 1] + shorter, longer = ( + (left_list, right_list) + if len(left_list) <= len(right_list) + else (right_list, left_list) + ) + n = len(shorter) + # Check that the trailing strides match + return all( + _provably_equal_or_zero(shorter[-(i + 1)], longer[-(i + 1)]) + for i in range(n) + ) + + def _render_input_signature(self, fn_name: str = "fn") -> str: + arguments = ", ".join( + [_ACCUMULATOR_ARG_NAME] + + [name for name in self.reads if name != self.accumulator_node_name] + ) + return f"def {fn_name}({arguments}):" + + def _render_return_statement(self) -> str: + return_vars = OrderedSet( + op_v.value for op_v in self.store_name_to_value.values() + ) + if "D" not in return_vars: + raise AssertionError(f"expected 'D' in return_vars, got {return_vars}") + return f"return {', '.join(return_vars)}" + + def _tmp_var(self) -> str: + return f"tmp_{next(self.var_counter)}" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..08be591d5d70b0b592e83ab5aa6544b18fb51a15 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/scheduling.py @@ -0,0 +1,389 @@ +# mypy: allow-untyped-defs +import hashlib +import logging +from collections.abc import Sequence +from typing import cast, TypeGuard + +import sympy + +from torch._inductor.codegen.cutlass.python_evt import ( + CutlassEVTCodegen, + MockCutlassHandler, +) +from torch._inductor.utils import Placeholder +from torch.utils._ordered_set import OrderedSet + +from ...._dynamo.utils import counters +from ... import config +from ...codecache import code_hash, get_path +from ...ir import Buffer, ComputedBuffer, CUTLASSTemplateBuffer, Pointwise +from ...scheduler import ( + BaseSchedulerNode, + BaseScheduling, + FusedSchedulerNode, + SchedulerNode, + WhyNoFuse, +) +from ...utils import get_fused_kernel_name, get_kernel_metadata, sympy_product +from ...virtualized import V +from ..common import BackendFeature, IndentedBuffer + + +log = logging.getLogger(__name__) + + +class WhyNoFuseNames(WhyNoFuse): + def __init__(self, name1: str, name2: str) -> None: + self.name1 = name1 + self.name2 = name2 + + +class CUTLASSScheduling(BaseScheduling): + """ + Partial Scheduling implementation for cutlass C++ Kernels. + This class is intended to be used in combination with TritonScheduling, + and delegated to by CUDACombinedScheduling/XPUCombinedScheduling. + + It handles fusion decisions and cutlass C++ specific template code generation. + """ + + @classmethod + def get_backend_features(cls, device) -> OrderedSet[BackendFeature]: + return OrderedSet() + + def group_fn(self, sizes): + return tuple(V.graph.sizevars.simplify(sympy_product(s)) for s in sizes) + + @staticmethod + def is_cutlass_template(node: BaseSchedulerNode) -> TypeGuard[SchedulerNode]: + return isinstance(node, SchedulerNode) and isinstance( + node.node, CUTLASSTemplateBuffer + ) + + def is_cutlass_fused_template(self, node: BaseSchedulerNode) -> bool: + return isinstance(node, FusedSchedulerNode) and self.is_cutlass_template(node) + + def can_fuse_vertical( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + if self.is_cutlass_template(node1) and isinstance(node2, BaseSchedulerNode): + if not node1.node: + raise AssertionError("node1.node should not be None") + return self._can_fuse_epilogue_impl( + cast(CUTLASSTemplateBuffer, node1.node), + [], + node2, # type: ignore[arg-type] + ) + elif self.is_cutlass_fused_template(node1) and isinstance( + node2, BaseSchedulerNode + ): + if not node1.node: + raise AssertionError("node1.node should not be None") + if not node2.node: + raise AssertionError("node2.node should not be None") + fnode1 = cast(FusedSchedulerNode, node1) + return self._can_fuse_epilogue_impl( + fnode1.get_template_node(), # type: ignore[arg-type] + self._unwrap_epilogue_nodes(fnode1), + node2, # type: ignore[arg-type] + ) + + 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 "" + ) + + # use the original src_code as the key + kernel_hash = hashlib.sha256(src_code.encode("utf-8")).hexdigest()[:8] + if fused_name == "fused": + # no EVT kernel, use the original kernel name + kernel_name = f"cutlass_{kernel_hash}" + else: + kernel_name = f"cutlass_{fused_name}_{kernel_hash}" + wrapper.src_to_kernel[src_code] = kernel_name + src_code = src_code.replace(str(Placeholder.KERNEL_NAME), kernel_name) + + _, _, kernel_path = get_path(code_hash(src_code), "py") + + compile_wrapper = IndentedBuffer() + compile_wrapper.writeline(f"async_compile.{V.graph.device_type}(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. cutlass_), but at codegen time the kernel name + # gains a descriptive prefix (cutlass_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 CUDACodeCache, XPUCodeCache + + codecache_cls = ( + XPUCodeCache if V.graph.device_type == "xpu" else CUDACodeCache + ) + so_path, _, _ = codecache_cls.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 cutlass template, possibly with fused epilogues + """ + counters["inductor"]["cutlass_epilogue_fusion_counter"] += len(epilogue_nodes) + if not self.is_cutlass_template(template_node): + raise AssertionError( + "Template node passed to CUTLASSScheduling.codegen_template must be a SchedulerNode that wraps a CUTLASSTemplateBuffer" + ) + _, (_numel, rnumel) = template_node.group + if rnumel != 1: + raise AssertionError(f"expected rnumel == 1, got {rnumel}") + ctb: CUTLASSTemplateBuffer = cast(CUTLASSTemplateBuffer, template_node.node) + epilogue_ir_nodes: list[Buffer] = [n.node for n in epilogue_nodes] # type: ignore[misc] + if not all(isinstance(n, ComputedBuffer) for n in epilogue_ir_nodes): + raise AssertionError( + "Epilogue nodes must all be instances of ir.ComputedBuffer" + ) + kernel, render = ctb.make_kernel_render( # type: ignore[misc] + ctb, epilogue_nodes=epilogue_nodes + ) + with kernel: + for node in [template_node, *epilogue_nodes]: + node.mark_run() + + # typically there is a codegen pass which runs after mark_run + # for this kernel we've already generated the C++ code, but we still + # need to let the kernel know about loads/stores that occur in the fused + # kernel for memory planning to properly optimize allocations + ctb.emulate_store_fn() + for node in epilogue_ir_nodes: + with V.set_ops_handler(MockCutlassHandler(V.get_ops_handler())): + # Not sure why we need to do this again + if not isinstance(node, ComputedBuffer): + raise AssertionError( + f"expected ComputedBuffer, got {type(node)}" + ) + node.get_store_function()(CutlassEVTCodegen.get_index_vars(node)) + + with V.set_kernel_handler(kernel): + src_code = render() + node_schedule = [template_node, *epilogue_nodes] + kernel_name = self.define_kernel(src_code, node_schedule) + + # debug printing values of intermediate tensors + _, call_args, arg_signatures, _ = kernel.args.python_argdefs() + debug_printer_manager = V.graph.wrapper_code.debug_printer + debug_printer_manager.set_printer_args( + call_args, kernel_name, arg_signatures, kernel + ) + with debug_printer_manager: + 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() + + @staticmethod + def _unwrap_epilogue_nodes( + fused_node: FusedSchedulerNode, + ) -> list[BaseSchedulerNode]: + nodes = fused_node.get_nodes() + template_node = fused_node.get_template_node() + if not all(n.node is not None for n in nodes): + raise AssertionError("All epilogue nodes should have an IRNode") + # pyrefly: ignore [redundant-cast] + return cast( + list[BaseSchedulerNode], [n for n in nodes if n.node is not template_node] + ) + + @staticmethod + def _is_compatible_reshape( + template_size: Sequence[sympy.Expr], node_size: Sequence[sympy.Expr] + ) -> bool: + """ + Check if node_size is a compatible reshape of template_size. + This allows cases like template [8192, 3072] with node [16, 512, 3072] + where [16*512, 3072] == [8192, 3072] (prefix dims multiply to match). + """ + if len(node_size) <= len(template_size): + return False + # Try to merge consecutive node dims to reconstruct template dims + t_idx = 0 + n_idx = 0 + + def _matches_template_dim(lhs: sympy.Expr, rhs: sympy.Expr) -> bool: + # Fast path for concrete/static equality before invoking simplify. + if lhs == rhs: + return True + if V.graph.sizevars.statically_known_equals(lhs, rhs): + return True + return sympy.simplify(lhs - rhs) == 0 + + while t_idx < len(template_size) and n_idx < len(node_size): + product = node_size[n_idx] + n_idx += 1 + # Try multiplying consecutive node dims until we match template dim + while not _matches_template_dim(product, template_size[t_idx]): + if n_idx >= len(node_size): + return False + product = product * node_size[n_idx] + n_idx += 1 + t_idx += 1 + return t_idx == len(template_size) and n_idx == len(node_size) + + def _can_fuse_epilogue_impl( + self, + cutlass_template_buffer: CUTLASSTemplateBuffer, + existing_epilogue_nodes: list[BaseSchedulerNode], + node_to_fuse: BaseSchedulerNode, + ) -> bool: + """ + Check if the given node can be fused with the epilogue. At the moment, Kernels + support fusion with Pointwise operations, wrapped in (named) ComputedBuffer nodes. + + Args: + cutlass_template_buffer : A CUTLASSTemplateBuffer object representing the CUTLASS template and it's result buffer + existing_epilogue_nodes : List[SchedulerNode]: The list of already fused epilogue nodes. + node_to_fuse: The SchedulerNode node to be checked if it can be fused with the epilogue. + Returns: + - bool: True if the given node can be fused with the epilogue, False otherwise. + + """ + why = WhyNoFuseNames( + cutlass_template_buffer.get_name(), node_to_fuse.get_name() + ) + + scheduler_nodes_to_fuse = node_to_fuse.get_nodes() + + if not isinstance(cutlass_template_buffer, CUTLASSTemplateBuffer): + raise AssertionError( + f"expected CUTLASSTemplateBuffer, got {type(cutlass_template_buffer)}" + ) + + # Checks on constituent nodes + for s_node in scheduler_nodes_to_fuse: + node = s_node.node + + if not isinstance(node, ComputedBuffer): + why(f"{node} is not a ComputedBuffer") + return False + elif not isinstance(node.data, Pointwise): + why(f"{node} is not a Pointwise op") + return False + elif not node.get_computed_buffer_name(): # type: ignore[attr-defined] + why(f"{node} does not have a computed buffer name") + return False + + name = node.get_computed_buffer_name() # type: ignore[attr-defined] + # dtype can differ, and strides can differ as long as they are broadcastable + # Allow compatible reshapes (e.g., [8192, 3072] vs [16, 512, 3072]) + # where the node's shape is a split of the template's shape + if node.get_size() != cutlass_template_buffer.get_size(): + if not self._is_compatible_reshape( + cutlass_template_buffer.get_size(), node.get_size() + ): + why( + f"{name}'s size: {node.get_size()} differs from {cutlass_template_buffer.get_name()}'s \ +size: {cutlass_template_buffer.get_size()}" + ) + return False + + if not ( + len(existing_epilogue_nodes) + or cutlass_template_buffer.get_name() + in OrderedSet([rd.name for rd in node_to_fuse.read_writes.reads]) + ): + raise AssertionError( + "First epilogue node must read from cutlass template buffer" + ) + + if node_to_fuse.has_aliasing_or_mutation(): + why(f"{node_to_fuse.get_name()} has aliasing or mutation") + return False + elif node_to_fuse.is_reduction(): + why( + f"{node_to_fuse.get_name()} is a reduction which is not yet supported by EVT" + ) + return False + elif ( + not config.cutlass.cutlass_epilogue_fusion_enabled + or not config.epilogue_fusion + ): + why("cutlass epilogue fusion is not enabled") + return False + elif not cutlass_template_buffer.supports_epilogue_fusion: + why("epilogue fusion is only supported for TMA-enabled gemm ops") + return False + + try: + from torch._inductor.codegen.cutlass.python_evt import CutlassEVTCodegen + + read_names, _, _, _ = CutlassEVTCodegen.ir_to_evt_python_code( + cutlass_template_buffer.get_name(), + existing_epilogue_nodes + list(node_to_fuse.get_nodes()), + OrderedSet(), + ) + + except NotImplementedError as e: + not_implemented_op = str(e) + if not_implemented_op.startswith("_op_"): + not_implemented_op = not_implemented_op[4:] + why( + f"Cannot fuse epilogue node {node_to_fuse} into {cutlass_template_buffer.name}, \ +likely due to unsupported operation: {not_implemented_op}" + ) + return False + else: # Likely due to unsupported dtype. + why( + f"Cannot fuse epilogue node {node_to_fuse} into {cutlass_template_buffer.name}. \ +Reason: {not_implemented_op}" + ) + return False + + # An external read whose shape is a compatible reshape of the 2D GEMM + # output is normalized to the template shape during rendering, but only + # when it is contiguous (the row-major flatten is memory-equivalent). + # A non-contiguous compatible-reshape read cannot be safely flattened, + # and EVT would fail shape propagation against the (1, M, N) accumulator, + # so reject the fusion in that case. + template_size = cutlass_template_buffer.get_size() + all_bufs = V.graph.name_to_buffer | V.graph.graph_inputs + for read_name in read_names: + buf = all_bufs.get(read_name) + if ( + buf is not None + and self._is_compatible_reshape(template_size, buf.get_size()) + and not buf.get_layout().is_contiguous() + ): + why( + f"external read {read_name} with size {buf.get_size()} is a " + f"non-contiguous compatible reshape of template size " + f"{template_size}, which CUTLASS EVT cannot align to the " + f"accumulator shape" + ) + return False + + return True diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/serialization.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..5f96721281770e11f19e0bba2c0d7a89e015bd7e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/serialization.py @@ -0,0 +1,508 @@ +# mypy: allow-untyped-defs +import functools +import json +from enum import Enum +from typing import Any, Optional + +from torch._inductor.codegen.cutlass.utils import try_import_cutlass + + +class CUTLASSOperationSerializer: + """Serializes and deserializes CUTLASS GEMM operations to/from JSON. + + Handles GemmOperation objects and their nested components (TileDescription, TensorDescription). + """ + + # not used, but keeping in case we want to generalize the serializer + _SUPPORTED_CLASSES: list[str] = [ + "GemmOperation", + "GemmKind", + "TileDescription", + "TensorDescription", + "DataType", + "EpilogueFunctor", + "EpilogueFunctor3x", + "SwizzlingFunctor", + "KernelScheduleType", + "EpilogueScheduleType", + "TileSchedulerType", + ] + + @classmethod + def serialize(cls, operation: "GemmOperation") -> str: # type: ignore[name-defined] # noqa: F821 + """Serialize a GEMM operation to JSON string. + + Args: + operation: GemmOperation object + + Returns: + str: JSON string representation of the operation + """ + if operation.__class__.__qualname__ != "GemmOperation": + raise AssertionError( + "Only GemmOperation objects are supported via the main API" + ) + return json.dumps(cls._gemm_operation_to_json(operation)) + + @classmethod + def deserialize(cls, json_str: str) -> "GemmOperation": # type: ignore[name-defined] # noqa: F821 + """Deserialize JSON string to a GEMM operation. + + Args: + json_str: JSON string of a GEMM operation + + Returns: + GemmOperation: Reconstructed operation + """ + json_dict = json.loads(json_str) + return cls._json_to_gemm_operation(json_dict) + + @classmethod + def _gemm_operation_to_json(cls, operation: "GemmOperation") -> dict[str, Any]: # type: ignore[name-defined] # noqa: F821 + """Convert GemmOperation to JSON-serializable dict. + + Args: + operation: GemmOperation object + + Returns: + dict: Dictionary representation + """ + from cutlass_library.library import TensorDescription + + # Create the main dictionary with required and optional parameters + result = { + # Required parameters + "gemm_kind": cls._enum_to_json(operation.gemm_kind), + "arch": operation.arch, + "tile_description": cls._tile_description_to_json( + operation.tile_description + ), + "A": cls._tensor_description_to_json(operation.A), + "B": cls._tensor_description_to_json(operation.B), + "C": cls._tensor_description_to_json(operation.C), + "element_epilogue": cls._enum_to_json(operation.element_epilogue), + # Optional parameters + "epilogue_functor": cls._enum_to_json(operation.epilogue_functor), + "swizzling_functor": cls._enum_to_json(operation.swizzling_functor), + "D": cls._tensor_description_to_json(operation.D) if operation.D else None, + "kernel_schedule": cls._enum_to_json(operation.kernel_schedule), + "epilogue_schedule": cls._enum_to_json(operation.epilogue_schedule), + "tile_scheduler": cls._enum_to_json(operation.tile_scheduler), + } + + # Process optional attributes + optional_attrs = [ + "mixed_input_mode", + "mixed_input_shuffle", + "ScaleFactorA", + "ScaleFactorB", + "ScaleFactorD", + "ScaleFactorMVecSize", + "ScaleFactorNVecSize", + "ScaleFactorKVecSize", + "ScaleFactorVectorSize", + "is_3x", + ] + + for attr in optional_attrs: + if not hasattr(operation, attr): + continue + + value = getattr(operation, attr) + + if isinstance(value, TensorDescription): + result[attr] = cls._tensor_description_to_json(value) + elif isinstance(value, Enum): + result[attr] = cls._enum_to_json(value) + else: + result[attr] = value + + return result + + @classmethod + def _json_to_gemm_operation(cls, json_dict: dict[str, Any]) -> "GemmOperation": # type: ignore[name-defined] # noqa: F821 + """Convert JSON dict to GemmOperation object. + + Args: + json_dict: Dictionary representation + + Returns: + GemmOperation: Reconstructed object + """ + from cutlass_library import DataType + from cutlass_library.gemm_operation import GemmKind, GemmOperation + from cutlass_library.library import ( + EpilogueFunctor, + EpilogueFunctor3x, + EpilogueScheduleType, + KernelScheduleType, + MixedInputMode, + SwizzlingFunctor, + TileSchedulerType, + ) + + # Extract constructor parameters from the JSON dictionary + gemm_kind = cls._json_to_enum(json_dict["gemm_kind"], GemmKind) + arch = json_dict["arch"] + tile_description = cls._json_to_tile_description(json_dict["tile_description"]) + A = cls._json_to_tensor_description(json_dict.get("A"), "A") + B = cls._json_to_tensor_description(json_dict.get("B"), "B") + C = cls._json_to_tensor_description(json_dict.get("C"), "C") + element_epilogue = cls._json_to_enum(json_dict["element_epilogue"], DataType) + + # Get optional parameters with defaults + epilogue_functor = cls._json_to_enum( + json_dict.get("epilogue_functor"), + EpilogueFunctor3x if json_dict.get("is_3x") else EpilogueFunctor, + ) + swizzling_functor = cls._json_to_enum( + json_dict.get("swizzling_functor"), SwizzlingFunctor + ) + D = cls._json_to_tensor_description(json_dict.get("D"), "D") + kernel_schedule = cls._json_to_enum( + json_dict.get("kernel_schedule"), KernelScheduleType + ) + epilogue_schedule = cls._json_to_enum( + json_dict.get("epilogue_schedule"), EpilogueScheduleType + ) + tile_scheduler = cls._json_to_enum( + json_dict.get("tile_scheduler"), TileSchedulerType + ) + + mixed_input_mode = cls._json_to_enum( + json_dict.get("mixed_input_mode"), MixedInputMode + ) + mixed_input_shuffle = json_dict.get("mixed_input_shuffle", False) + + # Scale factors + ScaleFactorA = cls._json_to_enum(json_dict.get("ScaleFactorA"), DataType) + ScaleFactorB = cls._json_to_enum(json_dict.get("ScaleFactorB"), DataType) + + ScaleFactorD = None + if "ScaleFactorD" in json_dict and "ScaleFactorVectorSize" in json_dict: + ScaleFactorD = { + "tensor": cls._json_to_tensor_description( + json_dict.get("ScaleFactorD"), "ScaleFactorD" + ), + "vector_size": json_dict.get("ScaleFactorVectorSize"), + } + + ScaleFactorMVecSize = json_dict.get("ScaleFactorMVecSize") + ScaleFactorNVecSize = json_dict.get("ScaleFactorNVecSize") + ScaleFactorKVecSize = json_dict.get("ScaleFactorKVecSize") + + # Create the GemmOperation with the extracted parameters + operation = GemmOperation( + gemm_kind=gemm_kind, + arch=arch, + tile_description=tile_description, + A=A, + B=B, + C=C, + element_epilogue=element_epilogue, + epilogue_functor=epilogue_functor, + swizzling_functor=swizzling_functor, + D=D, + kernel_schedule=kernel_schedule, + epilogue_schedule=epilogue_schedule, + tile_scheduler=tile_scheduler, + mixed_input_mode=mixed_input_mode, + mixed_input_shuffle=mixed_input_shuffle, + ScaleFactorA=ScaleFactorA, + ScaleFactorB=ScaleFactorB, + ScaleFactorD=ScaleFactorD, + ScaleFactorMVecSize=ScaleFactorMVecSize, + ScaleFactorNVecSize=ScaleFactorNVecSize, + ScaleFactorKVecSize=ScaleFactorKVecSize, + ) + + return operation + + @classmethod + @functools.lru_cache(None) + def _tile_description_to_json(cls, tile_desc: "TileDescription") -> str: # type: ignore[name-defined] # noqa: F821 + """ + Convert TileDescription to JSON string. + + Args: + tile_desc: TileDescription object + + Returns: + str: JSON string representation + """ + + # Create the main dictionary with field names matching TileDescription constructor parameters + result = { + "threadblock_shape": tile_desc.threadblock_shape, + "stages": tile_desc.stages, + "warp_count": tile_desc.warp_count, + "math_instruction": cls._math_instruction_to_json( + tile_desc.math_instruction + ), + "min_compute": tile_desc.minimum_compute_capability, # Store as min_compute for constructor + "max_compute": tile_desc.maximum_compute_capability, # Store as max_compute for constructor + "cluster_shape": tile_desc.cluster_shape, + "explicit_vector_sizes": tile_desc.explicit_vector_sizes, + } + + # Add tile_shape if it exists and differs from threadblock_shape + if ( + hasattr(tile_desc, "tile_shape") + and tile_desc.tile_shape != tile_desc.threadblock_shape + ): + result["tile_shape"] = tile_desc.tile_shape + + return json.dumps(result) + + @classmethod + @functools.lru_cache(None) + def _json_to_tile_description( + cls, json_dict: str | None + ) -> Optional["TileDescription"]: # type: ignore[name-defined] # noqa: F821 + """ + Convert JSON dict to TileDescription object. + + Args: + json_dict: Dictionary representation + + Returns: + TileDescription: Reconstructed object + """ + if json_dict is None: + return None + + tile_dict = json.loads(json_dict) + + from cutlass_library.library import TileDescription + + math_instruction = cls._json_to_math_instruction(tile_dict["math_instruction"]) + + # Get compute capability values, checking both naming conventions + min_compute = tile_dict.get( + "min_compute", tile_dict.get("minimum_compute_capability") + ) + max_compute = tile_dict.get( + "max_compute", tile_dict.get("maximum_compute_capability") + ) + + # Get cluster shape with default value + cluster_shape = tile_dict.get("cluster_shape", [1, 1, 1]) + + # Create the TileDescription object + tile_desc = TileDescription( + threadblock_shape=tile_dict["threadblock_shape"], + stages=tile_dict["stages"], + warp_count=tile_dict["warp_count"], + math_instruction=math_instruction, + min_compute=min_compute, + max_compute=max_compute, + cluster_shape=cluster_shape, + explicit_vector_sizes=tile_dict.get("explicit_vector_sizes"), + ) + + # Set tile_shape if it exists and differs from threadblock_shape + if ( + "tile_shape" in tile_dict + and tile_dict["tile_shape"] != tile_dict["threadblock_shape"] + ): + tile_desc.tile_shape = tile_dict["tile_shape"] + + return tile_desc + + @classmethod + @functools.lru_cache(None) + def _math_instruction_to_json( + cls, + math_instruction: Optional["MathInstruction"], # type: ignore[name-defined] # noqa: F821 + ) -> str | None: + """Convert MathInstruction to JSON string. + + Args: + math_instruction: MathInstruction object + + Returns: + Optional[str]: JSON string representation or None + """ + if math_instruction is None: + return None + + result = { + "instruction_shape": math_instruction.instruction_shape, + "element_a": cls._enum_to_json(math_instruction.element_a), + "element_b": cls._enum_to_json(math_instruction.element_b), + "element_accumulator": cls._enum_to_json( + math_instruction.element_accumulator + ), + "opcode_class": cls._enum_to_json(math_instruction.opcode_class), + "math_operation": cls._enum_to_json(math_instruction.math_operation), + "element_scale_factor": cls._enum_to_json( + math_instruction.element_scale_factor + ), + } + + return json.dumps(result) + + @classmethod + @functools.lru_cache(None) + def _json_to_math_instruction( + cls, json_dict: str | None + ) -> Optional["MathInstruction"]: # type: ignore[name-defined] # noqa: F821 + """Convert JSON string to MathInstruction object. + + Args: + json_dict: JSON string representation + + Returns: + Optional[MathInstruction]: Reconstructed object or None + """ + if json_dict is None: + return None + + from cutlass_library import DataType + from cutlass_library.library import MathInstruction, MathOperation, OpcodeClass + + mi_dict = json.loads(json_dict) + + # Convert string enum names back to enum values + element_a = cls._json_to_enum(mi_dict["element_a"], DataType) + element_b = cls._json_to_enum(mi_dict["element_b"], DataType) + element_acc = cls._json_to_enum(mi_dict["element_accumulator"], DataType) + + # Get the opcode_class enum + opcode_class = cls._json_to_enum(mi_dict["opcode_class"], OpcodeClass) + + # Get the math_operation enum + math_op = cls._json_to_enum(mi_dict["math_operation"], MathOperation) + + # Create the MathInstruction object + math_instruction_obj = MathInstruction( + instruction_shape=mi_dict["instruction_shape"], + element_a=element_a, + element_b=element_b, + element_accumulator=element_acc, + opcode_class=opcode_class, + math_operation=math_op, + ) + + # Add element_scale_factor if it exists + if ( + "element_scale_factor" in mi_dict + and mi_dict["element_scale_factor"] is not None + ): + math_instruction_obj.element_scale_factor = cls._json_to_enum( + mi_dict["element_scale_factor"], DataType + ) + + return math_instruction_obj + + @classmethod + @functools.lru_cache(None) + def _tensor_description_to_json( + cls, + tensor_desc: Optional["TensorDescription"], # type: ignore[name-defined] # noqa: F821 + ) -> str | None: + """Convert TensorDescription to JSON string. + + Args: + tensor_desc: TensorDescription object + + Returns: + Optional[str]: JSON string representation or None + """ + if tensor_desc is None: + return None + + result = { + "element": cls._enum_to_json(tensor_desc.element), + "layout": cls._enum_to_json(tensor_desc.layout), + "alignment": tensor_desc.alignment, + "complex_transform": cls._enum_to_json(tensor_desc.complex_transform), + } + + return json.dumps(result) + + @classmethod + @functools.lru_cache(None) + def _json_to_tensor_description( + cls, + json_dict: str | None, + tensor_name: str | None = None, + ) -> Optional["TensorDescription"]: # type: ignore[name-defined] # noqa: F821 + """Convert JSON string to TensorDescription object. + + Args: + json_dict: JSON string representation + tensor_name: Name of the tensor to avoid cache in the same op + + Returns: + Optional[TensorDescription]: Reconstructed object or None + """ + if json_dict is None: + return None + + tensor_dict = json.loads(json_dict) + + from cutlass_library import DataType + from cutlass_library.library import ( + ComplexTransform, + LayoutType, + TensorDescription, + ) + + element = cls._json_to_enum(tensor_dict["element"], DataType) + layout = cls._json_to_enum(tensor_dict["layout"], LayoutType) + alignment = tensor_dict["alignment"] + complex_transform = cls._json_to_enum( + tensor_dict["complex_transform"], ComplexTransform + ) + + return TensorDescription(element, layout, alignment, complex_transform) + + @classmethod + @functools.lru_cache(None) + def _enum_to_json(cls, enum_value: Enum | None) -> str | None: + """Convert enum value to JSON string. + + Args: + enum_value: Enum value + + Returns: + Optional[str]: JSON string representation or None + """ + if enum_value is None: + return None + + result = { + "type": enum_value.__class__.__name__, + "name": enum_value.name, + } + + return json.dumps(result) + + @classmethod + @functools.lru_cache(None) + def _json_to_enum(cls, json_dict: str | None, enum_class: Any) -> Enum | None: + """Convert JSON string to enum value. + + Format: {name: "EnumName", value: 1} + + Args: + json_dict: JSON string representation + enum_class: Target enum class + + Returns: + Optional[Enum]: Reconstructed enum value or None + """ + if json_dict is None: + return None + + enum_dict = json.loads(json_dict) + + return enum_class[enum_dict["name"]] + + +@functools.lru_cache(1) +def get_cutlass_operation_serializer() -> CUTLASSOperationSerializer | None: + if not try_import_cutlass(): + return None + return CUTLASSOperationSerializer() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/template.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a2bacfe7b9ffa668bb48ec04f8f4be1e933d9e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/template.py @@ -0,0 +1,387 @@ +# mypy: allow-untyped-defs +import functools +import hashlib +import itertools +from dataclasses import dataclass +from typing import Any, TYPE_CHECKING +from unittest.mock import patch + +import sympy + +import torch +from torch._inductor import config +from torch._inductor.utils import clear_on_fresh_cache, Placeholder +from torch._logging import getArtifactLogger + +from ...autotune_process import CUTLASSBenchmarkRequest, TensorMeta +from ...ir import Buffer, CUTLASSTemplateBuffer, IRNode, Layout +from ...utils import IndentedBuffer, unique +from ...virtualized import V +from ..common import KernelTemplate +from .kernel import CUTLASSTemplateCaller, CUTLASSTemplateKernel +from .utils import DTYPE_TO_CUTLASS_TYPE + + +if TYPE_CHECKING: + from ...scheduler import BaseSchedulerNode +else: + BaseSchedulerNode = Any + +GemmOperation = Any + +autotuning_log = getArtifactLogger(__name__, "autotuning") + + +@dataclass(frozen=True) +class ArgInfo: + name: str + ty: str + + +@clear_on_fresh_cache +class CUTLASSTemplate(KernelTemplate): + """ + CUTLASSTemplate is a class that provides a template for generating CUTLASS Templates. Used as a baseclass for the + CUTLASSGemmTemplate, providing functionality that might also be relevant for non-GEMM CUTLASS Kernels. + """ + + index_counter = itertools.count() + # dict of cache key to (code, size_args) + code_cache: dict[str, tuple[str, tuple[int, ...], tuple[int, ...]]] = {} + cache_clear = staticmethod(code_cache.clear) + + def __init__( + self, + name: str, + input_nodes: list[Buffer], + layout: Layout, + input_reorder: list[int] | None = None, + ) -> None: + """ + Baseclass for CUTLASS C++ Templates, derived from KernelTemplate. + Not to be instantiated directly. + + Args: + name (str): The name of the CUTLASSTemplate 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 + self.device_type = layout.device.type + + @classmethod + @functools.lru_cache(None) + # pyrefly: ignore [bad-override] + def _template_from_string(cls, source: str) -> Any: + return KernelTemplate._template_from_string(source) + + @staticmethod + def supports_epilogue_fusion(op: GemmOperation, device_type: str) -> bool: + return False + + def make_key(self, name: str, input_key: str, layout_repr: str) -> str: + """ + Make a key for the code cache. The idea of the method is to cache + everything that matters but doesn't include runtime param values, i.e., + self.get_runtime_arg_values(). + + Args: + kwargs: Additional keyword arguments. Including op (GemmOperation). + """ + return hashlib.sha256( + str( + ( + input_key, + self.input_reorder, + # output layout, same as self.output_node.get_layout() + layout_repr, + self.get_runtime_arg_info(), + name, + ) + ).encode("utf-8") + ).hexdigest() + + def generate_code_and_args( + self, name: str, input_key: str, layout_repr: str, **kwargs + ) -> tuple[str, tuple[int, ...]]: + """ + Generate code and args with caching. We cache the code even if runtime + args are different. + """ + key: str | None = None + if config.cutlass.enable_caching_codegen: + key = self.make_key(name=name, input_key=input_key, layout_repr=layout_repr) + + if key is not None and key in self.code_cache: + code, size_args, offset_args = self.code_cache[key] + extra_args = tuple( + list(size_args) + + list(offset_args) + + list(self.get_runtime_arg_values(**kwargs)) + ) + return code, extra_args + + kernel_name = str(Placeholder.KERNEL_NAME) + kernel = CUTLASSTemplateKernel( + kernel_name=kernel_name, + runtime_arg_info=self.get_runtime_arg_info(), + runtime_arg_values=self.get_runtime_arg_values(**kwargs), + device_type=self.device_type, + ) + with patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)): + code = self.render(kernel=kernel, **kwargs) + _, call_args, _, _ = kernel.args.python_argdefs() + autotuning_log.debug("Generated Code:\n%s", code) + autotuning_log.debug( + "Args: cpp_argdefs: %s, python_argdefs: %s", + kernel.args.cpp_argdefs(DTYPE_TO_CUTLASS_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, + ) + ) + # Resolve symbolic sizes to concrete ints for benchmarking only. + V.graph.sizevars.optimization_hints( + map(sympy.expand, call_args[len(expected_args) :]) + ) + size_args = V.graph.sizevars.optimization_hints(kernel.get_dynamic_shape_args()) + offset_args = V.graph.sizevars.optimization_hints(kernel.get_offset_args()) + + if key is not None: + self.code_cache[key] = code, size_args, offset_args + + # extra args has runtime params, which shouldn't be cached + extra_args = tuple( + list(size_args) + list(offset_args) + self.get_runtime_arg_values(**kwargs) + ) + + return code, extra_args + + def generate( # type: ignore[override] + self, + name: str, + description: str, + input_key: str, + layout_repr: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + **kwargs, + ) -> CUTLASSTemplateCaller: + """ + Generates the CUDA template caller object for the given GEMM template and operation. + This CUTLASSTemplateCaller may be used to call and benchmark the generated CUDA kernel + in a standalone manner to enable Autotuning. + + Args: + description: op name followed by swizzle. + kwargs: Additional keyword arguments. + + Returns: + A CUTLASSTemplateCaller object representing the generated CUDA template caller. + """ + code, extra_args = self.generate_code_and_args( + name=name, + input_key=input_key, + layout_repr=layout_repr, + **kwargs, + ) + + # not caching since kernel name is needed below + kernel_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()[:8] + kernel_name = f"cutlass_{kernel_hash}" + code = code.replace(self.name, kernel_name) + + # create the BenchmarkRequest + bmreq = CUTLASSBenchmarkRequest( + kernel_name=kernel_name, + input_tensor_meta=input_tensor_meta, + output_tensor_meta=output_tensor_meta, + extra_args=extra_args, + source_code=code, + device_type=self.device_type, + ) + + # kwargs has "op" argument in case of CUTLASSGemmTemplate + op = kwargs["op"] + if not op: + supports_epilogue_fusion = False + else: + # epilogue fusion is only supported for TMA kernels + supports_epilogue_fusion = self.supports_epilogue_fusion( + op, self.device_type + ) + + def make_kernel_render( + template_node: CUTLASSTemplateBuffer, + epilogue_nodes: list[BaseSchedulerNode] | None = None, + ) -> tuple[CUTLASSTemplateKernel, functools.partial[str]]: + if not supports_epilogue_fusion and epilogue_nodes: + raise AssertionError("epilogue fusion is not supported for this kernel") + kernel = CUTLASSTemplateKernel( + kernel_name=str(Placeholder.KERNEL_NAME), + runtime_arg_info=self.get_runtime_arg_info(), + runtime_arg_values=self.get_runtime_arg_values(**kwargs), + device_type=self.device_type, + ) + 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 CUTLASSTemplateCaller( + kernel_name, + "cutlass_gemm", + self.input_nodes, + self.output_node.get_layout(), + make_kernel_render, + bmreq, + supports_epilogue_fusion, + self, + kwargs, + description, + ) + + def header(self) -> IndentedBuffer: + res = IndentedBuffer() + res.splice( + """ + #include + #include + #include + #include + #include + """ + ) + res.splice( + """ + #include "cute/tensor.hpp" + #include "cutlass/cutlass.h" + #include "cutlass/numeric_types.h" + #include "cutlass/tensor_ref.h" + #include "cutlass/util/host_tensor.h" + #include "cutlass/util/reference/host/tensor_fill.h" + #include "cutlass/util/reference/device/tensor_fill.h" + #include "cutlass/util/device_memory.h" + """ + ) + 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 + """ + ) + res.splice( + """ + using namespace cute; + #define CUTLASS_CHECK(status) \\ + { \\ + cutlass::Status error = status; \\ + if (error != cutlass::Status::kSuccess) { \\ + auto msg = std::string("[") + __FILE__ + "] Got cutlass error: " + \\ + cutlassGetStatusString(error) + " at: " + std::to_string(__LINE__); \\ + throw std::runtime_error(msg); \\ + } \\ + } + + // Used as pass-through functor in EVT just for type casting / rounding + template + struct identity_op { + CUTLASS_HOST_DEVICE + T operator()(T val) const { return val; } + }; + + """ + ) + return res + + def cute_int(self, int_str: str, var_name: str) -> str: + res = "" + if int_str in ("1", "1L"): + res = "cute::Int<1>{}" + else: + res = int_str + + return f"{res} /* {var_name} */" + + _DTYPE_TO_CUTLASS = { + torch.float32: "float", + torch.float64: "double", + torch.float16: "cutlass::half_t", + torch.int32: "int32_t", + torch.int16: "int16_t", + torch.int8: "int8_t", + torch.uint8: "uint8_t", + torch.bool: "bool", + torch.bfloat16: "cutlass::bfloat16_t", + torch.float8_e4m3fn: "cutlass::float_e4m3_t", + torch.float8_e5m2: "cutlass::float_e5m2_t", + } + + _DTYPE_TO_CUTLASS_SPARSE_META = { + torch.int32: "uint32_t", + torch.int16: "uint16_t", + } + + def cutlass_type_cast(self, node: IRNode, ptr: str) -> str: + if node is None: + return ptr + else: + return f"({self._DTYPE_TO_CUTLASS.get(node.get_dtype())}*)({ptr})" + + def cutlass_sparse_meta_type_cast(self, node: IRNode, ptr: str) -> str: + if node is None: + return ptr + else: + return ( + f"({self._DTYPE_TO_CUTLASS_SPARSE_META.get(node.get_dtype())}*)({ptr})" + ) + + def render(self, **kwargs) -> str: + raise NotImplementedError + + def get_runtime_arg_info(self) -> list[ArgInfo]: + return [ArgInfo("swizzle", "const uint8_t")] + + def get_runtime_arg_values(self, **kwargs) -> list[Any]: + """ + Helper method to retrieve runtime args from generate kwargs + """ + return [kwargs[arg.name] for arg in self.get_runtime_arg_info()] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..efd794f098bb972beddaf06f2b31b24adb2a9192 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/cutlass/utils.py @@ -0,0 +1,618 @@ +# mypy: allow-untyped-defs +import atexit +import functools +import logging +import os +import shutil +import sys +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any +from typing_extensions import TypeIs + +import sympy + +import torch +from torch._inductor.runtime.runtime_utils import dynamo_timed +from torch._inductor.utils import clear_on_fresh_cache +from torch.utils._ordered_set import OrderedSet + +from ... import config +from ...ir import Layout +from ...runtime.runtime_utils import cache_dir +from ...virtualized import V +from ..cuda.cuda_env import get_cuda_arch, get_cuda_version +from ..xpu.xpu_env import get_xpu_arch, get_xpu_version + + +log = logging.getLogger(__name__) + +CUTLASS_OPERATION_KIND: str = "gemm" +ACCUMULATOR_DTYPES: OrderedSet[torch.dtype] = OrderedSet([torch.float, torch.int32]) +XW_DTYPES: OrderedSet[torch.dtype] = OrderedSet( + [torch.half, torch.bfloat16, torch.float8_e4m3fn, torch.int8, torch.float8_e5m2] +) + + +@atexit.register +def move_cutlass_compiled_cache() -> None: + """Move CUTLASS compiled cache file to the cache directory if it exists.""" + if try_import_cutlass.cache_info().currsize == 0: + return + + try: + import cutlass_cppgen # type: ignore[import-not-found] + except ImportError: + return + + # Check if the CACHE_FILE attribute exists in cutlass_cppgen and if the file exists + if not hasattr(cutlass_cppgen, "CACHE_FILE") or not os.path.exists( + cutlass_cppgen.CACHE_FILE + ): + return + + try: + filename = os.path.basename(cutlass_cppgen.CACHE_FILE) + shutil.move(cutlass_cppgen.CACHE_FILE, os.path.join(cache_dir(), filename)) + log.debug("Moved CUTLASS compiled cache file to %s", cache_dir()) + except OSError: + log.warning("Failed to move CUTLASS compiled cache file", exc_info=True) + + +def _rename_cutlass_import(content: str, cutlass_modules: list[str]) -> str: + for cutlass_module in cutlass_modules: + content = content.replace( + f"from {cutlass_module} import ", + f"from cutlass_library.{cutlass_module} import ", + ) + return content + + +@functools.cache +def try_import_cutlass() -> bool: + """ + We want to support three ways of passing in CUTLASS: + 1. fbcode, handled by the internal build system. + 2. User specifies cutlass_dir. The default is ../third_party/cutlass/, + which is the directory when developers build from source. + """ + if config.is_fbcode(): + try: + import cutlass_cppgen # type: ignore[import-not-found] + import cutlass_library # type: ignore[import-not-found] + except ImportError as e: + log.warning( + "Failed to import CUTLASS packages in fbcode: %s, ignoring the CUTLASS backend.", + e, + ) + return False + + return True + + # Copy CUTLASS python scripts to a temp dir and add the temp dir to Python search path. + # This is a temporary hack to avoid CUTLASS module naming conflicts. + # TODO(ipiszy): remove this hack when CUTLASS solves Python scripts packaging structure issues. + + # TODO(mlazos): epilogue visitor tree currently lives in python/cutlass, + # but will be moved to python/cutlass_library in the future (later 2025) + def path_join(path0, path1): + return os.path.abspath(os.path.join(path0, path1)) + + # contains both cutlass and cutlass_library + # we need cutlass for eVT + cutlass_dir = ( + config.xpu.cutlass_dir + if torch.xpu._is_compiled() + else config.cutlass.cutlass_dir + ) + cutlass_python_path = path_join(cutlass_dir, "python") + torch_root = os.path.abspath(os.path.dirname(torch.__file__)) + mock_src_path = os.path.join( + torch_root, + "_inductor", + "codegen", + "cutlass", + "lib_extensions", + "cutlass_mock_imports", + ) + + cutlass_library_src_path = path_join(cutlass_python_path, "cutlass_library") + cutlass_cppgen_src_path = path_join(cutlass_python_path, "cutlass_cppgen") + pycute_src_path = path_join(cutlass_python_path, "pycute") + + tmp_cutlass_full_path = os.path.abspath(os.path.join(cache_dir(), "torch_cutlass")) + + dst_link_library = path_join(tmp_cutlass_full_path, "cutlass_library") + dst_link_cutlass_cppgen = path_join(tmp_cutlass_full_path, "cutlass_cppgen") + dst_link_pycute = path_join(tmp_cutlass_full_path, "pycute") + + # mock modules to import cutlass + mock_modules = ["cuda", "scipy", "pydot"] + + if os.path.isdir(cutlass_python_path): + if tmp_cutlass_full_path not in sys.path: + + def link_and_append(dst_link, src_path, parent_dir): + if os.path.lexists(dst_link): + if not os.path.islink(dst_link): + raise AssertionError( + f"{dst_link} is not a symlink. Try to remove {dst_link} manually and try again." + ) + if os.path.realpath(os.readlink(dst_link)) != os.path.realpath( + src_path, + ): + raise AssertionError( + f"Symlink at {dst_link} does not point to {src_path}" + ) + else: + os.makedirs(parent_dir, exist_ok=True) + os.symlink(src_path, dst_link) + + if parent_dir not in sys.path: + sys.path.append(parent_dir) + + link_and_append( + dst_link_library, cutlass_library_src_path, tmp_cutlass_full_path + ) + link_and_append( + dst_link_cutlass_cppgen, cutlass_cppgen_src_path, tmp_cutlass_full_path + ) + link_and_append(dst_link_pycute, pycute_src_path, tmp_cutlass_full_path) + + for module in mock_modules: + link_and_append( + path_join(tmp_cutlass_full_path, module), # dst_link + path_join(mock_src_path, module), # src_path + tmp_cutlass_full_path, # parent + ) + + try: + import cutlass_cppgen # type: ignore[import-not-found] # noqa: F401 + import cutlass_library.generator + import cutlass_library.library + import cutlass_library.manifest # noqa: F401 + import pycute # type: ignore[import-not-found] # noqa: F401 + + return True + except ImportError as e: + log.debug( + "Failed to import CUTLASS packages: %s, ignoring the CUTLASS backend.", + e, + ) + else: + log.debug( + "Failed to import CUTLASS packages: CUTLASS repo does not exist: %s", + cutlass_python_path, + ) + return False + + +def _normalize_xpu_arch(arch: str) -> str: + if arch.startswith("Xe"): + return arch[2:] + if 12 <= int(arch) and int(arch) <= 50: + return arch + else: + raise NotImplementedError(f"Unsupported xpu arch: {arch}") + + +def _normalize_cuda_arch(arch: str) -> str: + arch_num = arch + if isinstance(arch, str): + digits = "".join(ch for ch in arch if ch.isdigit()) + if not digits: + raise ValueError(f"Unrecognized cuda arch: {arch}") + arch_num = int(digits) + else: + arch_num = int(arch) + + if arch_num > 107: + log.warning("Detected CUDA architecture > 107: %s. Please file an issue.", arch) + return str(arch_num) + if arch_num >= 107: + return "107" + if arch_num >= 103: + return "103" + if arch_num >= 100: + return "100" + if arch_num >= 90: + return "90" + if arch_num >= 80: + return "80" + if arch_num >= 75: + return "75" + if arch_num >= 70: + return "70" + raise NotImplementedError(f"Unsupported cuda arch: {arch}") + + +@functools.lru_cache(8) +def cutlass_arch(device_type: str) -> str: + if device_type == "xpu": + arch = get_xpu_arch() + return _normalize_xpu_arch(arch) + else: + arch = get_cuda_arch() + return _normalize_cuda_arch(arch) + + +@functools.lru_cache(1) +def toolkit_version(device_type: str) -> str: + if device_type == "xpu": + return get_xpu_version() + else: + return get_cuda_version() + + +def get_device_cutlass_config(device_type: str): + """Get device-specific CUTLASS config (xpu/cuda overrides general cutlass config).""" + if device_type == "xpu": + return config.xpu + from ...config import cutlass as inductor_cutlass_config + + return inductor_cutlass_config + + +@dataclass +class CUTLASSArgs: + """ + CUTLASS args used to initialize a CUTLASS Manifest. + """ + + architectures: str | None = None + toolkit_version: str | None = None + instantiation_level: str | None = None + operations: str | None = None + + build_dir = "" + curr_build_dir = "" + generator_target = "" + kernels = "all" + ignore_kernels = "" + exclude_kernels = "" + # TODO: these three look dead? + kernel_filter_file: None = None + selected_kernel_list: None = None + interface_dir: None = None + filter_by_cc = True + disable_full_archs_compilation = False + device_type: str = "cuda" + + def __post_init__(self): + if self.architectures is None or self.toolkit_version is None: + raise RuntimeError( + f"{self.architectures=} or {self.toolkit_version=} is None!" + ) + + +@clear_on_fresh_cache +@functools.cache +def _gen_ops_cached(arch: str, version: str, device_type: str) -> dict[Any, Any]: + # Note: Cache needs to be specific for cuda architecture and version + + # Import cutlass python scripts. + if not try_import_cutlass(): + raise AssertionError("Failed to import CUTLASS library") + import cutlass_library.generator as cutlass_generator + import cutlass_library.manifest as cutlass_manifest + + if arch is None or version is None: + log.error( + "Cannot detect cuda arch %s or version %s. " + "Will discard all cutlass ops. " + "Please consider setting _inductor.cuda.arch and _inductor.cuda.version configs.", + arch, + version, + ) + return {} + + # SM103 and SM107 reuse the SM100 generator, but the CUTLASS manifest must keep + # their architecture-specific baseline rather than treating them as SM100. + if arch in ("103", "107"): + gen_arch = "100" + manifest_arch = f"{arch}a" + else: + gen_arch = manifest_arch = arch + + instantiation_level: str = config.cutlass.cutlass_instantiation_level + args = CUTLASSArgs( + architectures=manifest_arch, + toolkit_version=version, + instantiation_level=instantiation_level, + operations=CUTLASS_OPERATION_KIND, + device_type=device_type, + ) + manifest = cutlass_manifest.Manifest(args) + if arch == "107": + # CUTLASS uses 103a as the SM100-family feature marker for architectures + # without INT8 UMMA. Keep the SM107 baseline while sharing that feature. + manifest.compute_capabilities_feature_set.append("103a") + + start_time = time.time() + if device_type == "xpu": + if hasattr(cutlass_generator, "GenerateIntelXe"): + cutlass_generator.GenerateIntelXe( + manifest, args.toolkit_version, arch=int(arch) + ) + else: + raise NotImplementedError( + "Arch " + arch + " is not supported by current cutlass lib." + ) + + elif arch == "100": + if hasattr(cutlass_generator, "GenerateSM100"): + cutlass_generator.GenerateSM100(manifest, args.toolkit_version) + cutlass_generator.GenerateSM90(manifest, args.toolkit_version) + else: + try: + func = getattr(cutlass_generator, "GenerateSM" + gen_arch) + func(manifest, args.toolkit_version) + except AttributeError as e: + raise NotImplementedError( + "Arch " + gen_arch + " is not supported by current cutlass lib." + ) from e + + log.info( + "CUTLASS library generated a dict of %d operation kinds in %.2f seconds", + len(manifest.operations), + time.time() - start_time, + ) + return manifest.operations + + +def gen_ops(device_type: str) -> dict[Any, Any]: + """ + Generates all supported CUTLASS operations. + """ + with dynamo_timed("cutlass_utils.gen_ops"): + arch = cutlass_arch(device_type) + version = toolkit_version(device_type) + return _gen_ops_cached(arch, version, device_type) + + +from ..cpp_utils import DTYPE_TO_CPP + + +if torch.xpu._is_compiled(): + DTYPE_TO_CUTLASS_TYPE = { + **DTYPE_TO_CPP, + torch.float16: "uint16_t", + torch.bfloat16: "uint16_t", + torch.float8_e4m3fn: "uint8_t", + torch.float8_e5m2: "uint8_t", + } +else: + DTYPE_TO_CUTLASS_TYPE = { + **DTYPE_TO_CPP, + torch.float16: "__half", + torch.bfloat16: "__nv_bfloat16", + torch.float8_e4m3fn: "__nv_fp8_e4m3", + torch.float8_e5m2: "__nv_fp8_e5m2", + } + + +@functools.lru_cache(32) +def torch_dtype_to_cutlass_type( + torch_dtype: torch.dtype, +) -> "cutlass_library.library.DataType": # type: ignore[name-defined] # noqa: F821 + # Import cutlass python scripts. + if not try_import_cutlass(): + raise AssertionError("Failed to import CUTLASS library") + import cutlass_library # type: ignore[import] + + if torch_dtype == torch.float: + return cutlass_library.library.DataType.f32 + elif torch_dtype == torch.half: + return cutlass_library.library.DataType.f16 + elif torch_dtype == torch.bfloat16: + return cutlass_library.library.DataType.bf16 + elif torch_dtype == torch.float8_e4m3fn: + return cutlass_library.library.DataType.e4m3 + elif torch_dtype == torch.float8_e5m2: + return cutlass_library.library.DataType.e5m2 + else: + raise NotImplementedError(f"Unsupported data type: {torch_dtype=}") + + +@functools.lru_cache(32) +def dtype_match( + torch_dtype: torch.dtype | None, + cutlass_dtype: "cutlass_library.library.DataType", # type: ignore[name-defined] # noqa: F821 +) -> bool: + # Import cutlass python scripts. + if not try_import_cutlass(): + raise AssertionError("Failed to import CUTLASS library") + import cutlass_library + + if torch_dtype == torch.float: + return ( + cutlass_dtype == cutlass_library.library.DataType.f32 + or cutlass_dtype == cutlass_library.library.DataType.tf32 + ) + elif torch_dtype == torch.half: + return cutlass_dtype == cutlass_library.library.DataType.f16 + elif torch_dtype == torch.bfloat16: + return cutlass_dtype == cutlass_library.library.DataType.bf16 + elif torch_dtype == torch.int8: + return cutlass_dtype == cutlass_library.library.DataType.s8 + elif torch_dtype == torch.uint8: + return cutlass_dtype == cutlass_library.library.DataType.u8 + elif torch_dtype == torch.int32: + return cutlass_dtype == cutlass_library.library.DataType.s32 + elif torch_dtype == torch.float8_e4m3fn: + return cutlass_dtype == cutlass_library.library.DataType.e4m3 + elif torch_dtype == torch.float8_e5m2: + return cutlass_dtype == cutlass_library.library.DataType.e5m2 + else: + return False + + +def get_accumulator_dtype( + input_torch_dtypes: list[torch.dtype], +) -> torch.dtype | None: + """ + Given a pair of input torch dtypes, returns the inferred accumulator torch dtype. + """ + + if not (OrderedSet(input_torch_dtypes) <= XW_DTYPES): + raise AssertionError(f"{input_torch_dtypes=} is not supported") + + if len(input_torch_dtypes) != 2: + return None + + if OrderedSet(input_torch_dtypes) == OrderedSet( + [torch.float8_e5m2, torch.float8_e4m3fn] + ): + return torch.float + + torch_dtype = None + if input_torch_dtypes[0] == input_torch_dtypes[1]: + torch_dtype = input_torch_dtypes[0] + else: + size0 = torch.tensor([], dtype=input_torch_dtypes[0]).element_size() + size1 = torch.tensor([], dtype=input_torch_dtypes[1]).element_size() + if size0 > size1: + dtype0, dtype1 = input_torch_dtypes + else: + dtype1, dtype0 = input_torch_dtypes + if dtype0 in [torch.half, torch.bfloat16] and dtype1 in [ + torch.int8, + torch.uint8, + ]: + torch_dtype = dtype0 + + if torch_dtype in ( + torch.float16, + torch.bfloat16, + torch.float, + torch.float8_e4m3fn, + torch.float8_e5m2, + ): + accumulator_dtype = torch.float + elif torch_dtype == torch.int8: + accumulator_dtype = torch.int32 + else: + raise NotImplementedError(f"Unsupported data types: {input_torch_dtypes=}") + + if accumulator_dtype not in ACCUMULATOR_DTYPES: + raise AssertionError(f"{accumulator_dtype=} is not supported") + return accumulator_dtype + + +@functools.lru_cache(32) +def get_alignments(torch_dtype: torch.dtype) -> list[int]: + """ + Returns all possible valid CUTLASS alignments in terms of the number of elements for a given dtype. + CUTLASS gemm / conv SM80 APIs support 16 bytes max alignment, and 2 bytes min alignment. + """ + + if torch_dtype in (torch.half, torch.bfloat16): + return [8, 4, 2, 1] + elif torch_dtype == torch.float: + return [4, 2, 1] + elif torch_dtype in ( + torch.uint8, + torch.int8, + torch.float8_e4m3fn, + torch.float8_e5m2, + ): + return [16, 8, 4, 2] + elif torch_dtype == torch.int32: + return [4, 2, 1] + else: + raise NotImplementedError(f"unsupported {torch_dtype=} for alignments") + + +def get_max_alignment(inductor_layout: Layout) -> int: + """ + Returns the max alignment (in terms of number of elements) for a given Inductor Layout. + """ + + dtype = inductor_layout.dtype + size = inductor_layout.size + offset = inductor_layout.offset + + def is_static_int(number: object) -> TypeIs[int | sympy.Integer]: + return isinstance(number, (int | sympy.Integer)) + + def a_factor_of(x, alignment): + if is_static_int(x) and is_static_int(alignment): + return x % alignment == 0 + rem = sympy.Mod(x, alignment) + return V.graph.sizevars.evaluate_expr(sympy.Eq(rem, 0)) + + try: + contiguous_dim = inductor_layout.stride.index(1) + except ValueError: + # No dim with stride 1 found, return 1 + return 1 + alignments = get_alignments(dtype) + for alignment in alignments: + if not a_factor_of(size[contiguous_dim], alignment) or not a_factor_of( + offset, alignment + ): + continue + if all( + (dim == contiguous_dim) + or a_factor_of(inductor_layout.stride[dim], alignment) + for dim in range(len(size)) + ): + return alignment + return 1 + + +class CUTLASSCompileSourceCapturingContext: + # Helper class for Benchmarking and Testing CUTLASS Kernels in isolation. + # Can be used to capture the sourcecode passed to CUDACodeCache.compile + + def __init__(self, device_type: str): + self.sources = [] + self._compile_patch = None + self.device_type = device_type + + def __enter__(self, *args, **kwargs): + import unittest.mock as mock + + import torch._inductor.codecache + + codecache_cls = ( + torch._inductor.codecache.XPUCodeCache + if self.device_type == "xpu" + else torch._inductor.codecache.CUDACodeCache + ) + _compile_method_orig = codecache_cls.compile + + def my_compile(source_code, dst_file_ext, extra_args: list[str] | None = None): + self.sources.append(source_code) + return _compile_method_orig(source_code, dst_file_ext) + + # pyrefly: ignore [bad-assignment] + self._compile_patch = mock.patch( + f"torch._inductor.codecache.{codecache_cls.__name__}.compile", my_compile + ) + self._compile_patch.__enter__(*args, **kwargs) # type: ignore[union-attr] + return self + + def __exit__(self, *args, **kwargs): + self._compile_patch.__exit__(*args, **kwargs) # type: ignore[union-attr] + + +def cutlass_standalone_runner_compile_command( + device_type: str, srcpath: Path, exepath: Path +): + # returns command string to compile a (captured) CUDA GEMM Kernel source to a standalone executable that's ready to run + # Passes the correct preprocessor define to nvcc to ensure the standalone runner is enabled. + + extra_args = ["-DGENERATE_STANDALONE_RUNNER=1"] + if device_type != "xpu": + extra_args.append("-DCUTLASS_DEBUG_TRACE_LEVEL=1") + cutlass_compile_command = ( + torch._inductor.codegen.xpu.compile_utils.xpu_compile_command + if device_type == "xpu" + else torch._inductor.codegen.cuda.compile_utils.cuda_compile_command + ) + compile_command = cutlass_compile_command( + [str(srcpath)], str(exepath), "exe", extra_args=extra_args + ) + return compile_command diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/debug_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/debug_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..eac55255abacdaaf4da615c6096ff47893964dea --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/debug_utils.py @@ -0,0 +1,293 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import functools +import logging +import os +from enum import Enum +from typing import TYPE_CHECKING + +import torch +from torch import dtype as torch_dtype + +from .. import config +from ..virtualized import V +from .multi_kernel import MultiKernel + + +if TYPE_CHECKING: + from collections.abc import Callable + + +log = logging.getLogger(__name__) + + +def _print_debugging_tensor_value_info(msg, arg): + # helper for printing debugging stats for intermediate tensor values + # at jit inductor level codegen + max_numel_to_print = 64 + print(msg) + if not isinstance(arg, torch.Tensor): + print("Value: ", arg) + return + numel = arg.numel() + # print the debug printing stats + if numel <= max_numel_to_print: + print(arg) + print("Number of elements: ", numel) + print("Size: ", arg.size()) + print("Dtype: ", arg.dtype) + arg_f = arg.float() + std, mean = torch.std_mean(arg_f) + amin, amax = torch.aminmax(arg_f) + print("Mean: ", mean.item()) + print("Min: ", amin.item()) + print("Max: ", amax.item()) + print("Std: ", std.item()) + + +# AOTI debug printing related configs +class IntermediateValueDebuggingLevel(Enum): + # OFF: No intermediate tensor value debug info will be printed or saved. + OFF = "0" + # LEVEL 1: Save all intermediate tensor values to individual `.pt` files. No debug printing will be displayed. + SAVE_ONLY = "1" + # LEVEL 2: Print all intermediate tensor values by default to the console. No debug saving will be performed. + PRINT_ONLY = "2" + # LEVEL 3: Print all kernel names to the console only. No debug saving/printing for input tensor value info will be performed. + # This mode can be helpful in cases when you just want to pinpoint what kernel is running into a CUDA IMA issue, etc. + PRINT_KERNEL_NAMES_ONLY = "3" + + +class DebugPrinterManager: + def __init__( + self, + debug_printer_level, + use_array_ref: bool, + writeline: Callable[..., None] | None = None, + args_to_print_or_save: list[str] | None = None, + kernel_name: str = "", + kernel=None, + arg_signatures: list[type] | None = None, + kernel_type=None, + ): + self.debug_printer_level = IntermediateValueDebuggingLevel(debug_printer_level) + self.use_array_ref = use_array_ref + if args_to_print_or_save is None: + args_to_print_or_save = [] + self.args_to_print_or_save = args_to_print_or_save + self.kernel_name = kernel_name + self.arg_signatures: list[type] | None = None + self.kernel = kernel + self.filtered_kernel_names_to_print = self._get_debug_filtered_kernel_names() + self.kernel_type = None + + def __enter__(self): + self._perform_debug_print_or_save_helper( + self.args_to_print_or_save, + self.kernel_name, + before_launch=True, + arg_signatures=self.arg_signatures, + ) + + def __exit__(self, args_to_print_or_save, kernel_name, arg_signatures): + self._perform_debug_print_or_save_helper( + args_to_print_or_save, + kernel_name, + before_launch=False, + arg_signatures=arg_signatures, + ) + + def _perform_debug_print_or_save_helper( + self, + args_to_print_or_save, + kernel_name, + before_launch, + arg_signatures: list[type] | None = None, + ): + if self.debug_printer_level == IntermediateValueDebuggingLevel.OFF: + return + if self.debug_printer_level == IntermediateValueDebuggingLevel.SAVE_ONLY: + # by default save all the tensor values before launch + self.codegen_intermediate_tensor_value_save( + self.args_to_print_or_save, + self.kernel_name, + before_launch, + arg_signatures=self.arg_signatures, + ) + if self.debug_printer_level == IntermediateValueDebuggingLevel.PRINT_ONLY: + # by default print all the tensor values before launch + self.codegen_intermediate_tensor_value_print( + self.args_to_print_or_save, + self.kernel_name, + before_launch, + arg_signatures=self.arg_signatures, + ) + if ( + self.debug_printer_level + == IntermediateValueDebuggingLevel.PRINT_KERNEL_NAMES_ONLY + ): + # Print all kernel names to the console only + self.codegen_intermediate_tensor_value_print( + [], + self.kernel_name, + before_launch, + ) + + @functools.lru_cache # noqa: B019 + def _get_debug_filtered_kernel_names(self) -> list[str]: + if config.aot_inductor.filtered_kernel_names is None: + return [] + return [ + x.strip() + for x in config.aot_inductor.filtered_kernel_names.lower().split(",") + ] + + def set_printer_args( + self, + args_to_print_or_save: list[str], + kernel_name: str, + arg_signatures: list[type] | None, + kernel, + kernel_type=None, + ): + # Note: MultiKernel debug printing is not supported for now + if isinstance(kernel, MultiKernel): + log.info( + "MultiKernel type is not supported in AOTI debug printer tool yet." + ) + self.debug_printer_level = IntermediateValueDebuggingLevel.OFF + + self.kernel_type = kernel_type + # Note: if the kernel type is an extern kernel (or cpp kernel), we do a special handling to + # get the list of args_to_print_or_save + # TODO: Find a more reliable way to detect kernel args types to print for extern kernel calls + if kernel_type == "extern": + args_to_print_or_save_extern = [ + arg + for arg in args_to_print_or_save + if isinstance(arg, str) and arg.startswith(("buf", "arg")) + ] + self.args_to_print_or_save = args_to_print_or_save_extern + elif kernel_type == "cpp": + self.args_to_print_or_save = [ + ( + f"copy_arrayref_tensor_to_tensor({arg})" + if self.use_array_ref + else arg + ) + for arg in args_to_print_or_save + if isinstance(arg, str) and arg.startswith(("buf", "arg")) + ] + else: + self.args_to_print_or_save = args_to_print_or_save + self.kernel_name = kernel_name + self.arg_signatures = arg_signatures + self.kernel = kernel + + def codegen_model_inputs_value_print(self, input_args_to_print: list[str]) -> None: + if self.debug_printer_level != IntermediateValueDebuggingLevel.PRINT_ONLY: + return + for arg in input_args_to_print: + if V.graph.cpp_wrapper: + V.graph.wrapper_code.prefix.writeline( + f'aoti_torch_print_tensor_handle({arg}, "aoti_model_inputs - {arg}");' + ) + + def codegen_intermediate_tensor_value_save( + self, + args_to_save, + kernel_name, + before_launch=True, + arg_signatures: list[type] | None = None, + ) -> None: + for i, arg in enumerate(args_to_save): + if arg_signatures is not None and not isinstance( + arg_signatures[i], torch_dtype + ): + # infer from the arg data type (has torch.dtype) to see if it is a tensor type + continue + launch_prefix = "before_launch" if before_launch else "after_launch" + if V.graph.cpp_wrapper: + V.graph.wrapper_code.writeline( + f'aoti_torch_save_tensor_handle({arg}, "{arg}", "{launch_prefix}", "{kernel_name}");' + ) + else: + cwd = os.getcwd() + saved_dir = cwd + "/tmp/jit_inductor/" + if not os.path.exists(saved_dir): + log.info( + "Creating directory to save inductor intermediate tensor values." + ) + os.makedirs(saved_dir) + # Save the model to the directory + saved_path = saved_dir + f"{launch_prefix}_{kernel_name}_{arg}.pt" + log.info( + "Saved intermediate tensor %s for %s to %s", + arg, + kernel_name, + saved_path, + ) + line = f"torch.save({arg}, '{saved_path}')" + V.graph.wrapper_code.writeline(line) + + def codegen_intermediate_tensor_value_print( + self, + args_to_print, + kernel_name, + before_launch=True, + arg_signatures: list[type] | None = None, + ) -> None: + launch_prefix = "before_launch" if before_launch else "after_launch" + + # if the debug printing level is PRINT_KERNEL_NAMES_ONLY + # we only print the kernel name to the console + if ( + self.debug_printer_level + == IntermediateValueDebuggingLevel.PRINT_KERNEL_NAMES_ONLY + ): + if V.graph.cpp_wrapper: + V.graph.wrapper_code.writeline( + f'printf("[ {launch_prefix}: {kernel_name} ]\\n");' + ) + return + + if self.debug_printer_level != IntermediateValueDebuggingLevel.PRINT_ONLY: + return + for i, arg in enumerate(args_to_print): + # when debug printing is enabled i.e. IntermediateValueDebuggingLevel.PRINT_ONLY, + # check if filtered kernel name list is provided + if ( + len(self.filtered_kernel_names_to_print) > 0 + and kernel_name.lower() not in self.filtered_kernel_names_to_print + ): + continue + if V.graph.cpp_wrapper: + if arg_signatures is not None and isinstance( + arg_signatures[i], torch_dtype + ): + # infer from the arg data type (has torch.dtype) to see if it is a tensor type + V.graph.wrapper_code.writeline( + f'aoti_torch_print_tensor_handle({arg}, "{launch_prefix} - {kernel_name} - {arg}");' + ) + elif arg_signatures is not None and isinstance( + arg_signatures[i], + ( + type(torch._inductor.codegen.wrapper.SymbolicCallArg), + type(int), + type(float), + type(bool), + ), + ): + V.graph.wrapper_code.writeline( + f'printf("[ {launch_prefix} - {kernel_name} - {arg}: %ld ]", {arg}); printf("\\\\n");' + ) + else: + if arg_signatures is None and self.kernel_type in ("cpp", "extern"): + V.graph.wrapper_code.writeline( + f'aoti_torch_print_tensor_handle({arg}, "{launch_prefix} - {kernel_name} - {arg}");' + ) + else: + V.graph.wrapper_code.writeline( + f'_print_debugging_tensor_value_info("inductor: {launch_prefix} - {kernel_name} - {arg}", {arg})' + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/halide.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/halide.py new file mode 100644 index 0000000000000000000000000000000000000000..89c798c10c025364e0634f33684c1c257615036d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/halide.py @@ -0,0 +1,1895 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import dataclasses +import functools +import itertools +import logging +import re +import sys +from collections import defaultdict +from typing import Any, cast, TYPE_CHECKING + +import sympy + +import torch +import torch._logging + +from ..._prims_common import is_integer_dtype +from ...utils._ordered_set import OrderedSet +from ...utils._sympy.functions import FloorDiv, Max, Min, ModularIndexing +from ...utils._sympy.symbol import symbol_is_type, SymT +from ...utils._sympy.value_ranges import ValueRanges +from .. import config, ir +from ..codecache import HalideCodeCache +from ..ir import get_reduction_combine_fn +from ..metrics import is_metric_table_enabled, log_kernel_metadata +from ..ops_handler import AddParenHandler +from ..runtime.hints import HalideInputSpec, HalideMeta +from ..utils import ( + get_bounds_index_expr, + get_kernel_metadata, + parallel_num_threads, + sympy_index_symbol, + sympy_subs, +) +from ..virtualized import _ops as ops, V +from .common import ( + BackendFeature, + CSEVariable, + DeferredLine, + IndentedBuffer, + KernelArgType, + OpOverrides, + PythonPrinter, + SizeArg, + TensorArg, +) +from .cpp import DTYPE_TO_CPP +from .cpp_utils import cexpr +from .simd import constant_repr, SIMDKernel, SIMDScheduling + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from ..ops_handler import ReductionType, StoreMode + from ..shape_propagation import BlockShapeType + +log = logging.getLogger(__name__) + + +def halide_constant(val): + if isinstance(val, int) and not (-2147483648 <= val <= 2147483647): + info = torch.iinfo(torch.int64) + if val == info.min: + return "hl.Int(64).min()" + if val == info.max: + return "hl.Int(64).max()" + return f"hl.i64({val!r})" + if isinstance(val, float): + return f"hl.f64({constant_repr(val)})" + return repr(val) + + +class Unsupported(RuntimeError): + def __init__(self, thing) -> None: + super().__init__(f"halide backend does not support: {thing}") + + +class HalidePrinter(PythonPrinter): # noqa: docstring_linter + @staticmethod + def cast_index(expr): + return f"hl.cast({V.kernel.index_dtype}, {expr})" + + @staticmethod + def cast_float(expr): + return f"hl.cast(hl.Float(32), {expr})" + + def _print_Float(self, expr): + return f"hl.f32({expr})" + + def _print_ToFloat(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.f32({self._print(expr.args[0])})" + + def _print_floor(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return self.cast_index(f"hl.floor({self._print(expr.args[0])})") + + _print_FloorToInt = _print_floor + + def _print_Trunc(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return self.cast_index(f"hl.trunc({self._print(expr.args[0])})") + + _print_TruncToInt = _print_Trunc + + def _print_ceiling(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return self.cast_index(f"hl.ceil({self._print(expr.args[0])})") + + def _helper_sqrt(self, expr): + # pyrefly: ignore [missing-attribute] + return f"hl.sqrt({self.cast_float(self._print(expr))})" + + def _print_Where(self, expr): + c = self.doprint(expr.args[0]) + p = self.doprint(expr.args[1]) + q = self.doprint(expr.args[2]) + return f"hl.select({c}, {p}, {q})" + + def _print_Min(self, expr): + if len(expr.args) == 1: + # pyrefly: ignore [missing-attribute] + return self._print(expr.args[0]) + + mid = len(expr.args) // 2 + # pyrefly: ignore [missing-attribute] + a = self._print(Min(*expr.args[:mid])) + # pyrefly: ignore [missing-attribute] + b = self._print(Min(*expr.args[mid:])) + return f"hl.min({a}, {b})" + + def _print_Max(self, expr): + if len(expr.args) == 1: + # pyrefly: ignore [missing-attribute] + return self._print(expr.args[0]) + + mid = len(expr.args) // 2 + # pyrefly: ignore [missing-attribute] + a = self._print(Max(*expr.args[:mid])) + # pyrefly: ignore [missing-attribute] + b = self._print(Max(*expr.args[mid:])) + + return f"hl.max({a}, {b})" + + def _print_Abs(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return self.cast_index(f"hl.abs({self._print(expr.args[0])})") + + def _print_OpaqueUnaryFn_cos(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.cos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_cosh(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.cosh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_acos(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.acos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sin(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.sin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sinh(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.sinh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_asin(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.asin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tan(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.tan({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tanh(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.tanh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_atan(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return f"hl.atan({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_log2(self, expr): + raise NotImplementedError("log2") + + def _print_FloorDiv(self, expr): + if expr.is_integer: + return super()._print_FloorDiv(expr) + + x, div = expr.args + x = self.cast_float(self.doprint(x)) + div = self.cast_float(self.doprint(div)) + return self.cast_index(f"hl.floor({x} / {div})") + + def _print_Round(self, expr): + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + # pyrefly: ignore [missing-attribute] + return self.cast_index(f"hl.round({self._print(expr.args[0])})") + + _print_RoundToInt = _print_Round + + def _print_IntTrueDiv(self, expr): + a, b = expr.args + # force a cast to float + return f"({a}) / ({b}+hl.f32(0))" + + def _print_RoundDecimal(self, expr): + val, n = expr.args + # pyrefly: ignore [missing-attribute] + val = self._print(val) + n = int(n) + return f"hl.f32({10.0 ** (-n)!r})*hl.round(({val})*hl.f32({10.0**n!r}))" + + +texpr = HalidePrinter().doprint +pexpr = PythonPrinter().doprint + + +_halide_type = { + torch.bool: "hl.Bool()", + torch.bfloat16: "hl.BFloat(16)", + torch.float16: "hl.Float(16)", + torch.float32: "hl.Float(32)", + torch.float64: "hl.Float(64)", + torch.int8: "hl.Int(8)", + torch.int16: "hl.Int(16)", + torch.int32: "hl.Int(32)", + torch.int64: "hl.Int(64)", + torch.uint8: "hl.UInt(8)", + torch.uint16: "hl.UInt(16)", + torch.uint32: "hl.UInt(32)", + torch.uint64: "hl.UInt(64)", +} + + +def halide_type(dtype): + return _halide_type[dtype] + + +def halide_acc_type(dtype): + if is_integer_dtype(dtype) and dtype.is_signed and dtype != torch.int64: + dtype = torch.int32 + if dtype in (torch.float16, torch.bfloat16): + dtype = torch.float32 + return halide_type(dtype) + + +class HalideOverrides(OpOverrides): + @staticmethod + def to_dtype( + x, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types=True, + ): + if dtype == torch.bool: + return f"({x} != 0)" + return f"hl.cast({halide_type(dtype)}, {x})" + + @staticmethod + def to_dtype_bitcast(x, dtype: torch.dtype, src_dtype: torch.dtype): + if src_dtype in (torch.float16, torch.bfloat16): + x = f"hl.cast({halide_type(src_dtype)}, {x})" # body compute is upcast to fp32 + line = f"hl.reinterpret({halide_type(dtype)}, {x})" + if dtype in (torch.float16, torch.bfloat16): + line = f"hl.cast(hl.Float(32), {line})" + return line + + @classmethod + def constant(cls, value, dtype): + return cls.to_dtype(halide_constant(value), dtype) + + @staticmethod + # pyrefly: ignore [bad-override] + def abs(x): + return f"hl.abs({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def exp(x): + if not hasattr(x, "name"): + return f"hl.exp({x})" + return f"hl.fast_exp(hl.cast(hl.Float(32), {x})) if {x.name}.type().bits() <= 32 else hl.exp({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sqrt(x): + return f"hl.sqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def minimum(a, b): + # return f"hl.min({a}, {b})" <== handles nan wrong + if not hasattr(a, "name"): + return f"hl.min({a}, {b})" + b = f"hl.cast({a.name}.type(), {b})" + return f"hl.select(({a}<{b})|hl.is_nan({a}), {a}, {b}) if {a.name}.type().is_float() else hl.min({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def maximum(a, b): + # return f"hl.max({a}, {b})" <== handles nan wrong + if not hasattr(a, "name"): + return f"hl.max({a}, {b})" + b = f"hl.cast({a.name}.type(), {b})" + return f"hl.select(({a}>{b})|hl.is_nan({a}), {a}, {b}) if {a.name}.type().is_float() else hl.max({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmaximum(a, b): + return f"hl.max({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def where(a, b, c): + if hasattr(b, "name"): + c = f"hl.cast({b.name}.type(), {c})" + return f"hl.select({a}, {b}, {c})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cos(x): + return f"hl.cos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sin(x): + return f"hl.sin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def lgamma(x): + raise Unsupported("lgamma") + + @staticmethod + # pyrefly: ignore [bad-override] + def erf(x): + return f"hl.erf({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cosh(x): + return f"hl.cosh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sinh(x): + return f"hl.sinh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acos(x): + return f"hl.acos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acosh(x): + return f"hl.acosh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asin(x): + return f"hl.asin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asinh(x): + return f"hl.asinh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan2(x, y): + return f"hl.atan2({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan(x): + return f"hl.atan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atanh(x): + return f"hl.atanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def copysign(x, y): + raise Unsupported("copysign") + + @staticmethod + # pyrefly: ignore [bad-override] + def erfinv(x): + raise Unsupported("erfinv") + + @staticmethod + # pyrefly: ignore [bad-override] + def hypot(x, y): + return f"hl.hypot({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def nextafter(x, y): + raise Unsupported("nextafter") + + @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): + return f"halide_helpers.rand({seed}, {offset})" + + @staticmethod + def randn(seed, offset): + return f"halide_helpers.randn({seed}, {offset})" + + @staticmethod + def rand_eager(seed, base_offset, threads_per_round, tid, vec): + return f"halide_helpers.rand_eager_kernel({seed}, {base_offset}, {threads_per_round}, {tid}, {vec})" + + @staticmethod + def randint64(seed, offset, low, high): + return f"halide_helpers.randint64({seed}, {offset}, {low}, {high})" + + @staticmethod + def load_seed(name, offset): + return f"{ops.load(name, 0)} + {V.kernel.args.seed_offset('load_seed_offset', offset)}" + + @staticmethod + # pyrefly: ignore [bad-override] + def rsqrt(x): + # return f"hl.fast_inverse_sqrt({x})" <== accuracy issues + return f"1./hl.sqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tan(x): + return f"hl.tan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tanh(x): + return f"hl.tanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def signbit(x): + return f"(hl.reinterpret(hl.UInt(32), hl.cast(hl.Float(32), {x})) >> 31) != 0" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmod(a, b): + # TODO(jansel): find a better way to do this, builtin % has wrong sign + return f"{a} - hl.trunc({a}/{b})*{b}" + + @staticmethod + def pow(a, b): + return f"hl.pow({a}, {b})" # hl.fast_pow fails accuracy + + @staticmethod + # pyrefly: ignore [bad-override] + def ldexp(x, n): + raise Unsupported("ldexp") + + @staticmethod + # pyrefly: ignore [bad-override] + def log(x): + return f"hl.log({x})" # hl.fast_log fails accuracy + + @staticmethod + def log2(x): + raise NotImplementedError("log2") + + @staticmethod + # pyrefly: ignore [bad-override] + def isinf(x): + # workaround https://github.com/halide/Halide/issues/8309 + return f"hl.is_inf(hl.cast(hl.Float(32), {x}))" + + @staticmethod + # pyrefly: ignore [bad-override] + def isnan(x): + # workaround https://github.com/halide/Halide/issues/8309 + return f"hl.is_nan(hl.cast(hl.Float(32), {x}))" + + @staticmethod + # pyrefly: ignore [bad-override] + def round(x): + return f"hl.round({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def floor(x): + return f"hl.floor({x})" + + @staticmethod + def int_truediv(a, b): + return f"({a}) / ({b} + hl.f32(0))" + + @staticmethod + def floordiv(a, b): + # TODO(jansel): find a better ways to do this, the select-based trick from triton.py didn't work + return ( + f"hl.floor(hl.cast(hl.Float(max(32, {a.name}.type().bits())), {a}) / {b})" + ) + + @classmethod + def sign(cls, x): + left = ops.to_dtype(ops.lt("0", x), torch.int8) + right = ops.to_dtype(ops.lt(x, "0"), torch.int8) + sub = ops.sub(left, right) + return f"hl.cast({x.name}.type(), {sub})" + + @staticmethod + # pyrefly: ignore [bad-override] + def trunc(x): + return f"hl.trunc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def truncdiv(a, b): + # this causes crashes with floating point exception, see test_div_zero_dim_cpu + # return f"hl.div_round_to_zero({a}, {b})" + return ( + f"hl.trunc(hl.cast(hl.Float(max(32, {a.name}.type().bits())), {a}) / {b})" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def ceil(x): + return f"hl.ceil({x})" + + @staticmethod + def relu(x): + return f"hl.max({x}, 0)" + + @classmethod + def index_expr(cls, expr, dtype): + index = V.kernel.prepare_indexing(expr) + var = V.kernel.genfunc( + V.kernel.index_to_str(index), + V.kernel.used_dims_from_index(index), + bounds=get_bounds_index_expr(expr), + ) + if dtype not in (torch.int32, torch.int64): + return ops.to_dtype(var, dtype) + return var + + @classmethod + def value_expr(cls, expr, dtype): + index = V.kernel.prepare_indexing(expr) + var = V.kernel.genfunc( + V.kernel.index_to_str(index), + V.kernel.used_dims_from_index(index), + bounds=get_bounds_index_expr(expr), + ) + return ops.to_dtype(var, dtype) + + @classmethod + def indirect_indexing(cls, index_var, size, check=True, wrap_neg=True): + # TODO(jansel): Halide only supports 32-bit indexing, we should error on overflow + index_var = ops.to_dtype(index_var, torch.int32) + index_var = ops.halide_clamp(index_var, size, check) + index_var.indirect_indexing_size = size + return sympy_index_symbol(str(index_var)) + + @classmethod + def halide_clamp(cls, value, size, check): + end = V.kernel.kexpr(V.kernel.rename_indexing(size) - 1) + if not isinstance(size, (int, sympy.Integer)): + end = f"hl.cast({value.name}.type(), {end})" + # Skip unsafe_promise_clamped to workaround: https://github.com/halide/Halide/issues/8261#issuecomment-2148835692 + # return f"hl.unsafe_promise_clamped({value}, 0, {end})" + return f"hl.clamp({value}, 0, {end})" + + @staticmethod + def masked(mask, body, other): + with V.kernel.mask_loads(mask, other) as new_mask: + result = body() + + if result.bounds.is_bool: + other = bool(other) + + # Take dtype from result to prevent accidental promotion + other = V.kernel.genfunc( + f"hl.cast({result.name}.type(), {halide_constant(other)})", + [], + bounds=ValueRanges.wrap(other), + shape=result.shape, + ) + # TODO(jansel): look into removing the where in the same places triton does + return ops.where(new_mask, result, other) + + @staticmethod + # pyrefly: ignore [bad-override] + def frexp(x): + raise NotImplementedError("frexp") + + @staticmethod + def device_assert_async(cond, msg): + raise NotImplementedError("device_assert_async") + + @staticmethod + # pyrefly: ignore [bad-override] + def partial_accumulate( + name: str, + reduction_type: str, + value: CSEVariable, + extra_meta: dict[str, Any], + ) -> None: + raise NotImplementedError + + +HalideOverrides._initialize_pointwise_overrides("halide") + + +class HalideCSEVariable(CSEVariable): + undefined_re = re.compile(r"\b(tmp\d+)\[\?\]") + + def __init__( + self, + name, + bounds: ValueRanges[Any], + dtype: torch.dtype | None = None, + shape: BlockShapeType = None, + ) -> None: + super().__init__(name, bounds, dtype, shape=shape) + self.used_dims: list[sympy.Symbol] | None = None + + def update_on_args(self, name, args, kwargs): + used = OrderedSet(self.used_dims or ()) + for arg in itertools.chain(args, kwargs.values()): + if isinstance(arg, HalideCSEVariable): + if arg.used_dims is None: + raise AssertionError((name, arg, args)) + used.update(arg.used_dims) + self.used_dims = V.kernel.sort_used_dims(used) + + def index_str(self, dims): + if len(dims) == 0: + return f"{self.name}[()]" + # Reversed since Halide is column major + return f"{self.name}[{', '.join(map(str, dims))}]" + + def __str__(self) -> str: + if self.used_dims is None: + # This will get recomputed and replaced in codegen_kernel() + return f"{self.name}[?]" + return self.index_str(self.used_dims) + + def subs_str(self, replacements): + if not ( + self.used_dims is not None + and all(isinstance(x, sympy.Expr) for x in self.used_dims) + ): + raise AssertionError("used_dims must be set sympy expressions") + return self.index_str([replacements.get(n, n) for n in self.used_dims]) + + +@dataclasses.dataclass +class DimensionInfo: + expr: sympy.Expr | None + size: sympy.Expr + stride: sympy.Expr + + def __init__(self, expr, size, stride) -> None: + super().__init__() + if V.graph.sizevars.statically_known_lt(stride, 0): + stride = -stride + expr = -expr + self.expr = expr + self.size = size + self.stride = stride + + def index_str(self, replacements=None, zero_vars=False): + if self.expr is None: + raise AssertionError("expr must not be None") + expr = self.expr + if zero_vars and expr == 0: + return "hl.Var()" + if replacements: + replacements = {**replacements} + # pyrefly: ignore [missing-attribute] + for sym in expr.free_symbols: + if symbol_is_type(sym, SymT.TMP): + if not isinstance(sym, sympy.Symbol): + raise AssertionError(f"expected sympy.Symbol, got {type(sym)}") + var = V.kernel.lookup_cse_var(sym.name) + if not isinstance(var, HalideCSEVariable): + raise AssertionError( + f"expected HalideCSEVariable, got {type(var)}" + ) + replacements[sym] = sympy_index_symbol(var.subs_str(replacements)) + expr = sympy_subs(expr, replacements) + return V.kernel.index_to_str(expr) + + +def eq(left, right): + return V.graph.sizevars.guard_or_false(sympy.Eq(left, right)) + + +def lt(left, right): + """Compare sizes: only use on inputs known to be >= 0.""" + if V.graph.sizevars.guard_or_false(sympy.Lt(left, right)): + return True + + # GCD fallback: if gcd(left, right) == left then left divides right, + # so left <= right. Combined with left != right this gives left < right. + # + # TODO: This is NOT always sound for unbacked symints. + # e.g. lt(u0, 10*u0): gcd=u0, gcd==left, u0 != 10*u0 → returns True, + # but if u0=0 then 0 < 0 is False. The >= 0 checks mitigate the + # negative case but the zero case remains. + # TODO shall we add a runtime assertion at least. + gcd = sympy.gcd(left, right) + if gcd == left: + return left != right + + return False + + +class HalideKernel(SIMDKernel): + overrides = HalideOverrides # type: ignore[assignment] + kexpr: Callable[[sympy.Expr], str] = texpr + + def __init__( + self, + tiling: dict[str, sympy.Expr], + **kwargs, + ) -> None: + super().__init__(tiling, **kwargs) + # For halide, we just write directly to the body + self.compute = self.body + self.loads = self.body + self.stores = self.body + self.indexing_code_dom = IndentedBuffer() + self.needs_dom_indexing = self.inside_reduction + self.has_reduction = self.inside_reduction + self.buffer_dimensions: dict[str, list[DimensionInfo]] = {} + self.buffer_offsets: dict[str, sympy.Expr] = {} + # {h0: size1, h1: size2, ...} + self.halide_vars: dict[sympy.Symbol, sympy.Expr] = {} + # {x0: h0, x1: h1+10*h2, ...} + self.index_replacements: dict[sympy.Expr, sympy.Expr] = {} + # {h1: hr1, ...} + self.reduction_renames: dict[sympy.Symbol, sympy.Symbol] = {} + # {"i": {h0: hi0}, "o": ...} + self.dom_renames: dict[str, dict[sympy.Symbol, sympy.Symbol]] = {} + # {"in_ptr0": ["in_ptr0_view0"], ...} + self.buffer_aliases: dict[str, list[str]] = defaultdict(list) + self.has_indirect_indexing = False + + def dtype_to_str(self, dtype: torch.dtype) -> str: + return halide_type(dtype) + + # pyrefly: ignore [bad-override] + def create_cse_var(self, name, bounds=None, dtype=None, shape=None): + self.body.writeline(f"{name} = hl.Func({name!r})") + # pyrefly: ignore [bad-argument-type] + return HalideCSEVariable(name, bounds, dtype, shape) + + def finalize_indexing(self, indices: Sequence[sympy.Expr]): + """ + Hook called right before codegen with every index that will be + used in the fused kernel. + + This populates self.halide_vars/index_replacements/reduction_renames which is an alternate indexing + scheme that avoids using divide and modulus. Instead of xindex/yindex/rindex + we base indexing on a larger number of vars whose product combines to those. + + This function populates self.halide_vars, self.index_replacements, and self.reduction_renames + """ + if self.index_replacements or self.halide_vars or self.reduction_renames: + raise AssertionError( + "indexing state must be empty before finalize_indexing" + ) + size_hint = functools.partial( + V.graph.sizevars.optimization_hint, fallback=sys.maxsize + ) + # pyrefly: ignore [bad-assignment] + indices = dict.fromkeys(map(super().prepare_indexing, indices)) + all_used_symbols = OrderedSet[Any]() + sym_to_node = { + n.symbol(): n + for n in itertools.chain.from_iterable( + [tree.nodes.values() for tree in self.range_trees] + ) + } + + def simplify(expr): + return sympy.simplify( + V.graph.sizevars.remove_precomputed_replacements(expr) + ) + + def visit_modular_indexing(base, divisor, modulus): + if base in sym_to_node: + node = sym_to_node[base] + all_used_symbols.add( + node.root.lookup( + node.divisor * divisor, + V.graph.sizevars.evaluate_min( + modulus, + FloorDiv(node.length, divisor), + ), + ).symbol() + ) + + def visit_floor_div(base, divisor): + if base in sym_to_node: + node = sym_to_node[base] + all_used_symbols.add( + node.root.lookup( + node.divisor * divisor, + FloorDiv(node.length, divisor), + ).symbol() + ) + + # first figure out all_used_symbols to do dead symbol elimination + for index in indices: + if index.has(ModularIndexing): + index.replace( + ModularIndexing( + sympy.Wild("base"), + sympy.Wild("divisor"), + sympy.Wild("modulus"), + ), + visit_modular_indexing, + ) + if index.has(FloorDiv): + index.replace( + FloorDiv( + sympy.Wild("base"), + sympy.Wild("divisor"), + ), + visit_floor_div, + ) + all_used_symbols.update(super().prepare_indexing(index).free_symbols) + + self.has_indirect_indexing = any( + symbol_is_type(sym, SymT.INDIRECT) for sym in all_used_symbols + ) + + had_fallback = False + for tree in reversed(self.range_trees): + nodes = [n for n in tree.nodes.values() if n.symbol() in all_used_symbols] + nodes.sort(key=lambda n: size_hint(n.divisor)) + if not nodes: + nodes.append(tree.lookup(1, tree.numel)) + handled_count = 0 + divisor = sympy.S.One + added_sym_size = [] + # decide on a minimal set of symbols and put them in self.halide_vars + while handled_count < len(nodes) and not eq(tree.numel, divisor): + sizes_to_add = [ + simplify(n.length) for n in nodes if eq(n.divisor, divisor) + ] + handled_count += len(sizes_to_add) + if not sizes_to_add: + raise AssertionError(nodes) + end = divisor * functools.reduce( + lambda a, b: V.graph.sizevars.evaluate_max(a, b), + sizes_to_add, + ) + sizes_to_add.extend( + [ + simplify(n.divisor / divisor) + for n in nodes + if lt(divisor, n.divisor) and lt(n.divisor, end) + ] + ) + # pyrefly: ignore [bad-assignment] + while sizes_to_add: + next_size = functools.reduce(sympy.gcd, sizes_to_add) + if eq(next_size, 1): + # sizes share no common factors, e.g [2, 21, 42, 441, 889056] + # TODO(jansel): we should just prevent fusion in cases that hit this + next_size = simplify(tree.numel / divisor) + if eq(next_size, 1): + raise AssertionError("fallback next_size must not be 1") + sizes_to_add = [] + handled_count = len(nodes) + had_fallback = True + sym = sympy_index_symbol(f"h{len(self.halide_vars)}") + # pyrefly: ignore [missing-argument] + if tree.is_reduction: + self.reduction_renames[sym] = sympy_index_symbol( + f"hr{len(self.halide_vars)}" + ) + self.halide_vars[sym] = next_size + added_sym_size.append((sym, next_size)) + divisor *= next_size + new_sizes = [n.length for n in nodes if eq(n.divisor, divisor)] + handled_count += len(new_sizes) + prior_len = len(sizes_to_add) + sizes_to_add = [ + sympy.simplify(s / next_size) + for s in sizes_to_add + if not eq(s, next_size) + ] + if not (len(sizes_to_add) < prior_len or prior_len == 0): + raise AssertionError("sizes_to_add must shrink") + sizes_to_add.extend(new_sizes) + + # create a mapping to the new set of symbols in self.index_replacements + for node in nodes: + try: + idx = 0 + divisor = 1 + while not eq(node.divisor, divisor): + sym, size = added_sym_size[idx] + idx += 1 + divisor *= size + length = 1 + expr = sympy.S.Zero + while not eq(node.length, length): + sym, size = added_sym_size[idx] + idx += 1 + expr += length * sym + length *= size + self.index_replacements[node.symbol()] = expr + except IndexError: + if not had_fallback: + raise AssertionError("IndexError without fallback") from None + full_index = sympy.S.Zero + stride = sympy.S.One + for sym, size in added_sym_size: + full_index += stride * sym + stride *= size + self.index_replacements[node.symbol()] = ( + V.graph.sizevars.simplify_with_ranges( + ModularIndexing(full_index, node.divisor, node.length), + self.halide_vars, # type: ignore[arg-type] + ) + ) + + # codegen the variable definitions + for sym in self.halide_vars: + self.indexing_code.writeline(f"{sym} = hl.Var({sym.name!r})") + if self.reduction_renames: + self.codegen_rdom( + "rdom", + {rv: self.halide_vars[v] for v, rv in self.reduction_renames.items()}, + ) + + def setup_dom_indexing(self): + """RDom based indexing uses explicit iteration ranges for Func updates""" + prefix = "i" if self.inside_reduction else "o" + if prefix in self.dom_renames: + return self.dom_renames[prefix] + + renames = {} + for var in self.halide_vars: + if not self.inside_reduction and var in self.reduction_renames: + continue + m = re.match(r"^h(\d+)$", var.name) + if not m: + raise AssertionError(f"unexpected halide var name {var.name}") + renames[var] = sympy_index_symbol(f"h{prefix}{m.group(1)}") + + self.codegen_rdom( + f"{prefix}dom", {rv: self.halide_vars[v] for v, rv in renames.items()} + ) + + self.dom_renames[prefix] = renames + return renames + + def codegen_rdom(self, name, vars): + rsizes = [ + f"hl.Range(0, {self.kexpr(self.rename_indexing(size))})" + for size in vars.values() + ] + self.indexing_code.writeline(f"{name} = hl.RDom([{', '.join(rsizes)}])") + for i, rsym in enumerate(vars.keys()): + self.indexing_code.writeline(f"{rsym} = {name}[{i}]") + + def prepare_indexing( + self, + index: sympy.Expr, + ): + index = super().prepare_indexing(index) + index = sympy_subs(index, self.index_replacements) + return V.graph.sizevars.simplify_with_ranges(index, self.halide_vars) # type: ignore[arg-type] + + def sym_size(self, sym): + """The size of an index symbol""" + if symbol_is_type(sym, SymT.TMP): + return self.lookup_cse_var(sym.name).indirect_indexing_size + return self.halide_vars[sym] + + def indexing_to_dimensions(self, var: str, index: sympy.Expr, is_store: bool): + """Convert address-based indexing into dimensions using self.halide_vars""" + symbols = [] + for sym in sorted(index.free_symbols, key=lambda x: x.name): # type: ignore[attr-defined] + if symbol_is_type(sym, (SymT.HALIDE, SymT.TMP)): + symbols.append(sym) + else: + if not symbol_is_type( + sym, + ( + SymT.UNBACKED_INT, + SymT.SIZE, + SymT.PRECOMPUTED_SIZE, + ), + ): + raise AssertionError(sym) + + # group the expression by variables used + offset = sympy.S.Zero + split_expr = dict.fromkeys(symbols, sympy.S.Zero) + split_failed: list[tuple[list[sympy.Symbol], sympy.Expr]] = [] + index = sympy.expand(self.rename_indexing(index)) + for part in index.args if isinstance(index, sympy.Add) else [index]: + part_vars = [v for v in part.free_symbols if v in split_expr] + if len(part_vars) == 0: + offset += part + elif len(part_vars) == 1: + split_expr[part_vars[0]] += part + else: + new_split_failed = [] + for i in range(len(split_failed)): + if split_failed[i] is None: + raise AssertionError("split_failed entry must not be None") + other_vars, other_part = split_failed[i] + if OrderedSet(other_vars) & OrderedSet(part_vars): + part_vars.extend([v for v in other_vars if v not in part_vars]) + part += other_part + else: + new_split_failed.append((other_vars, other_part)) + split_failed = [*new_split_failed, (part_vars, part)] + + def expr_to_dimension(expr, syms): + expr = sympy.factor(expr) + if len(syms) == 1: + stride_wild = sympy.Wild("wild", exclude=symbols) + m = expr.match(stride_wild * syms[0]) + if m: + return DimensionInfo( + syms[0], self.sym_size(syms[0]), m[stride_wild] + ) + if is_store: + raise AssertionError(expr) + length = sympy.simplify( + sympy_subs(expr, {sym: self.sym_size(sym) - 1 for sym in syms}) + 1 + ) + stride = sympy.S.One + if isinstance(expr, sympy.Mul): + for term in expr.args: + if isinstance(term, sympy.Integer): + stride *= term + expr = sympy.simplify(expr / term) + length = sympy.simplify(sympy.ceiling(length / term)) + return DimensionInfo(expr, length, stride) + + # try to turn each group into a strided access + dims = [] + for syms, expr in split_failed: + for v in syms: + expr += split_expr.pop(v) + dims.append(expr_to_dimension(expr, syms)) + for sym, expr in split_expr.items(): + dims.append(expr_to_dimension(expr, [sym])) + dims.sort( + key=lambda d: V.graph.sizevars.optimization_hint( + d.stride, fallback=sys.maxsize + ) + ) # type: ignore[arg-type] + + if not dims: # scalar load/store + if self.has_indirect_indexing: + # workaround https://github.com/halide/Halide/issues/8338 + dims.append(DimensionInfo(sympy.S.Zero, 1, 1)) + elif not V.graph.sizevars.statically_known_equals(dims[0].stride, 1): + # Halide assumes dimension 0 is stride == 1, so add a dummy dimension + dims.insert( + 0, DimensionInfo(sympy.S.Zero, 1 if is_store else dims[0].stride, 1) + ) + + if dims and not is_store: + if var in self.buffer_offsets and V.graph.sizevars.statically_known_geq( + offset, self.buffer_offsets[var] + ): + # reuse the existing offset to avoid needing an input alias + self.apply_offset_to_dimension(dims, offset - self.buffer_offsets[var]) + offset = self.buffer_offsets[var] + elif V.graph.sizevars.statically_known_gt( + offset, 0 + ): # TODO(jansel): negative offsets + # roll the offset into the dimensions for cleaner indexing + self.apply_offset_to_dimension(dims, offset) + offset = 0 + + orig_var = var + for i in itertools.count(): + if self.install_dims(var, dims, offset, is_store): + return var, dims + if is_store: + raise AssertionError("install_dims must succeed for stores") + var = f"{orig_var}_view{i}" + if var not in self.buffer_aliases[orig_var]: + self.buffer_aliases[orig_var].append(var) + + def install_dims(self, var, dims, offset, is_store): + """Try to set self.buffer_dimensions[var], return True on success""" + if var not in self.buffer_dimensions: + self.buffer_dimensions[var] = dims + self.buffer_offsets[var] = offset + return True + if self.buffer_offsets[var] != offset or len( + self.buffer_dimensions[var] + ) != len(dims): + return False + if is_store: + return self.buffer_dimensions[var] == dims + for old, new in zip(self.buffer_dimensions[var], dims): + if old.stride != new.stride: + return False + if old.size != new.size or old.expr != new.expr: + old.size = V.graph.sizevars.evaluate_max(old.size, new.size) + old.expr = None + return True + + def apply_offset_to_dimension(self, dims, offset): + if offset == 0: + return + for i in reversed(range(len(dims))): + if dims[i].stride == 1 or V.graph.sizevars.statically_known_geq( + offset, dims[i].stride + ): + part = FloorDiv(offset, dims[i].stride) + offset -= part * dims[i].stride + dims[i].expr += part + if offset != 0: + raise AssertionError(f"offset must be fully applied, got {offset}") + + def used_dims_from_index(self, index: sympy.Expr): + """Detect which range trees are used to populate HalideCSEVariable.used_dims""" + used_dims = OrderedSet[sympy.Symbol]() + for sym in index.free_symbols: + if not isinstance(sym, sympy.Symbol): + raise AssertionError(f"expected sympy.Symbol, got {type(sym)}") + if symbol_is_type(sym, SymT.TMP): + # indirect indexing + cse_var = self.lookup_cse_var(sym.name) + if not ( + isinstance(cse_var, HalideCSEVariable) + and cse_var.used_dims is not None + ): + raise AssertionError( + "cse_var must be HalideCSEVariable with used_dims" + ) + used_dims.update(cse_var.used_dims) + elif symbol_is_type(sym, SymT.HALIDE): + used_dims.add(sym) + elif symbol_is_type( + sym, (SymT.UNBACKED_INT, SymT.SIZE, SymT.PRECOMPUTED_SIZE, SymT.INDEX) + ): + pass + else: + raise NotImplementedError(f"unhandled symbol {sym}") + return self.sort_used_dims(used_dims) + + def sort_used_dims(self, used_dims): + if not all(isinstance(x, sympy.Expr) for x in used_dims): + raise AssertionError("used_dims must all be sympy expressions") + ordered = [ + sym + for sym in itertools.chain( + self.halide_vars, self.reduction_renames.values() + ) + if sym in used_dims + ] + if len(ordered) != len(used_dims): + raise AssertionError( + f"expected {len(used_dims)} ordered dims, got {len(ordered)}" + ) + return ordered + + def make_index_str(self, dims, replacements=None, zero_vars=False): + index_str = ", ".join(d.index_str(replacements, zero_vars) for d in dims) + if len(dims) == 0: + index_str = "()" + elif len(dims) == 1: + # workaround for https://github.com/halide/Halide/issues/8299 + index_str = f"{index_str}," + return index_str + + def load(self, name: str, index: sympy.Expr): + """Codegen a load from an InputBuffer""" + var = self.args.input(name) + index = self.prepare_indexing(index) + var, dims = self.indexing_to_dimensions(var, index, False) + line = f"{var}[{self.make_index_str(dims)}]" + dtype = V.graph.get_dtype(name) + if dtype in (torch.float16, torch.bfloat16): + dtype = torch.float32 + line = f"hl.cast(hl.Float(32), {line})" + + if self._load_mask: + if not ( + isinstance(self._load_mask, HalideCSEVariable) + and self._load_mask.used_dims is not None + ): + raise AssertionError( + "_load_mask must be HalideCSEVariable with used_dims" + ) + used_dims = OrderedSet( + (*self.used_dims_from_index(index), *self._load_mask.used_dims) + ) + result = self.newfunc(self.sort_used_dims(used_dims)) + if result.used_dims: + self.body.writeline(f"{result.name}_mask = hl.RDom([hl.Range(0, 1)])") + self.body.writeline(f"{result.name}_mask.where({self._load_mask})") + other = self.kexpr(self._load_other or 0) # type: ignore[arg-type] + self.body.writeline( + f"{result} = hl.cast({halide_type(dtype)}, {other})" + ) + self.body.writeline( + f"{result} = {line} + hl.cast({halide_type(dtype)}, {result.name}_mask)" + ) + else: + # scalar case + self.body.writeline( + f"{result} = hl.select({self._load_mask}, {line}, hl.cast({halide_type(dtype)}, 0))" + ) + return result + else: + return self.genfunc(line, self.used_dims_from_index(index)) + + def lookup_cse_var(self, name: str): + return self.cse.varname_map[re.sub(r"\[.*", "", name)] + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + """Codegen a store to an OutputBuffer""" + if not isinstance(value, HalideCSEVariable): + raise AssertionError(f"expected HalideCSEVariable, got {type(value)}") + var = self.args.output(name) + index = self.prepare_indexing(index) + var, dims = self.indexing_to_dimensions(var, index, True) + if self.is_indirect_indexing(index) or mode is not None: + replacements = self.setup_dom_indexing() + index_str = self.make_index_str(dims, replacements) + value_str = value.subs_str(replacements) + undef_dims = (", ".join(["hl.Var()"] * len(dims))) or "()" + self.body.writeline( + DeferredLine(name, f"{var}[{undef_dims}] = hl.undef({var}.type())") + ) + else: + index_str = self.make_index_str(dims, zero_vars=True) + value_str = str(value) + + dtype = V.graph.get_dtype(name) + if mode is None: + line = f"{var}[{index_str}] = hl.cast({halide_type(dtype)}, {value_str})" + elif mode == "atomic_add": + line = f"{var}[{index_str}] += hl.cast({halide_type(dtype)}, {value_str})" + else: + raise NotImplementedError(f"store mode={mode}") + self.body.writeline(DeferredLine(name, line)) + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: + """Codegen a reduction operation""" + if not self.inside_reduction: + raise AssertionError("reduction called outside reduction") + if self._load_mask: + raise AssertionError("reduction with active load mask") + cache_key = (src_dtype, reduction_type, value) + if cache_key in self.cse.reduction_cache: + return self.cse.reduction_cache[cache_key] + + if isinstance(value, tuple): + if reduction_type != "welford_combine": + raise AssertionError(f"expected welford_combine, got {reduction_type}") + self.cse.reduction_cache[cache_key] = result_tuple = ( + self.welford_combine_impl(*value) + ) + return result_tuple + + if not (isinstance(value, HalideCSEVariable) and value.used_dims is not None): + raise AssertionError("value must be HalideCSEVariable with used_dims") + reduction_vars = OrderedSet(self.reduction_renames) + result_var = self.newfunc( + [v for v in value.used_dims if v not in reduction_vars], + ) + if reduction_vars - OrderedSet(value.used_dims): + value = self.genfunc( + f"{value}", + self.sort_used_dims(OrderedSet((*value.used_dims, *reduction_vars))), + shape=value.shape, + ) + value_str = value.subs_str(self.reduction_renames) + default = ir.Reduction.default_accumulator(reduction_type, src_dtype) + acc_type = halide_acc_type(dtype) + + if reduction_type in ("argmax", "argmin"): + index = f"{result_var.name}_{reduction_type}" + self.body.writeline(f"{index} = hl.{reduction_type}(rdom, {value_str})") + # turn the N-D argmax index into a 1-D one + parts = [] + stride = 1 + for i, sym in enumerate(self.reduction_renames): + # pyrefly: ignore [bad-argument-type] + parts.append(f"{index}[{i}]") + if stride != 1: + # pyrefly: ignore [unsupported-operation] + parts[-1] += f"*{stride}" + stride *= self.halide_vars[sym] + self.body.writeline(f"{result_var} = {' + '.join(parts)}") + elif reduction_type == "welford_reduce": + # TODO(jansel): implement welford_reduce without fallback + result_var = self.welford_reduce_fallback(dtype, value) + else: + combine_fn = get_reduction_combine_fn(reduction_type, acc_type) + with V.set_ops_handler(AddParenHandler(HalideOverrides())): + combine_str = combine_fn(result_var, value_str) # type: ignore[arg-type] + default_str = f"hl.cast({acc_type}, {halide_constant(default)})" + self.body.writeline(f"{result_var} = {default_str}") + self.body.writeline(f"{result_var} = {combine_str}") + + self.cse.reduction_cache[cache_key] = result_var + return result_var + + def welford_combine_impl(self, mean, m2, weight): + if not (isinstance(mean, HalideCSEVariable) and mean.used_dims is not None): + raise AssertionError("mean must be HalideCSEVariable with used_dims") + if not (isinstance(m2, HalideCSEVariable) and m2.used_dims is not None): + raise AssertionError("m2 must be HalideCSEVariable with used_dims") + if not (isinstance(weight, HalideCSEVariable) and weight.used_dims is not None): + raise AssertionError("weight must be HalideCSEVariable with used_dims") + used_dims = OrderedSet( + (*mean.used_dims, *m2.used_dims, *weight.used_dims) or self.halide_vars + ) + used_dims -= OrderedSet(self.reduction_renames) + result_var = self.newfunc(self.sort_used_dims(used_dims)) + default = [f"hl.cast({x.name}.type(), 0)" for x in (mean, m2, weight)] + pfx = result_var.name + self.body.writeline(f"{result_var} = hl.Tuple([{', '.join(default)}])") + self.body.writeline(f"{pfx}_mean_1 = {result_var}[0]") + self.body.writeline(f"{pfx}_m2_1 = {result_var}[1]") + self.body.writeline(f"{pfx}_weight_1 = {result_var}[2]") + self.body.writeline(f"{pfx}_mean_2 = {mean.subs_str(self.reduction_renames)}") + self.body.writeline(f"{pfx}_m2_2 = {m2.subs_str(self.reduction_renames)}") + self.body.writeline( + f"{pfx}_weight_2 = {weight.subs_str(self.reduction_renames)}" + ) + self.body.writeline(f"{pfx}_delta = {pfx}_mean_2 - {pfx}_mean_1") + self.body.writeline(f"{pfx}_new_weight = {pfx}_weight_1 + {pfx}_weight_2") + self.body.writeline( + f"{pfx}_w2_over_w = hl.select({pfx}_new_weight == 0.0, 0.0, {pfx}_weight_2 / {pfx}_new_weight)" + ) + update = [ + f"{pfx}_mean_1 + {pfx}_delta * {pfx}_w2_over_w", + f"{pfx}_m2_1 + {pfx}_m2_2 + {pfx}_delta * {pfx}_delta * {pfx}_weight_1 * {pfx}_w2_over_w", + f"{pfx}_new_weight", + ] + self.body.writeline(f"{result_var} = hl.Tuple([{', '.join(update)}])") + + unpacked = [] + for i in range(3): + unpacked.append(self.newfunc(result_var.used_dims)) + self.body.writeline(f"{unpacked[-1]} = {result_var}[{i}]") + return tuple(unpacked) + + def scan( + self, + dtypes: tuple[torch.dtype, ...], + combine_fn: Callable[ + [tuple[CSEVariable, ...], tuple[CSEVariable, ...]], tuple[CSEVariable, ...] + ], + values_orig: tuple[CSEVariable, ...], + ) -> tuple[CSEVariable, ...]: + if not self.inside_reduction: + raise AssertionError("scan called outside reduction") + if len(dtypes) != len(values_orig): + raise AssertionError( + f"expected {len(values_orig)} dtypes, got {len(dtypes)}" + ) + values: list[HalideCSEVariable] = [] + all_used_dims = OrderedSet[sympy.Symbol]() + + for value in values_orig: + if not ( + isinstance(value, HalideCSEVariable) and value.used_dims is not None + ): + raise AssertionError("value must be HalideCSEVariable with used_dims") + if OrderedSet(value.used_dims) & OrderedSet(self.reduction_renames): + values.append(value) + else: + values.append( + self.genfunc( + f"{value}", + [*value.used_dims, [*self.reduction_renames][:1]], + shape=value.shape, + ) + ) + all_used_dims.update(value.used_dims) + result_var = self.newfunc(self.sort_used_dims(all_used_dims)) + if not ( + result_var.used_dims + and OrderedSet(result_var.used_dims) & OrderedSet(self.reduction_renames) + ): + raise AssertionError("result_var must use reduction dims") + initial = [ + f"hl.cast({halide_acc_type(dtype)}, {value})" + for dtype, value in zip(dtypes, values) + ] + + length = self.kexpr(self.rename_indexing(self.range_trees[-1].numel)) + scan_dom = f"{result_var.name}_rdom" + scan = f"{scan_dom}.x" + self.body.writeline(f"{scan_dom} = hl.RDom([hl.Range(1, {length})])") + + if len(self.reduction_renames) != 1: + raise AssertionError("multi-dimensional scan not implemented") + (scan_var,) = [*self.reduction_renames] # type: ignore[misc] + scan_renames_cur = {scan_var: sympy_index_symbol(scan)} + scan_renames_pri = {scan_var: sympy_index_symbol(scan) - 1} + + if len(values) == 1: + + def maybe_tuple(x): + return x[0] + + read_left = [result_var.subs_str(scan_renames_pri)] + read_right = [result_var.subs_str(scan_renames_cur)] + else: + + def maybe_tuple(x): + return f"hl.Tuple([{', '.join(x)}])" + + read_left = [ + result_var.subs_str(scan_renames_pri) + f"[{i}]" + for i in range(len(values)) + ] + read_right = [ + result_var.subs_str(scan_renames_cur) + f"[{i}]" + for i in range(len(values)) + ] + + self.body.writeline(f"{result_var} = {maybe_tuple(initial)}") + + # Disable CSE for update fn + with V.set_ops_handler(AddParenHandler(HalideOverrides())): + combine_str = combine_fn(read_left, read_right) # type: ignore[arg-type] + self.body.writeline( + f"{result_var.subs_str(scan_renames_cur)} = {maybe_tuple(combine_str)}" + ) + + if len(values) == 1: + return (result_var,) + + unpack_vars = [self.newfunc(self.sort_used_dims(all_used_dims)) for _ in values] + for i, v in enumerate(unpack_vars): + self.body.writeline(f"{v} = {result_var}[{i}]") + return tuple(unpack_vars) + + def genfunc( + self, + line, + used_dims, + *, + bounds=ValueRanges.unknown(), + shape: BlockShapeType = None, + ) -> HalideCSEVariable: + var = self.cse.generate(self.body, line, bounds=bounds, shape=shape) + if not isinstance(var, HalideCSEVariable): + raise AssertionError(f"expected HalideCSEVariable, got {type(var)}") + var.used_dims = used_dims + return var + + def newfunc(self, used_dims, *, shape: BlockShapeType = None) -> HalideCSEVariable: + var = self.cse.newvar(shape=shape) + if not isinstance(var, HalideCSEVariable): + raise AssertionError(f"expected HalideCSEVariable, got {type(var)}") + var.used_dims = used_dims + return var + + def halide_buffer_numel(self, name: str): + """ + We map all tensors to 1D buffers in Halide since Halide has trouble representing some strides that PyTorch + supports. If there are gaps in the underlying layout the numel we pass to Halide includes the gaps while + PyTorch's numel excludes them. + """ + return V.graph.get_buffer(name).get_layout().storage_size() + + def halide_argdefs(self): + """ + Halide requires scalar inputs before outputs, so need to reorder args. + """ + + def arg_order(arg_tuple): + _call_str, arg = arg_tuple + if isinstance(arg, SizeArg): + return 1 # this would normally be at the end, move it to middle + elif "out_ptr" in arg.name: + return 2 + else: + if "in_ptr" not in arg.name: + raise AssertionError(f"expected in_ptr in arg name, got {arg.name}") + return 0 + + result: list[tuple[str | None, KernelArgType]] = [] + _, a, b, _ = self.args.python_argdefs() + for call_str, arg in sorted(zip(a, b), key=arg_order): + result.append((call_str, arg)) + if isinstance(arg, TensorArg): + if not (arg.offset == 0 and arg.alias_of is None): + raise AssertionError("TensorArg must have zero offset and no alias") + result.extend( + ( + None, + TensorArg( + alias, + arg.buffer, + arg.dtype, + arg.offset, + alias_of=arg.name, + ), + ) + for alias in self.buffer_aliases.get(arg.name, ()) + ) + return result + + def halide_kernel_meta(self) -> HalideMeta: + """Compute metadata required by codecache.py""" + argtypes = [] + for _, arg in self.halide_argdefs(): + if isinstance(arg, SizeArg): + shape = None + stride = None + offset = None + dtype = "long" + else: + shape = [ + cexpr(self.rename_indexing(x.size)) + for x in self.buffer_dimensions[arg.name] + ] + stride = [ + cexpr(self.rename_indexing(x.stride)) + for x in self.buffer_dimensions[arg.name] + ] + if len(shape) != len(stride): + raise AssertionError( + f"shape/stride length mismatch: {len(shape)} vs {len(stride)}" + ) + offset = cexpr(self.buffer_offsets[arg.name]) + dtype = f"{DTYPE_TO_CPP[arg.dtype]}*" + argtypes.append( + HalideInputSpec( + dtype, + arg.name, + shape=shape, + stride=stride, + offset=offset, + alias_of=arg.alias_of, + ) + ) + + current_device = V.graph.get_current_device_or_throw() + if current_device.type == "cpu": + target = [config.halide.cpu_target] + scheduler = config.halide.scheduler_cpu + scheduler_flags = { + "parallelism": parallel_num_threads(), + } + cuda_device = None + else: + if current_device.type != "cuda": + raise AssertionError("only cpu/cuda supported") + if current_device.index > 0: + raise AssertionError("only default device supported") + target = [config.halide.gpu_target] + scheduler = config.halide.scheduler_cuda + capability = torch.cuda.get_device_properties(current_device) + if "cuda_capability" not in target[0]: + for major, minor in [(8, 6), (8, 0), (7, 5), (7, 0), (6, 1)]: + if capability.major >= major and capability.minor >= minor: + target.append(f"cuda_capability_{major}{minor}") + break + target.append("user_context") + scheduler_flags = { + "parallelism": capability.multi_processor_count, + # TODO(jansel): explore other flags, see: + # grep parser.parse ~/Halide/src/autoschedulers/anderson2021/AutoSchedule.cpp + } + cuda_device = max(0, current_device.index) + + # strict_float is required for correctness + target.append("strict_float") + + # without this we will initialize cuda once per kernel and hit errors + target.append("no_runtime") + + if not config.halide.asserts: + target.append("no_asserts") + + if config.halide.debug: + target.append("debug") + + if "64" in self.index_dtype: + # TODO(jansel): it is unclear if this does anything, since input sizes are still int32 + target.append("large_buffers") + + return HalideMeta( + argtypes, + target="-".join(target), + scheduler=scheduler, + scheduler_flags=scheduler_flags, # type: ignore[arg-type] + cuda_device=cuda_device, + ) + + def codegen_kernel(self, name=None): + """Called at the end to generate a final kernel string""" + if self.args.inplace_buffers: + raise Unsupported("inplace_buffers") + meta = self.halide_kernel_meta() # ensure needed args are added early + code = IndentedBuffer() + code.splice( + """ + import halide as hl + from torch._inductor.runtime import halide_helpers + from math import inf, nan + + @hl.generator(name="kernel") + class Kernel: + """, + strip=True, + ) + code.do_indent() + for _, arg in self.halide_argdefs(): + if isinstance(arg, SizeArg): + code.writeline(f"{arg.name} = hl.InputScalar({self.index_dtype})") + else: + if not arg.buffer: + raise AssertionError(arg) + argcls = "hl.OutputBuffer" if "out" in arg.name else "hl.InputBuffer" + argtype = halide_type(arg.dtype) + ndim = len(self.buffer_dimensions[arg.name]) + code.writeline(f"{arg.name} = {argcls}({argtype}, {ndim})") + code.splice( + """ + def generate(g): + """ + ) + code.do_indent() + for _, arg in self.halide_argdefs(): + code.writeline(f"{arg.name} = g.{arg.name}") + for old, new in self.args.aliases(): + code.writeline(f"{old} = {new}") + code.splice(self.indexing_code) + + def update_index(m): + var = cast(HalideCSEVariable, self.cse.varname_map[m.group(1)]) + if var.used_dims is None: + raise AssertionError(var) + return str(var) + + for line in self.body._lines: + if isinstance(line, str): + # fill in missing indices + line = HalideCSEVariable.undefined_re.sub(update_index, line) + code.writeline(line) + code.writeline("") + code.writeline("assert g.using_autoscheduler()") + + for _, arg in self.halide_argdefs(): + # fallback=1 below because halide requires buffers to be at least as large as the estimates + # This causes crashes if our estimate is greater than the vector length + # https://github.com/halide/Halide/issues/3103 + if isinstance(arg, SizeArg): + hint = V.graph.sizevars.optimization_hint(arg.expr, fallback=1) + code.writeline(f"{arg.name}.set_estimate({hint})") + else: + dims = self.buffer_dimensions[arg.name] + range_hints = [] + for i, dim in enumerate(dims): + hint = self._autoscheduler_workarounds( + V.graph.sizevars.optimization_hint(dim.size, fallback=1), dims + ) + # pyrefly: ignore [bad-argument-type] + range_hints.append(f"hl.Range(0, {hint})") + if "out" not in arg.name: + code.writeline(f"{arg.name}.dim({i}).set_min(0)") + try: + code.writeline( + f"{arg.name}.dim({i}).set_stride({int(dim.stride)})" + ) + except TypeError: + pass # not integer + try: + code.writeline( + f"{arg.name}.dim({i}).set_extent({int(dim.size)})" + ) + except TypeError: + pass # not integer + code.writeline(f"{arg.name}.set_estimates([{', '.join(range_hints)}])") + + code.do_unindent(2) + code.splice( + """ + if __name__ == "__main__": + hl.main() + """.rstrip(), + ) + if meta.scheduler: + code.splice( + f""" + else: + hl.load_plugin({HalideCodeCache.find_libautoschedule(meta.scheduler)!r}) + target = hl.Target({meta.target!r}) + autoscheduler = hl.AutoschedulerParams({meta.scheduler!r}, {meta.scheduler_flags!r}) + with hl.GeneratorContext(target, autoscheduler): + gen = Kernel() + pipeline = gen._build_pipeline() + # gen.compile_to_callable() does not run the autoscheduler + pipeline.apply_autoscheduler(target, autoscheduler) + kernel = pipeline.compile_to_callable([ + gen._get_input_parameter(a.name)._to_argument() + for a in gen._get_arginfos() + if a.dir == hl.ArgInfoDirection.Input + ], target) + """, + strip=True, + ) + else: + code.splice( + f""" + else: + with hl.GeneratorContext(hl.Target({meta.target!r})): + kernel = Kernel().compile_to_callable() + """, + strip=True, + ) + return code.getvalue() + + @staticmethod + def _autoscheduler_workarounds(n, dims): + if ( + len(dims) == 1 + and config.halide.scheduler_cuda == "Anderson2021" + and V.graph.get_current_device_or_throw().type == "cuda" + ): + # workaround https://github.com/halide/Halide/issues/8246 + n = max(2, n) + return n + + def call_kernel(self, name: str, node=None, deallocate_ws: bool = True): + """Codegen a call to this kernel""" + wrapper = V.graph.wrapper_code + call_args = [f"{n}" for n, arg in self.halide_argdefs() if arg.alias_of is None] + current_device = V.graph.get_current_device_or_throw() + if current_device.type == "cuda": + stream_name = wrapper.write_get_raw_stream( + current_device.index, V.graph.name + ) + call_args.append(stream_name) + wrapper.generate_kernel_call( + name, + call_args, + device=current_device, + triton=False, + ) + + def generate_assert(self, check): + return False # TODO(jansel): support asserts + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ): + pass # TODO(jansel): support asserts + + +class HalideScheduling(SIMDScheduling): + kernel_type = HalideKernel # type: ignore[arg-type,assignment] + + @classmethod + def get_backend_features(cls, device: torch.device) -> OrderedSet[BackendFeature]: + result = OrderedSet( + [ + BackendFeature.TUPLE_REDUCTION, + BackendFeature.PREFER_STORE_LOOP_ORDER, + BackendFeature.REDUCE_TO_SINGLE_ELEMENT, + ] + ) + if config.halide.scan_kernels: + result.add(BackendFeature.SCAN) + return result + + def define_kernel(self, src_code, node_schedule, kernel): + """Codegen kernel definition to go in output wrapper code""" + wrapper = V.graph.wrapper_code + if src_code in wrapper.src_to_kernel: + kernel_name = wrapper.src_to_kernel[src_code] + else: + kernel_name = f"halide_kernel_{wrapper.next_kernel_suffix()}" + wrapper.src_to_kernel[src_code] = kernel_name + wrapper.add_import_once( + "from torch._inductor.runtime.hints import HalideMeta, HalideInputSpec" + ) + + compile_wrapper = IndentedBuffer() + compile_wrapper.writeline( + f"async_compile.halide({kernel.halide_kernel_meta()!r}, '''" + ) + compile_wrapper.splice(src_code, strip=True) + compile_wrapper.writeline("''')") + + origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper) + metadata_comment = f"{origins}\n{detailed_origins}" + wrapper.define_kernel( + kernel_name, compile_wrapper.getvalue(), metadata_comment + ) + if is_metric_table_enabled("kernel_metadata"): + log_kernel_metadata(kernel_name, "", src_code) + + return kernel_name diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/memory_planning.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/memory_planning.py new file mode 100644 index 0000000000000000000000000000000000000000..a4c41071e7bcc8a03e7c07f74d9c49697a28bc7c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/memory_planning.py @@ -0,0 +1,849 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import collections +import dataclasses +import itertools +import pprint +from typing import Any, Protocol, TYPE_CHECKING + +import torch +from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import Max + +from .. import config +from ..utils import _align, align, cache_on_self, CachedMethod, IndentedBuffer +from ..virtualized import V +from .wrapper import ( + AllocateLine, + BufferLike, + FreeIfNotReusedLine, + MemoryPlanningLine, + NullLine, + ReuseLine, +) + + +if TYPE_CHECKING: + from collections.abc import Iterable + + import sympy + + +@dataclasses.dataclass +class LiveRange: + """ + A range where a given tensor is live. Begin and end are both counters + representing points in the program of grouped memory operations. + Begin is inclusive, end is exclusive. + + Invariant: begin <= end + """ + + begin: float # int | +/-inf + end: float # int | +/-inf + + def contains(self, other: LiveRange): + """Is other entirely within self""" + return self.begin <= other.begin and other.end <= self.end + + def join(self, other: LiveRange): + """Combine two ranges using a union operation""" + return LiveRange(min(self.begin, other.begin), max(self.end, other.end)) + + def __len__(self): + return self.end - self.begin + + +class LiveRanges: + """ + A collection of LiveRange regions, allowing for non-contiguous + live regions. + + Invariant: LiveRanges.ranges is in sorted order and non-overlapping + """ + + def __init__(self, ranges: Iterable[LiveRange]): + ranges = [*sorted(ranges, key=lambda x: x.begin)] + self.ranges = ranges[:1] + for r in ranges[1:]: + if self.ranges[-1].begin > r.begin: + raise AssertionError("ranges must be sorted by begin") + if self.ranges[-1].end >= r.begin: + self.ranges[-1] = LiveRange.join(self.ranges[-1], r) + else: + self.ranges.append(r) + + def overlaps(self, other: LiveRanges): + """Check if any pair of ranges in self and other overlap""" + left = collections.deque(self.ranges) + right = collections.deque(other.ranges) + while left and right: + if left[0].begin > right[0].begin: + left, right = right, left + if left[0].begin > right[0].begin: + raise AssertionError("left should begin no later than right") + if left[0].end > right[0].begin: + return True + left.popleft() + return False + + @property + def begin(self): + return self.ranges[0].begin + + @property + def end(self): + return self.ranges[-1].end + + def __repr__(self): + return f"{self.__class__.__name__}([{', '.join(map(repr, self.ranges))}])" + + +class AllocationTreeNode: + """ + Abstract base class for nodes in allocation pool. + """ + + def allocate(self, block: Allocation, is_last: bool) -> bool: + """ + Try to assign block to a memory location in this pool. Return True if + an assignment was made. + """ + return False + + def get_live_ranges(self) -> LiveRanges: + """Aggregate LiveRanges for all objects below this in tree""" + raise NotImplementedError + + def get_size_hint(self) -> int: + """Number of bytes used for example inputs""" + raise NotImplementedError + + def get_symbolic_size(self) -> sympy.Expr: + """Number of bytes needed at runtime""" + raise NotImplementedError + + def finalize(self, pool, offset) -> AllocationTreeNode: + """Called after all allocations have been made""" + return self + + def is_empty(self): + return False + + +@dataclasses.dataclass +class Allocation(AllocationTreeNode): + """ + Represents memory allocated to a given node in the allocation pool. + """ + + node: BufferLike + live_range: LiveRange + size_hint: int + symbolic_size: sympy.Expr + allocated: bool = False + pool: AllocationPool | None = None + offset: sympy.Expr | None = None + earliest_available: float | None = None + + def __post_init__(self) -> None: + has_unbacked_sym = False + for s in self.node.get_layout().size: + if free_unbacked_symbols(s): + has_unbacked_sym = True + break + + if has_unbacked_sym: + self.earliest_available = self.get_live_ranges().begin + + @property + def device(self): + return self.node.get_device() + + def get_live_ranges(self): + return LiveRanges([self.live_range]) + + def get_size_hint(self): + return self.size_hint + + def get_symbolic_size(self): + return self.symbolic_size + + def mark_allocated(self): + if self.allocated: + raise AssertionError("block already allocated") + self.allocated = True + + def finalize(self, pool, offset): + if not (self.pool is None and self.offset is None): + raise AssertionError("block already finalized") + self.pool = pool + self.offset = offset + return self + + def codegen_alloc_from_pool(self, wrapper): + if not self.pool: + raise AssertionError("block has no pool assigned") + node = self.node + shape = tuple(node.get_size()) + stride = tuple(node.get_stride()) + return wrapper.codegen_alloc_from_pool( + self.pool.name, self.offset, node.get_dtype(), shape, stride + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(" + f"node={self.node.get_name()}, " + f"live_range={self.live_range}, " + f"size_hint={self.size_hint}, " + f"symbolic_size={self.symbolic_size}, " + f"pool={self.pool.name if self.pool else None}, " + f"offset={self.offset})" + ) + + def get_earliest_available(self): + return self.earliest_available + + +@dataclasses.dataclass +class Empty(AllocationTreeNode): + """ + Placeholder to represent empty space in the allocation pool. + Only exists to get the size_hint correct in parent nodes. + """ + + size_hint: int + + def get_live_ranges(self): + return LiveRanges([]) + + def get_size_hint(self): + return self.size_hint + + def get_symbolic_size(self): + return 0 + + def is_empty(self): + return True + + +class MemorySplitProtocol(Protocol): + get_live_ranges: CachedMethod[[], LiveRanges] + get_size_hint: CachedMethod[[], int] + get_symbolic_size: CachedMethod[[], sympy.Expr] + + def _allocate(self, block: Allocation, is_last: bool) -> bool: ... + + +class ClearCacheOnAllocateMixin(MemorySplitProtocol): + """ + Helper to assist in caching get_live_ranges, get_size_hint, and + get_symbolic_size. + """ + + def allocate(self, block: Allocation, is_last: bool): + is_allocated = self._allocate(block, is_last) + if is_allocated: + self.clear_cache() + return is_allocated + + def clear_cache(self): + self.get_live_ranges.clear_cache(self) + self.get_size_hint.clear_cache(self) + self.get_symbolic_size.clear_cache(self) + + +@dataclasses.dataclass +class TemporalSplit(ClearCacheOnAllocateMixin, AllocationTreeNode): + """ + Contains a list of allocations not overlapping in LiveRanges. + + Invariant: no pair (a,b) in self.allocations will have: + a.get_live_ranges().overlaps(b.get_live_ranges()) + """ + + allocations: list[AllocationTreeNode] + + def _allocate(self, block: Allocation, is_last: bool): + slot_size = self.get_size_hint() + block_size = block.get_size_hint() + if not is_last and block_size > slot_size: + return False # doesn't fit + + block_live = block.get_live_ranges() + overlapping = [ + s for s in self.allocations if s.get_live_ranges().overlaps(block_live) + ] + if len(overlapping) > 1: + # TODO(jansel): we could try harder here by merging overlapping in space + return False + elif len(overlapping) == 1: + return overlapping[0].allocate(block, is_last) + else: + block.mark_allocated() + + if len(self.allocations) == 1 and isinstance(self.allocations[-1], Empty): + self.allocations.pop() + + if slot_size == block_size: + # perfect fit + self.allocations.append(block) + elif slot_size > block_size: + self.allocations.append( + SpatialSplit.create(block, slot_size - block_size) + ) + else: # grow this allocation + if not is_last: + raise AssertionError("can only grow allocation when is_last") + self.allocations = [ + *( + SpatialSplit.create(a, block_size - slot_size) + for a in self.allocations + ), + block, + ] + return True + + @cache_on_self + def get_live_ranges(self) -> LiveRanges: + return LiveRanges( + itertools.chain.from_iterable( + x.get_live_ranges().ranges for x in self.allocations + ) + ) + + @cache_on_self + def get_size_hint(self) -> int: + if not self.allocations: + return 0 + return max(x.get_size_hint() for x in self.allocations) + + @cache_on_self + def get_symbolic_size(self) -> sympy.Expr: + if not self.allocations: + return 0 # type: ignore[return-value] + return Max(*[x.get_symbolic_size() for x in self.allocations]) + + def is_empty(self): + return len(self.allocations) == 1 and self.allocations[0].is_empty() + + def finalize(self, pool, offset): + self.allocations = [block.finalize(pool, offset) for block in self.allocations] + self.clear_cache() + if len(self.allocations) == 1: + return self.allocations[0] + return self + + +@dataclasses.dataclass +class SpatialSplit(ClearCacheOnAllocateMixin, AllocationTreeNode): + """ + Contains two allocations, left and right, that do not overlap in space. + Right will be allocated immediately after left in memory. + """ + + left: TemporalSplit + right: TemporalSplit + + @staticmethod + def create(left, extra_space): + if not isinstance(left, AllocationTreeNode): + raise AssertionError(f"expected AllocationTreeNode, got {type(left)}") + if not (isinstance(extra_space, int) and extra_space >= 1): + raise AssertionError( + f"expected positive int extra_space, got {extra_space}" + ) + return SpatialSplit(TemporalSplit([left]), TemporalSplit([Empty(extra_space)])) + + def _allocate(self, block: Allocation, is_last: bool): + return self.left.allocate(block, False) or self.right.allocate(block, is_last) + + @cache_on_self + def get_live_ranges(self): + return LiveRanges( + itertools.chain( + self.left.get_live_ranges().ranges, self.right.get_live_ranges().ranges + ) + ) + + @cache_on_self + def get_size_hint(self) -> int: + return _align(self.left.get_size_hint()) + self.right.get_size_hint() + + @cache_on_self + def get_symbolic_size(self) -> sympy.Expr: + return align(self.left.get_symbolic_size()) + self.right.get_symbolic_size() + + def finalize(self, pool, offset): + self.left = self.left.finalize(pool, offset) + self.right = self.right.finalize( + pool, offset + align(self.left.get_symbolic_size()) + ) + self.clear_cache() + if self.right.is_empty(): + return self.left + return self + + +@dataclasses.dataclass +class AllocationPool: + """ + Represents a pool of allocations that will be generated by a single + call to torch.empty. + """ + + device: torch.device + root: TemporalSplit + can_expand: bool = True + restrict_live_range: LiveRange | None = None + name: str | None = None + names_to_del: list[str] = dataclasses.field(default_factory=list) + creation_cache: dict[str, str] = dataclasses.field(default_factory=dict) + + def __post_init__(self) -> None: + for block in self.root.allocations: + if isinstance(block, Allocation): + self.update_restrict_live_range(block) + + def allocate(self, block: Allocation, is_last: bool): + if ( + self.restrict_live_range is not None + and not self.restrict_live_range.contains(block.live_range) + ): + return False + + block_earliest_available = block.get_earliest_available() + pool_begin = self.root.get_live_ranges().begin + if block_earliest_available and block_earliest_available > pool_begin: + return False + + is_last = self.can_expand and is_last + if self.root.allocate(block, is_last): + self.update_restrict_live_range(block) + return True + + if is_last: + return self.allocate_at_end(block) + + return False + + def update_restrict_live_range(self, block: Allocation): + if block_earliest_available := block.get_earliest_available(): + if self.restrict_live_range is None: + self.restrict_live_range = LiveRange( + block_earliest_available, float("inf") + ) + else: + self.restrict_live_range = LiveRange( + min(self.restrict_live_range.begin, block_earliest_available), + self.restrict_live_range.end, + ) + + def allocate_at_end(self, block): + block.mark_allocated() + self.root = TemporalSplit([SpatialSplit(self.root, TemporalSplit([block]))]) + self.update_restrict_live_range(block) + return True + + def finalize(self, name): + if self.name: + raise AssertionError("pool already finalized") + self.name = name + self.names_to_del.append(name) + self.root.finalize(self, 0) + + def codegen_create(self, wrapper, code: IndentedBuffer): + if not self.name: + raise AssertionError("pool must be finalized before codegen_create") + nbytes = self.root.get_symbolic_size() + for block in self.root.allocations: + if isinstance(block, Allocation) and nbytes == block.get_symbolic_size(): + node = block.node + code.writeline( + wrapper.make_allocation( + self.name, + device=self.device, + dtype=node.get_dtype(), + shape=tuple(node.get_size()), + stride=tuple(node.get_stride()), + ) + ) + return + else: + code.writeline( + wrapper.make_allocation( + self.name, + device=self.device, + dtype=torch.uint8, + shape=(nbytes,), + stride=(1,), + ) + ) + + def codegen_destroy(self, wrapper, code: IndentedBuffer): + code.writeline(wrapper.make_free_by_names(self.names_to_del)) + + def __eq__(self, other): + return self is other + + def __hash__(self): + return id(self) + + +@dataclasses.dataclass +class AllocationPools: + """ + Collection of many AllocationPool objects grouped by device. + """ + + device_to_pools: dict[torch.device, list[AllocationPool]] = dataclasses.field( + default_factory=dict + ) + + def get_pools(self, block): + if block.device not in self.device_to_pools: + self.device_to_pools[block.device] = [] + return self.device_to_pools[block.device] + + def allocate(self, block: Allocation): + pools = self.get_pools(block) + + for pool in pools: + if pool.allocate(block, is_last=pool is pools[-1]): + return + + # everything is full, make a new pool + pools.append( + AllocationPool( + block.device, + TemporalSplit([block]), + can_expand=config.memory_pool != "none", + ) + ) + block.mark_allocated() + + def allocate_output(self, block: Allocation): + """Outputs get different pools so memory gets freed properly""" + pools = self.get_pools(block) + if pools and config.memory_pool in ("outputs", "combined"): + pools[-1].allocate_at_end(block) + else: + # create a new pool + block.mark_allocated() + pools.append( + AllocationPool( + block.device, + TemporalSplit([block]), + can_expand=config.memory_pool == "combined", + ) + ) + + def finalize(self): + """Called at the end of allocation process""" + for i, pool in enumerate( + itertools.chain.from_iterable(self.device_to_pools.values()) + ): + pool.finalize(f"pool{i}") + + def pprint(self): + for pool in itertools.chain.from_iterable(self.device_to_pools.values()): + print() + print(pool.name) + print(pool.root.get_live_ranges()) + pprint.pprint(pool.root) + + +class BufferGroup: + """ + Due to inplace reuse an allocated buffer can have many names. + This tracks these collections of buffers sharing underlying memory. + """ + + def __init__(self, node: BufferLike): + self.node = node + self.names = [node.get_name()] + self.is_output = False + self.allocation: Allocation | None = None + self.live_range = LiveRange(float("inf"), -float("inf")) + + def update_usage(self, timestep: int): + """Expand self.live_range to include timestep""" + self.live_range = LiveRange( + min(timestep, self.live_range.begin), + max(timestep, self.live_range.end), + ) + + def sym_nbytes(self): + return self.node.get_layout().storage_size() * self.node.get_dtype().itemsize + + def make_allocation(self): + if self.allocation: + raise AssertionError("multiple allocations") + if not isinstance(self.live_range.begin, int): + raise AssertionError("live ranges not computed") + nbytes = self.sym_nbytes() + # For now, fallback value will be used if we encounter an unbacked SymInt. The longer-term plan is to have + # size_hint() use better heuristics for unbackeds, at which point the fallback value will be ignored. + size_hint = V.graph.sizevars.optimization_hint(nbytes, fallback=64) + self.allocation = Allocation( + self.node, + self.live_range, + size_hint=size_hint, + symbolic_size=nbytes, + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}({self.names!r}, is_output={self.is_output}, " + f"live_range={self.live_range}" + ) + + +@dataclasses.dataclass +class PoolMemoryPlanningLine(MemoryPlanningLine): + """Abstract base class for {Alloc,Dealloc}FromPoolLine""" + + group: BufferGroup + timestep: int | None = None + + @property + def node(self): + return self.group.node + + +@dataclasses.dataclass +class AllocFromPoolLine(PoolMemoryPlanningLine): + """Similar to AllocationLine, but takes memory from a pool""" + + is_first_pool_usage: bool = False + + def codegen(self, code: IndentedBuffer): + allocation = self.group.allocation + if not (allocation and allocation.pool): + raise AssertionError("group must have an allocation with a pool") + pool = allocation.pool + name = self.node.get_name() + + if self.is_first_pool_usage: + pool.codegen_create(self.wrapper, code) + + pool.names_to_del.extend(self.group.names) + alloc_from_pool, allocation_lines_to_write = allocation.codegen_alloc_from_pool( + self.wrapper + ) + code.writelines(allocation_lines_to_write) + if alloc_from_pool in pool.creation_cache: + code.writeline( + self.wrapper.make_tensor_alias( + name, pool.creation_cache[alloc_from_pool], "alloc" + ) + ) + else: + pool.creation_cache[alloc_from_pool] = name + code.writeline( + f"{self.wrapper.declare}{name} = {alloc_from_pool}{self.wrapper.ending}" + ) + + +@dataclasses.dataclass +class DeallocFromPoolLine(PoolMemoryPlanningLine): + """Similar to FreeIfNotReusedLine, but takes memory from a pool""" + + is_last_pool_usage: bool = False + + def codegen(self, code: IndentedBuffer): + if self.is_last_pool_usage: + if not (self.group.allocation and self.group.allocation.pool): + raise AssertionError("group must have an allocation with a pool") + self.group.allocation.pool.codegen_destroy(self.wrapper, code) + + +@dataclasses.dataclass +class MemoryPlanner: + """ + Coordination object to run memory planning passes during wrapper + codegen. + """ + + wrapper: Any + pools: AllocationPools = dataclasses.field(default_factory=AllocationPools) + buffer_groups: list[BufferGroup] | None = None + + def plan(self, lines: list[Any]) -> list[Any]: + """Call all the memory planning passes in sequence""" + lines = [*lines] + self.drop_removed_buffers(lines) + self.convert_to_pool_lines(lines) + self.compute_live_ranges(lines) + self.allocate_groups() + self.mark_first_last_usage(lines) + return lines + + def drop_removed_buffers(self, lines): + """ + Replace any memory planning lines in V.graph.removed_buffers with NullLine + """ + # drop any removed buffers + for i, line in enumerate(lines): + if isinstance(line, (AllocateLine, FreeIfNotReusedLine, ReuseLine)): + if line.node.get_name() in V.graph.removed_buffers: + lines[i] = NullLine(self.wrapper) + + def compute_buffer_groups(self, lines): + """ + Populates self.buffer_groups with BufferGroup objects that join + allocations with common storage (due to inplace reuse) into a + single object. + """ + name_to_group = {} + for line in lines: + if isinstance(line, AllocateLine): + name = line.node.get_name() + if name in name_to_group: + raise AssertionError(f"duplicate allocation for {name}") + name_to_group[name] = BufferGroup(line.node) + elif isinstance(line, ReuseLine): + old_name = line.node.get_name() + new_name = line.reused_as.get_name() + if new_name in name_to_group: + raise AssertionError(f"duplicate group for reused {new_name}") + # TODO(jansel): we should support reusing buffers created via ExternKernelAlloc + if old_name in name_to_group: + name_to_group[old_name].names.append(new_name) + name_to_group[new_name] = name_to_group[old_name] + + outputs = OrderedSet(V.graph.get_output_names()) + unique_groups = [*{id(g): g for g in name_to_group.values()}.values()] + for group in unique_groups: + group.is_output = any(x in outputs for x in group.names) or any( + any(user.node.get_name() == "OUTPUT" for user in buf.users) + for name in group.names + if (buf := V.graph.scheduler.name_to_buf.get(name)) is not None + ) + + if self.buffer_groups is not None: + raise AssertionError("buffer_groups already computed") + self.buffer_groups = unique_groups + return name_to_group + + def convert_to_pool_lines(self, lines): + """ + Convert AllocateLine/FreeIfNotReusedLine/ReuseLine into their + pool-based counterparts. + """ + name_to_group = self.compute_buffer_groups(lines) + for i, line in enumerate(lines): + if isinstance(line, AllocateLine): + if line.node.get_name() in name_to_group: + lines[i] = AllocFromPoolLine( + self.wrapper, name_to_group[line.node.get_name()] + ) + elif isinstance(line, FreeIfNotReusedLine): + if line.is_reused: + raise AssertionError("expected line not to be reused") + if line.node.get_name() in name_to_group: + lines[i] = DeallocFromPoolLine( + self.wrapper, name_to_group[line.node.get_name()] + ) + elif isinstance(line, ReuseLine): + if line.node.get_name() in name_to_group: + line.delete_old = False + + def compute_live_ranges(self, lines): + """Populate every BufferGroup.live_ranges field based on first/last usage""" + timestep = 0 + worklist = collections.deque(lines) + while worklist: + if isinstance(worklist[0], MemoryPlanningLine): + timestep += 1 + while worklist and isinstance(worklist[0], MemoryPlanningLine): + line = worklist.popleft() + if isinstance(line, PoolMemoryPlanningLine): + line.group.update_usage(timestep) + line.timestep = timestep + else: + worklist.popleft() + + timestep += 1 + if self.buffer_groups is None: + raise AssertionError("buffer_groups not computed") + for group in self.buffer_groups: + if group.is_output: + group.update_usage(timestep) + + def allocate_groups(self): + """ + Assign every allocation to a specific location in a specific AllocationPool. + """ + if config.memory_pool not in ("none", "intermediates", "outputs", "combined"): + raise AssertionError(f"invalid memory_pool {config.memory_pool}") + if self.buffer_groups is None: + raise AssertionError("buffer_groups not computed") + + for group in self.buffer_groups: + group.make_allocation() + + outputs: list[Allocation] = [] + intermediates: list[Allocation] = [] + for group in self.buffer_groups: + if not group.allocation: + raise AssertionError("group has no allocation") + if group.is_output and config.memory_pool != "combined": + outputs.append(group.allocation) + else: + intermediates.append(group.allocation) + + for block in sorted( + outputs, + key=lambda x: ( + x.size_hint, + -len(x.live_range), + ), + ): + self.pools.allocate_output(block) + + for block in sorted( + intermediates, + key=lambda x: ( + -x.size_hint, + -len(x.live_range), + ), + ): + self.pools.allocate(block) + + self.pools.finalize() + + def mark_first_last_usage(self, lines): + """ + Populate the AllocFromPoolLine.is_first_pool_usage and + DeallocFromPoolLine.is_last_pool_usage fields so that pools + are created/destroyed. + """ + seen = OrderedSet[AllocationPool]() + for line in lines: + if isinstance(line, AllocFromPoolLine): + if not line.group.allocation: + raise AssertionError("group has no allocation") + pool = line.group.allocation.pool + if pool is None: + raise AssertionError("allocation has no pool") + if pool not in seen: + line.is_first_pool_usage = True + seen.add(pool) + + seen = OrderedSet[AllocationPool]() + for line in reversed(lines): + if isinstance(line, DeallocFromPoolLine): + if not line.group.allocation: + raise AssertionError("group has no allocation") + pool = line.group.allocation.pool + if pool is None: + raise AssertionError("allocation has no pool") + if pool not in seen: + line.is_last_pool_usage = ( + pool.root.get_live_ranges().end <= line.timestep + ) + seen.add(pool) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/metal_flex_attention_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/metal_flex_attention_template.py new file mode 100644 index 0000000000000000000000000000000000000000..6e1604d730d34088fd68eeee2ac1a6815e721776 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/metal_flex_attention_template.py @@ -0,0 +1,1048 @@ +# mypy: allow-untyped-defs +"""Metal shader template for flex attention on MPS""" + +import itertools +import operator +from collections import namedtuple +from collections.abc import Sequence +from typing import Any + +import torch +from torch.utils._ordered_set import OrderedSet + +from .. import ir + + +METAL_DTYPE_MAP = { + torch.float32: "float", + torch.float16: "half", + torch.bfloat16: "bfloat", +} + +# Captured score_mod/mask_mod buffers may hold more types than q/k/v; elements +# are always loaded and cast to float for use in the (float-typed) op table. +# Integer captures (e.g. document ids) are therefore exact only below 2**24, +# which covers realistic id/index ranges. +CAPTURE_DTYPE_MAP = { + torch.float32: "float", + torch.float16: "half", + torch.bfloat16: "bfloat", + torch.int64: "long", + torch.int32: "int", + torch.int16: "short", + torch.int8: "char", + torch.uint8: "uchar", + torch.bool: "bool", +} + +# log2(e) for converting flex attention stats back +RCP_LN2 = "1.44269504088896340736f" + +# A captured buffer bound as a Metal kernel argument, with its static shape. +_CapturedBuf = namedtuple("_CapturedBuf", ["name", "sizes", "strides", "dtype"]) +# A captured SymInt (dynamic-shape closure) packed into the scalar _params +# buffer; `name` is the unpacked Metal variable holding its runtime value. +_CapturedScalar = namedtuple("_CapturedScalar", ["name"]) + +# Python operator builtins appear in score_mod/mask_mod when a closure does +# arithmetic/comparison on captured SymInts (e.g. q_idx < (s0 // 32) * 32). +# Arithmetic preserves integer typing when both operands are integral, so a +# downstream floordiv/index stays exact; otherwise it falls back to float. +_INT_PRESERVING_OPS = {operator.add: "+", operator.sub: "-", operator.mul: "*"} +_CMP_OPS = { + operator.lt: "<", + operator.le: "<=", + operator.gt: ">", + operator.ge: ">=", + operator.eq: "==", + operator.ne: "!=", +} + +# Fixed score/mask placeholders bound to integer index variables in the kernel; +# the score placeholder (score_val) is the only float-typed fixed input. +_INT_INDEX_VARS = OrderedSet(["b_idx", "h_idx", "m_idx", "n_idx"]) + + +# FX aten target -> (output C type, Metal format string with positional {} placeholders). +aten = torch.ops.aten +prims = torch.ops.prims +_OP_TABLE: dict[Any, tuple[str, str]] = { + # Arithmetic + aten.add.Tensor: ("float", "{} + {}"), + aten.add.Scalar: ("float", "{} + {}"), + aten.sub.Tensor: ("float", "{} - {}"), + aten.sub.Scalar: ("float", "{} - {}"), + aten.mul.Tensor: ("float", "{} * {}"), + aten.mul.Scalar: ("float", "{} * {}"), + # Cast to float so Python truediv semantics hold even when both operands are ints + aten.div.Tensor: ("float", "static_cast({}) / static_cast({})"), + aten.div.Scalar: ("float", "static_cast({}) / static_cast({})"), + aten.neg.default: ("float", "-{}"), + aten.abs.default: ("float", "metal::abs({})"), + # Comparisons + aten.gt.Tensor: ("bool", "{} > {}"), + aten.gt.Scalar: ("bool", "{} > {}"), + aten.ge.Tensor: ("bool", "{} >= {}"), + aten.ge.Scalar: ("bool", "{} >= {}"), + aten.lt.Tensor: ("bool", "{} < {}"), + aten.lt.Scalar: ("bool", "{} < {}"), + aten.le.Tensor: ("bool", "{} <= {}"), + aten.le.Scalar: ("bool", "{} <= {}"), + aten.eq.Tensor: ("bool", "{} == {}"), + aten.eq.Scalar: ("bool", "{} == {}"), + aten.ne.Tensor: ("bool", "{} != {}"), + aten.ne.Scalar: ("bool", "{} != {}"), + aten.logical_and.default: ("bool", "{} && {}"), + aten.logical_or.default: ("bool", "{} || {}"), + aten.logical_not.default: ("bool", "!{}"), + # Math + aten.exp.default: ("float", "metal::precise::exp({})"), + aten.log.default: ("float", "metal::precise::log({})"), + aten.sqrt.default: ("float", "metal::precise::sqrt({})"), + aten.rsqrt.default: ("float", "metal::precise::rsqrt({})"), + aten.tanh.default: ("float", "metal::precise::tanh({})"), + aten.sin.default: ("float", "metal::precise::sin({})"), + aten.cos.default: ("float", "metal::precise::cos({})"), + aten.exp2.default: ("float", "metal::precise::exp2({})"), + # remainder + aten.remainder.Scalar: ("float", "c10::metal::remainder({}, (float){})"), + aten.remainder.Tensor: ("float", "c10::metal::remainder({}, {})"), + aten.maximum.default: ("float", "metal::max({}, {})"), + aten.max.other: ("float", "metal::max({}, {})"), + aten.minimum.default: ("float", "metal::min({}, {})"), + aten.min.other: ("float", "metal::min({}, {})"), + # Bitwise - int output + aten.bitwise_and.Tensor: ("int", "(int){} & (int){}"), + aten.bitwise_and.Scalar: ("int", "(int){} & (int){}"), + aten.bitwise_or.Tensor: ("int", "(int){} | (int){}"), + aten.bitwise_or.Scalar: ("int", "(int){} | (int){}"), + aten.where.self: ("float", "{} ? {} : {}"), + aten._to_copy.default: ("float", "static_cast({})"), + aten.to.dtype: ("float", "static_cast({})"), + prims.convert_element_type.default: ("float", "static_cast({})"), + aten.scalar_tensor.default: ("float", "{}"), +} +del aten, prims + + +def _fx_graph_to_metal( + graph_module: torch.fx.GraphModule, + fixed_inputs: dict[str, str], + captured: dict[str, Any], + output_var: str, + var_prefix: str, + int_ctype: str = "int", +) -> str: + """Compile an FX GraphModule to inline Metal code. + + `fixed_inputs` maps scalar placeholder names (score/b/h/q/kv) to Metal + variables. `captured` maps captured placeholder names to a `_CapturedBuf` + (a tensor, indexed by `aten.index.Tensor` down to a scalar load) or a + `_CapturedScalar` (a SymInt bound directly to a Metal variable). The output + is assigned to `output_var`; `var_prefix` namespaces fresh temps. + """ + var_map: dict[str, str] = {} + views: dict[str, tuple] = {} + # Names of temps/placeholders known to hold an integer value, so operator + # arithmetic on captured SymInts stays in integer math (exact, proper floor). + int_vars: OrderedSet[str] = OrderedSet( + ph for ph, mv in fixed_inputs.items() if mv in _INT_INDEX_VARS + ) + code_lines: list[str] = [] + tmp_counter = itertools.count() + + def _is_int(node) -> bool: + if isinstance(node, bool): + return False + if isinstance(node, int): + return True + return isinstance(node, torch.fx.Node) and node.name in int_vars + + # Only emit nodes the output depends on; this drops dead constant captures + output_node = next(n for n in graph_module.graph.nodes if n.op == "output") + needed: OrderedSet[str] = OrderedSet() + stack = list(output_node.all_input_nodes) + while stack: + nd = stack.pop() + if nd.name not in needed: + needed.add(nd.name) + stack.extend(nd.all_input_nodes) + + def _tmp() -> str: + return f"{var_prefix}{next(tmp_counter)}" + + def _val(node) -> str: + if isinstance(node, torch.fx.Node): + if node.name in views: + raise NotImplementedError( + "flex_attention on MPS: captured buffer used without being " + "fully indexed to a scalar" + ) + return var_map[node.name] + if isinstance(node, bool): + return "true" if node else "false" + if isinstance(node, float): + if node == float("inf"): + return "INFINITY" + if node == float("-inf"): + return "(-INFINITY)" + if node != node: # NaN + return "NAN" + return f"{node}f" + if isinstance(node, int): + return str(node) + return str(node) + + for node in graph_module.graph.nodes: + if node.op == "placeholder": + if node.name in fixed_inputs: + var_map[node.name] = fixed_inputs[node.name] + elif node.name in captured: + cap = captured[node.name] + if isinstance(cap, _CapturedScalar): + var_map[node.name] = cap.name + int_vars.add(node.name) + elif len(cap.sizes) == 0: + var_map[node.name] = f"(float){cap.name}[0]" + else: + views[node.name] = ( + cap.name, + "0", + list(cap.sizes), + list(cap.strides), + ) + else: + var_map[node.name] = f"/* unknown placeholder {node.name} */" + continue + + if node.op == "output": + out_node = node.args[0] + if isinstance(out_node, (tuple, list)): + out_node = out_node[0] + code_lines.append(f"{output_var} = {_val(out_node)};") + continue + + if node.name not in needed: + continue + + if node.op == "get_attr": + raise NotImplementedError( + "flex_attention on MPS does not support constant tensor captures " + "in score_mod/mask_mod yet" + ) + + if node.op != "call_function": + continue + + target = node.target + args = node.args + + # Index a captured buffer: accumulate a flat offset over the leading + # dims, peeling them off; emit a scalar load when fully indexed. + if target == torch.ops.aten.index.Tensor: + base_node, idx_list = args[0], args[1] + if not (isinstance(base_node, torch.fx.Node) and base_node.name in views): + raise NotImplementedError( + "flex_attention on MPS only supports indexing captured buffers" + ) + base, offset, sizes, strides = views[base_node.name] + if any(ix is None for ix in idx_list) or len(idx_list) > len(sizes): + raise NotImplementedError( + "flex_attention on MPS does not support this captured-buffer " + "indexing pattern" + ) + for j, ix in enumerate(idx_list): + term = f"(long)({_val(ix)}) * {strides[j]}" + offset = term if offset == "0" else f"{offset} + {term}" + k = len(idx_list) + rem_sizes, rem_strides = sizes[k:], strides[k:] + if rem_sizes: + views[node.name] = (base, offset, rem_sizes, rem_strides) + else: + t = _tmp() + code_lines.append(f"float {t} = (float){base}[{offset}];") + var_map[node.name] = t + continue + + t = _tmp() + # Python operator builtins on captured SymInts (dynamic-shape closures). + if target in _INT_PRESERVING_OPS: + both_int = _is_int(args[0]) and _is_int(args[1]) + op = _INT_PRESERVING_OPS[target] + ctype = int_ctype if both_int else "float" + code_lines.append(f"{ctype} {t} = {_val(args[0])} {op} {_val(args[1])};") + if both_int: + int_vars.add(node.name) + elif target in _CMP_OPS: + code_lines.append( + f"bool {t} = {_val(args[0])} {_CMP_OPS[target]} {_val(args[1])};" + ) + elif target in (operator.floordiv, operator.mod): + fn = "floor_divide" if target is operator.floordiv else "remainder" + both_int = _is_int(args[0]) and _is_int(args[1]) + if both_int: + a, b, ctype = _val(args[0]), _val(args[1]), int_ctype + else: + a = f"static_cast({_val(args[0])})" + b = f"static_cast({_val(args[1])})" + ctype = "float" + code_lines.append(f"{ctype} {t} = c10::metal::{fn}({a}, {b});") + if both_int: + int_vars.add(node.name) + elif target is operator.neg: + is_int = _is_int(args[0]) + ctype = int_ctype if is_int else "float" + code_lines.append(f"{ctype} {t} = -{_val(args[0])};") + if is_int: + int_vars.add(node.name) + elif target in (operator.and_, operator.or_): + a, b = _val(args[0]), _val(args[1]) + if _is_int(args[0]) and _is_int(args[1]): + op = "&" if target is operator.and_ else "|" + code_lines.append(f"{int_ctype} {t} = {a} {op} {b};") + int_vars.add(node.name) + else: + op = "&&" if target is operator.and_ else "||" + code_lines.append(f"bool {t} = ({a}) {op} ({b});") + elif target in _OP_TABLE: + out_type, fmt = _OP_TABLE[target] + code_lines.append( + f"{out_type} {t} = {fmt.format(*(_val(a) for a in args))};" + ) + elif target == torch.ops.aten.clamp.default: + v = _val(args[0]) + lo = _val(args[1]) if len(args) > 1 and args[1] is not None else None + hi = _val(args[2]) if len(args) > 2 and args[2] is not None else None + if lo is not None and hi is not None: + code_lines.append(f"float {t} = metal::clamp({v}, {lo}, {hi});") + elif lo is not None: + code_lines.append(f"float {t} = metal::max({v}, {lo});") + elif hi is not None: + code_lines.append(f"float {t} = metal::min({v}, {hi});") + else: + code_lines.append(f"float {t} = {v};") + elif target in ( + torch.ops.aten.div.Tensor_mode, + torch.ops.aten.div.Scalar_mode, + ): + # Floor/trunc division (e.g. paged attention's kv_idx // page_size). + mode = args[2] if len(args) > 2 else node.kwargs.get("rounding_mode") + quot = f"static_cast({_val(args[0])}) / static_cast({_val(args[1])})" + if mode == "floor": + code_lines.append(f"float {t} = metal::floor({quot});") + elif mode == "trunc": + code_lines.append(f"float {t} = metal::trunc({quot});") + else: + code_lines.append(f"float {t} = {quot};") + elif target in ( + torch.ops.aten.full_like.default, + torch.ops.aten.full.default, + ): + fill = args[1] if len(args) > 1 else node.kwargs.get("fill_value", 0) + code_lines.append(f"float {t} = {_val(fill)};") + else: + raise NotImplementedError( + f"flex_attention on MPS does not support op {target} in " + f"score_mod/mask_mod yet" + ) + + var_map[node.name] = t + + return "\n".join(code_lines) + + +def _compile_subgraph_to_metal( + graph_module: torch.fx.GraphModule, + placeholder_metal_names: list[str], + captured_meta: list[Any], + output_var: str, + var_prefix: str, + int_ctype: str = "int", +) -> str: + """ + Bind placeholders by position to Metal variable names and emit parts of Metal . + + score_mod placeholders are [score, b, h, q_idx, kv_idx, *captured]; + mask_mod's are [b, h, q_idx, kv_idx, *captured]. The captured placeholders + map positionally to `captured_meta` (each a `_CapturedBuf` or + `_CapturedScalar`). + """ + fixed: dict[str, str] = {} + captured: dict[str, Any] = {} + n_fixed = len(placeholder_metal_names) + for i, node in enumerate( + n for n in graph_module.graph.nodes if n.op == "placeholder" + ): + if i < n_fixed: + fixed[node.name] = placeholder_metal_names[i] + else: + captured[node.name] = captured_meta[i - n_fixed] + return _fx_graph_to_metal( + graph_module, fixed, captured, output_var, var_prefix, int_ctype + ) + + +def _generate_mma_shader( + metal_dtype, + d_qk, + d_v, + kv_dim, + block_m, + block_n, + full_kv_params, + captured_params, + scalar_params_str, + unpack_code, + score_code, + mask_code, + has_full_blocks, + scale, + lse_param="", + lse_write_code="", + max_param="", + max_write_code="", +): + """Generate Metal shader using simdgroup_matrix for Q@K^T.""" + + def _block_loop_body(is_partial): + if is_partial: + mask_section = f""" + bool mask_result = true; +{mask_code} +""" + else: + mask_section = """ + bool mask_result = true; +""" + return f"""\ + for (int tile_start = kv_start; tile_start < kv_end; tile_start += BLOCK_N) {{ + int tile_end = min(tile_start + BLOCK_N, kv_end); + int tile_size = tile_end - tile_start; + + // Load K into KV_tg, zero-padding rows past tile_size for MMA alignment. + for (int i = (int)tid; i < BLOCK_N * D_QK; i += BLOCK_M) {{ + int n_local = i / D_QK; + int d = i % D_QK; + if (n_local < tile_size) {{ + int n_global = tile_start + n_local; + long k_off = b_kv * stride_kz + hkv_idx * stride_kh + (long)n_global * stride_kn + (long)d * stride_kk; + KV_tg[n_local * D_QK + d] = K[k_off]; + }} else {{ + KV_tg[n_local * D_QK + d] = ({metal_dtype})0; + }} + }} + threadgroup_barrier(mem_flags::mem_threadgroup); + + // S = Q_tg @ KV_tg^T via simdgroup MMA. + simdgroup_matrix S_frag[BLOCK_M / 8][BLOCK_N / 8]; + for (int ii = 0; ii < BLOCK_M / 8; ii++) + for (int jj = 0; jj < BLOCK_N / 8; jj++) {{ + S_frag[ii][jj].thread_elements()[0] = 0.0f; + S_frag[ii][jj].thread_elements()[1] = 0.0f; + }} + for (int k = 0; k < D_QK / 8; k++) {{ + simdgroup_matrix<{metal_dtype}, 8, 8> K_frags[BLOCK_N / 8]; + for (int j = 0; j < BLOCK_N / 8; j++) + simdgroup_load(K_frags[j], &KV_tg[j * 8 * D_QK + k * 8], (ulong)D_QK, ulong2(0), true); + for (int i = 0; i < BLOCK_M / 8; i++) {{ + simdgroup_matrix<{metal_dtype}, 8, 8> Q_frag; + simdgroup_load(Q_frag, &Q_tg[i * 8 * D_QK + k * 8], (ulong)D_QK); + for (int j = 0; j < BLOCK_N / 8; j++) + simdgroup_multiply_accumulate(S_frag[i][j], Q_frag, K_frags[j], S_frag[i][j]); + }} + }} + for (int i = 0; i < BLOCK_M / 8; i++) + for (int j = 0; j < BLOCK_N / 8; j++) + simdgroup_store(S_frag[i][j], &S_tg[i * 8 * BLOCK_N + j * 8], (ulong)BLOCK_N); + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Load V into KV_tg (reuses the K slot; safe past the MMA barrier). + for (int i = (int)tid; i < tile_size * D_V; i += BLOCK_M) {{ + int n_local = i / D_V; + int d = i % D_V; + int n_global = tile_start + n_local; + long v_off = b_kv * stride_vz + hkv_idx * stride_vh + (long)n_global * stride_vn + (long)d * stride_vk; + KV_tg[n_local * D_V + d] = V[v_off]; + }} + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Fused per-thread softmax + V accumulation. + if (active) {{ + for (int n_local = 0; n_local < tile_size; n_local++) {{ + int n_idx = tile_start + n_local; + float s = S_tg[(int)tid * BLOCK_N + n_local] * SCALE_VAL; + float score_val = s; +{score_code} + s = score_val; +{mask_section}\ + // s > -inf guards exp(-inf - -inf) = NaN when an entire row is -inf so far. + if (mask_result && s > -INFINITY) {{ + float new_max = metal::max(row_max, s); + float old_scale_v = metal::precise::exp(row_max - new_max); + float p = metal::precise::exp(s - new_max); + row_sum = row_sum * old_scale_v + p; + for (int d = 0; d < D_V; d++) o_acc[d] *= old_scale_v; + for (int d = 0; d < D_V; d++) + o_acc[d] += p * float(KV_tg[n_local * D_V + d]); + row_max = new_max; + }} + }} + }} + threadgroup_barrier(mem_flags::mem_threadgroup); + }}""" + + partial_loop = _block_loop_body(is_partial=True) + full_loop = _block_loop_body(is_partial=False) + + shader = f"""\ +#include +#include +using namespace metal; + +constant int D_QK = {d_qk}; +constant int D_V = {d_v}; +constant int BLOCK_M = {block_m}; +constant int BLOCK_N = {block_n}; +constant int KV_DIM = {kv_dim}; +constant float SCALE_VAL = {scale!r}f; + +kernel void flex_attn_fwd( + device {metal_dtype}* out [[buffer(0)]], + constant {metal_dtype}* Q [[buffer(1)]], + constant {metal_dtype}* K [[buffer(2)]], + constant {metal_dtype}* V [[buffer(3)]], + constant int* kv_num_blocks [[buffer(4)]], + constant int* kv_indices [[buffer(5)]], +{full_kv_params}{captured_params}{lse_param}{max_param}{scalar_params_str}, + uint3 tgpos [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) {{ +{unpack_code} + + int q_block = tgpos.x; + int h_idx = tgpos.y; + int b_idx = tgpos.z; + int b_kv = b_idx % (int)Bkv; + int m_base = q_block * BLOCK_M; + int m_idx = m_base + (int)tid; + bool active = (m_idx < N_Q); + + int hkv_idx = h_idx / (int)gqa_shared_heads; + + threadgroup {metal_dtype} Q_tg[BLOCK_M * D_QK]; + threadgroup {metal_dtype} KV_tg[BLOCK_N * KV_DIM]; + threadgroup float S_tg[BLOCK_M * BLOCK_N]; + + // Q stays resident across all KV tiles. + {{ + long q_base_global = b_idx * stride_qz + h_idx * stride_qh; + for (int i = (int)tid; i < BLOCK_M * D_QK; i += BLOCK_M) {{ + int row = i / D_QK; + int d = i % D_QK; + int global_row = m_base + row; + Q_tg[i] = (global_row < N_Q) + ? Q[q_base_global + (long)global_row * stride_qm + (long)d * stride_qk] + : ({metal_dtype})0; + }} + }} + threadgroup_barrier(mem_flags::mem_threadgroup); + + float row_max = -INFINITY; + float row_sum = 0.0f; + float o_acc[D_V]; + for (int d = 0; d < D_V; d++) o_acc[d] = 0.0f; + + int sparse_q_idx = m_base / (int)SPARSE_Q_BLOCK_SIZE; + long sparse_idx_z = b_idx % SPARSE_Z; + long sparse_idx_hq = h_idx % SPARSE_HQ; + + // Partial blocks: score_mod + mask_mod. + int num_kv_blks = kv_num_blocks[sparse_idx_z * kv_nb_stride_z + sparse_idx_hq * kv_nb_stride_h + sparse_q_idx * kv_nb_stride_q]; + long kv_idx_base = sparse_idx_z * kv_idx_stride_z + sparse_idx_hq * kv_idx_stride_h + (long)sparse_q_idx * kv_idx_stride_q; + + for (int blk = 0; blk < num_kv_blks; blk++) {{ + int kv_block_idx = kv_indices[kv_idx_base + (long)blk * kv_idx_stride_b]; + int kv_start = kv_block_idx * (int)SPARSE_KV_BLOCK_SIZE; + int kv_end = min(kv_start + (int)SPARSE_KV_BLOCK_SIZE, (int)N_KV); + +{partial_loop} + }} +""" + + if has_full_blocks: + shader += f""" + // Full blocks: score_mod only. + int full_num_kv_blks = full_kv_num_blocks[sparse_idx_z * full_kv_nb_stride_z + sparse_idx_hq * full_kv_nb_stride_h + sparse_q_idx * full_kv_nb_stride_q]; + long full_kv_idx_base = sparse_idx_z * full_kv_idx_stride_z + sparse_idx_hq * full_kv_idx_stride_h + (long)sparse_q_idx * full_kv_idx_stride_q; + + for (int blk = 0; blk < full_num_kv_blks; blk++) {{ + int kv_block_idx = full_kv_indices[full_kv_idx_base + (long)blk * full_kv_idx_stride_b]; + int kv_start = kv_block_idx * (int)SPARSE_KV_BLOCK_SIZE; + int kv_end = min(kv_start + (int)SPARSE_KV_BLOCK_SIZE, (int)N_KV); + +{full_loop} + }} +""" + + shader += f""" + if (active) {{ +{lse_write_code}{max_write_code} if (row_sum == 0.0f) row_sum = 1.0f; + long out_base = b_idx * stride_oz + h_idx * stride_oh + (long)m_idx * stride_om; + for (int d = 0; d < D_V; d++) + out[out_base + (long)d * stride_ok] = {metal_dtype}(o_acc[d] / row_sum); + }} +}} +""" + return shader + + +def _generate_metal_shader( + dtype: torch.dtype, + d_qk: int, + d_v: int, + score_mod_graph: torch.fx.GraphModule, + mask_mod_graph: torch.fx.GraphModule, + has_full_blocks: bool, + block_m: int, + scale: float, + score_captured: Sequence[tuple] = (), + mask_captured: Sequence[tuple] = (), + write_lse: bool = False, + write_max: bool = False, + captures_fit_int32: bool = True, +) -> str: + """Generate the complete Metal shader source for flex attention. + + `score_captured` / `mask_captured` describe the captures of score_mod / + mask_mod in placeholder order. Each entry is a tagged tuple: a tensor + capture ("tensor", sizes, strides, dtype) becomes an extra Metal buffer, + while a SymInt capture ("scalar",) is read from the packed scalar buffer. + """ + metal_dtype = METAL_DTYPE_MAP[dtype] + + bytes_per_elem = 4 if dtype == torch.float32 else 2 + kv_dim = max(d_qk, d_v) + + # simdgroup MMA needs each tile dim a multiple of 8. + use_mma = (d_qk % 8 == 0) and (d_v % 8 == 0) and (block_m % 8 == 0) + block_n = 0 + + if use_mma: + # Q_tg + KV_tg + S_tg must fit in the 32KB threadgroup memory budget. + q_tg_bytes = block_m * d_qk * bytes_per_elem + budget = 32768 - q_tg_bytes + per_n = kv_dim * bytes_per_elem + block_m * 4 + max_block_n = budget // per_n + block_n = min(32, max_block_n) + block_n = (block_n // 8) * 8 + if block_n < 8: + use_mma = False + + if not use_mma: + block_n = min(32, 32768 // ((d_qk + d_v) * bytes_per_elem)) + block_n = max(1, block_n) + + buf_idx = 6 # 0=out, 1=Q, 2=K, 3=V, 4=kv_num_blocks, 5=kv_indices + if has_full_blocks: + full_kv_params = ( + f" constant int* full_kv_num_blocks [[buffer({buf_idx})]],\n" + ) + buf_idx += 1 + full_kv_params += f" constant int* full_kv_indices [[buffer({buf_idx})]],\n" + buf_idx += 1 + else: + full_kv_params = "" + + # Captures follow the (full) kv buffers, in the order built in lower_mps: + # score captures first, then mask captures. Tensor captures become extra + # Metal buffers; SymInt captures are read from the packed scalar buffer + captured_decls: list[str] = [] + scalar_capture_names: list[str] = [] + score_meta: list[Any] = [] + mask_meta: list[Any] = [] + for meta_list, caps in ((score_meta, score_captured), (mask_meta, mask_captured)): + for entry in caps: + if entry[0] == "scalar": + sname = f"capsym{len(scalar_capture_names)}" + scalar_capture_names.append(sname) + meta_list.append(_CapturedScalar(sname)) + continue + _, sizes, strides, cap_dtype = entry + mtype = CAPTURE_DTYPE_MAP.get(cap_dtype) + if mtype is None: + raise NotImplementedError( + f"flex_attention on MPS does not support captured buffer " + f"dtype {cap_dtype}" + ) + name = f"capbuf{len(captured_decls)}" + captured_decls.append( + f" constant {mtype}* {name} [[buffer({buf_idx})]]," + ) + meta_list.append(_CapturedBuf(name, list(sizes), list(strides), cap_dtype)) + buf_idx += 1 + captured_params = "".join(d + "\n" for d in captured_decls) + + # Pack scalars into one buffer to stay under Metal's 31-buffer limit. + scalar_names = [ + "B", + "Bkv", + "Hq", + "Hkv", + "N_Q", + "N_KV", + "stride_qz", + "stride_qh", + "stride_qm", + "stride_qk", + "stride_kz", + "stride_kh", + "stride_kn", + "stride_kk", + "stride_vz", + "stride_vh", + "stride_vn", + "stride_vk", + "stride_oz", + "stride_oh", + "stride_om", + "stride_ok", + "SPARSE_KV_BLOCK_SIZE", + "gqa_shared_heads", + "SPARSE_Z", + "SPARSE_HQ", + "kv_nb_stride_z", + "kv_nb_stride_h", + "kv_nb_stride_q", + "kv_idx_stride_z", + "kv_idx_stride_h", + "kv_idx_stride_q", + "kv_idx_stride_b", + "SPARSE_Q_BLOCK_SIZE", + ] + if has_full_blocks: + scalar_names += [ + "full_kv_nb_stride_z", + "full_kv_nb_stride_h", + "full_kv_nb_stride_q", + "full_kv_idx_stride_z", + "full_kv_idx_stride_h", + "full_kv_idx_stride_q", + "full_kv_idx_stride_b", + ] + scalar_names += scalar_capture_names + lse_param = "" + lse_write_code = "" + if write_lse: + lse_param = f" device float* lse [[buffer({buf_idx})]],\n" + buf_idx += 1 + lse_write_code = ( + " lse[(long)b_idx * (Hq * N_Q)" + " + (long)h_idx * N_Q + (long)m_idx]" + " = (row_sum > 0.0f)" + f" ? (row_max + metal::precise::log(row_sum)) * {RCP_LN2}" + " : -INFINITY;\n" + ) + + max_param = "" + max_write_code = "" + if write_max: + max_param = f" device float* max_scores [[buffer({buf_idx})]],\n" + buf_idx += 1 + max_write_code = ( + " max_scores[(long)b_idx * (Hq * N_Q)" + " + (long)h_idx * N_Q + (long)m_idx]" + f" = row_max * {RCP_LN2};\n" + ) + + scalar_params_str = f" constant long* _params [[buffer({buf_idx})]]" + + int_ctype = "int" if captures_fit_int32 else "long" + score_code = _compile_subgraph_to_metal( + graph_module=score_mod_graph, + placeholder_metal_names=["score_val", "b_idx", "h_idx", "m_idx", "n_idx"], + captured_meta=score_meta, + output_var="score_val", + var_prefix="_sm", + int_ctype=int_ctype, + ) + mask_code = _compile_subgraph_to_metal( + graph_module=mask_mod_graph, + placeholder_metal_names=["b_idx", "h_idx", "m_idx", "n_idx"], + captured_meta=mask_meta, + output_var="mask_result", + var_prefix="_mm", + int_ctype=int_ctype, + ) + + capsym_set = OrderedSet(scalar_capture_names) + unpack_code = "\n".join( + f" {int_ctype if name in capsym_set else 'long'} {name} = _params[{i}];" + for i, name in enumerate(scalar_names) + ) + + if use_mma: + return _generate_mma_shader( + metal_dtype, + d_qk, + d_v, + kv_dim, + block_m, + block_n, + full_kv_params, + captured_params, + scalar_params_str, + unpack_code, + score_code, + mask_code, + has_full_blocks, + scale, + lse_param=lse_param, + lse_write_code=lse_write_code, + max_param=max_param, + max_write_code=max_write_code, + ) + + # Fallback: per-thread dot product with cooperative K/V tiling. + def _fallback_block_loop_body(is_partial): + if is_partial: + mask_section = f""" + bool mask_result = true; + {mask_code} + """ + else: + mask_section = """ + bool mask_result = true; + """ + return f"""\ + for (int tile_start = kv_start; tile_start < kv_end; tile_start += BLOCK_N) {{ + int tile_end = min(tile_start + BLOCK_N, kv_end); + int tile_size = tile_end - tile_start; + + for (int i = (int)tid; i < tile_size * D_QK; i += BLOCK_M) {{ + int n_local = i / D_QK; + int d = i % D_QK; + int n_global = tile_start + n_local; + long k_off = b_kv * stride_kz + hkv_idx * stride_kh + (long)n_global * stride_kn + (long)d * stride_kk; + K_tile[n_local * D_QK + d] = K[k_off]; + }} + + for (int i = (int)tid; i < tile_size * D_V; i += BLOCK_M) {{ + int n_local = i / D_V; + int d = i % D_V; + int n_global = tile_start + n_local; + long v_off = b_kv * stride_vz + hkv_idx * stride_vh + (long)n_global * stride_vn + (long)d * stride_vk; + V_tile[n_local * D_V + d] = V[v_off]; + }} + + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (active) {{ + for (int n_local = 0; n_local < tile_size; n_local++) {{ + int n_idx = tile_start + n_local; + + float s = 0.0f; + for (int d = 0; d < D_QK; d++) {{ + s += q_row[d] * float(K_tile[n_local * D_QK + d]); + }} + s *= SCALE_VAL; + + float score_val = s; +{score_code} + s = score_val; +{mask_section}\ + // s > -inf guards exp(-inf - -inf) = NaN when an entire row is -inf so far. + if (mask_result && s > -INFINITY) {{ + float new_max = metal::max(row_max, s); + float old_scale = metal::precise::exp(row_max - new_max); + float p = metal::precise::exp(s - new_max); + row_sum = row_sum * old_scale + p; + for (int d = 0; d < D_V; d++) o_acc[d] *= old_scale; + for (int d = 0; d < D_V; d++) {{ + o_acc[d] += p * float(V_tile[n_local * D_V + d]); + }} + row_max = new_max; + }} + }} + }} + + threadgroup_barrier(mem_flags::mem_threadgroup); + }}""" + + partial_loop = _fallback_block_loop_body(is_partial=True) + full_loop = _fallback_block_loop_body(is_partial=False) + + shader = f"""\ +#include +#include +using namespace metal; + +constant int D_QK = {d_qk}; +constant int D_V = {d_v}; +constant int BLOCK_M = {block_m}; +constant int BLOCK_N = {block_n}; +constant float SCALE_VAL = {scale!r}f; + +kernel void flex_attn_fwd( + device {metal_dtype}* out [[buffer(0)]], + constant {metal_dtype}* Q [[buffer(1)]], + constant {metal_dtype}* K [[buffer(2)]], + constant {metal_dtype}* V [[buffer(3)]], + constant int* kv_num_blocks [[buffer(4)]], + constant int* kv_indices [[buffer(5)]], +{full_kv_params}{captured_params}{lse_param}{max_param}{scalar_params_str}, + uint3 tgpos [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]] +) {{ +{unpack_code} + + int q_block = tgpos.x; + int h_idx = tgpos.y; + int b_idx = tgpos.z; + int b_kv = b_idx % (int)Bkv; + int m_idx = q_block * BLOCK_M + (int)tid; + bool active = (m_idx < N_Q); + + int hkv_idx = h_idx / (int)gqa_shared_heads; + + float q_row[D_QK]; + if (active) {{ + long q_base = b_idx * stride_qz + h_idx * stride_qh + (long)m_idx * stride_qm; + for (int d = 0; d < D_QK; d++) {{ + q_row[d] = float(Q[q_base + (long)d * stride_qk]); + }} + }} + + float row_max = -INFINITY; + float row_sum = 0.0f; + float o_acc[D_V]; + for (int d = 0; d < D_V; d++) o_acc[d] = 0.0f; + + threadgroup {metal_dtype} K_tile[BLOCK_N * D_QK]; + threadgroup {metal_dtype} V_tile[BLOCK_N * D_V]; + + int m_base = q_block * BLOCK_M; + int sparse_q_idx = m_base / (int)SPARSE_Q_BLOCK_SIZE; + long sparse_idx_z = b_idx % SPARSE_Z; + long sparse_idx_hq = h_idx % SPARSE_HQ; + + int num_kv_blks = kv_num_blocks[sparse_idx_z * kv_nb_stride_z + sparse_idx_hq * kv_nb_stride_h + sparse_q_idx * kv_nb_stride_q]; + long kv_idx_base = sparse_idx_z * kv_idx_stride_z + sparse_idx_hq * kv_idx_stride_h + (long)sparse_q_idx * kv_idx_stride_q; + + for (int blk = 0; blk < num_kv_blks; blk++) {{ + int kv_block_idx = kv_indices[kv_idx_base + (long)blk * kv_idx_stride_b]; + int kv_start = kv_block_idx * (int)SPARSE_KV_BLOCK_SIZE; + int kv_end = min(kv_start + (int)SPARSE_KV_BLOCK_SIZE, (int)N_KV); + +{partial_loop} + }} +""" + + if has_full_blocks: + shader += f""" + int full_num_kv_blks = full_kv_num_blocks[sparse_idx_z * full_kv_nb_stride_z + sparse_idx_hq * full_kv_nb_stride_h + sparse_q_idx * full_kv_nb_stride_q]; + long full_kv_idx_base = sparse_idx_z * full_kv_idx_stride_z + sparse_idx_hq * full_kv_idx_stride_h + (long)sparse_q_idx * full_kv_idx_stride_q; + + for (int blk = 0; blk < full_num_kv_blks; blk++) {{ + int kv_block_idx = full_kv_indices[full_kv_idx_base + (long)blk * full_kv_idx_stride_b]; + int kv_start = kv_block_idx * (int)SPARSE_KV_BLOCK_SIZE; + int kv_end = min(kv_start + (int)SPARSE_KV_BLOCK_SIZE, (int)N_KV); + +{full_loop} + }} +""" + + shader += f""" + if (active) {{ +{lse_write_code}{max_write_code} if (row_sum == 0.0f) row_sum = 1.0f; + long out_base = b_idx * stride_oz + h_idx * stride_oh + (long)m_idx * stride_om; + for (int d = 0; d < D_V; d++) {{ + out[out_base + (long)d * stride_ok] = {metal_dtype}(o_acc[d] / row_sum); + }} + }} +}} +""" + return shader + + +class MetalFlexAttentionNode(ir.ExternKernelAlloc): + """IR node for MPS flex attention; emits a compiled Metal shader at codegen.""" + + def __init__( + self, + layout: ir.Layout, + inputs: list[ir.IRNode], + shader_source: str, + scalar_args: list[Any], + grid: tuple[Any, ...], + block_m: int, + num_mutated_outputs: int = 0, + ): + super().__init__( + layout=layout, + inputs=inputs, + python_kernel_name="metal_flex_attention", + ) + self.shader_source = shader_source + self.scalar_args = scalar_args + self.grid = grid + self.block_m = block_m + # The last num_mutated_outputs inputs (logsumexp, max_scores) are written + # in place by the kernel. + self.mutation_outputs = [ + # pyrefly: ignore [bad-argument-type] + ir.MutationOutput(ir.NoneLayout(device=layout.device), buf, self) + for buf in self.inputs[len(self.inputs) - num_mutated_outputs :] + ] + + def codegen(self, wrapper) -> None: + wrapper.add_import_once( + "from torch._inductor.runtime.runtime_utils import compile_mps_shader" + ) + wrapper.add_import_once("import torch") + + src_code = self.shader_source + if src_code in wrapper.src_to_kernel: + lib_name = wrapper.src_to_kernel[src_code] + else: + lib_name = f"_mps_flex_lib_{wrapper.next_kernel_suffix()}" + wrapper.src_to_kernel[src_code] = lib_name + wrapper.header.splice( + f"{lib_name} = compile_mps_shader('''\n{src_code}\n''')" + ) + + name = self.get_name() + layout: ir.Layout = self.layout # type: ignore[assignment] + sizes = ", ".join(wrapper.codegen_sizevar(s) for s in layout.size) + strides = ", ".join(wrapper.codegen_sizevar(s) for s in layout.stride) + device_str = f"{layout.device.type!r}" + wrapper.writeline( + f"{name} = torch.empty_strided(" + f"({sizes},), ({strides},), " + f"dtype={layout.dtype!r}, device={device_str})" + ) + + # One packed int64 buffer keeps us under Metal's 31-buffer limit. + scalar_strs = [wrapper.codegen_sizevar(s) for s in self.scalar_args] + params_name = f"_flex_params_{name}" + wrapper.writeline( + f"{params_name} = torch.tensor(" + f"[{', '.join(scalar_strs)}], dtype=torch.int64, device={device_str})" + ) + + arg_parts = [name] + for inp in self.inputs: + # pyrefly: ignore [missing-attribute] + arg_parts.append(inp.codegen_reference()) + arg_parts.append(params_name) + args_str = ", ".join(arg_parts) + + grid_x = wrapper.codegen_sizevar(self.grid[0]) + grid_y = wrapper.codegen_sizevar(self.grid[1]) + grid_z = wrapper.codegen_sizevar(self.grid[2]) + + wrapper.writeline( + f"{lib_name}.flex_attn_fwd(" + f"{args_str}, " + f"threads=[{grid_x} * {self.block_m}, {grid_y}, {grid_z}], " + f"group_size=[{self.block_m}, 1, 1])" + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps.py new file mode 100644 index 0000000000000000000000000000000000000000..a7c654bdae29a53a6b9d9cd11995b17724c58b5f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps.py @@ -0,0 +1,1267 @@ +# This is not a feature-complete compiler backend +# Just an early prototype that shows that one can compile elementwise ops into a Metal shader +from __future__ import annotations + +import functools +import itertools +import logging +import math +from pathlib import Path +from typing import Any, TYPE_CHECKING + +import sympy +from sympy.printing.precedence import PRECEDENCE + +import torch +from torch.utils._cpp_embed_headers import _embed_headers +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import Min +from torch.utils._sympy.printers import CppPrinter, ExprPrinter as ExprPrinter_ +from torch.utils._sympy.value_ranges import ValueRanges + +from ..utils import ceildiv, get_bounds_index_expr, get_kernel_metadata +from ..virtualized import ops, OpsWrapper, V +from .common import ( + CSEVariable, + DeferredLine, + DTYPE_TO_COMPUTATION_DTYPE, + IndentedBuffer, + OpOverrides, + PythonPrinter, +) +from .simd import IterationRangesEntry, SIMDKernel, SIMDScheduling + + +if TYPE_CHECKING: + from ..ops_handler import ReductionType, StoreMode + from ..scheduler import Scheduler, SchedulerNode + from .common import OpVarT + +log = logging.getLogger(__name__) + +DTYPE_TO_METAL = { + torch.bool: "bool", + torch.int8: "char", + torch.int16: "short", + torch.int32: "int", + torch.int64: "long", + torch.uint8: "uchar", + torch.uint16: "ushort", + torch.uint32: "uint", + torch.uint64: "ulong", + torch.float: "float", + torch.half: "half", + torch.bfloat16: "bfloat", +} + + +def value_to_metal(val: float | int | bool | str | CSEVariable) -> str: + if isinstance(val, float): + if val == torch.inf: + return "HUGE_VALF" + elif val == -torch.inf: + return "-HUGE_VALF" + elif val != val: # Only float that not equal to self is nan + return "NAN" + return str(val) + elif isinstance(val, bool): + return "true" if val else "false" + return str(val) + + +class MetalExprPrinter(ExprPrinter_): + """Converts sympy expression to Metal code snippet""" + + def _print_FloorDiv(self, expr: sympy.Expr) -> str: + x, div = expr.args + x = self.doprint(x) + div = self.doprint(div) + if expr.is_integer: + return f"c10::metal::floor_divide({x}, {div})" + return f"metal::floor({x}) / ({div})" + + def _print_ModularIndexing(self, expr: sympy.Expr) -> str: + x, div, mod = expr.args + # Workaround for Metal compiler bug with fused (x / A) % B, see PR 175481 + use_safe_mod = div == 65536 and (mod & (mod - 1)) != 0 + + x = self.doprint(x) + if div != 1: + div = self.doprint(div) + if expr.is_integer: + x = f"({x}) / ({div})" + else: + x = f"metal::floor({x}) / ({div})" + mod = self.doprint(mod) + if use_safe_mod: + return f"c10::metal::safe_mod({x}, {mod})" + return f"({x}) % ({mod})" + + def _print_min_max(self, expr: sympy.Expr, fn: str) -> str: + # pyrefly: ignore [missing-attribute] + args = list(map(self._print, expr.args)) + result = args[0] + for arg in args[1:]: + result = self._print_binary_min_max(result, arg, fn) + return result + + @staticmethod + def _print_binary_min_max(a: str, b: str, fn: str) -> str: + typecast_a = f"static_cast({a})" + typecast_b = f"static_cast({b})" + return f"metal::{fn}({typecast_a}, {typecast_b})" + + def _print_Min(self, expr: sympy.Expr) -> str: + return self._print_min_max(expr, "min") + + def _print_Max(self, expr: sympy.Expr) -> str: + return self._print_min_max(expr, "max") + + 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"metal::abs({self._print(expr.args[0])})" + + def _print_RoundToInt(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"static_cast(metal::rint({self._print(expr.args[0])}))" + + 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"static_cast(metal::rint(1e{ndigits} * {number_str}) * 1e{-ndigits})" + + def _print_IntTrueDiv(self, expr: sympy.Expr) -> str: + lhs, rhs = expr.args + # TODO: This is only accurate up to 2**23 + # pyrefly: ignore [missing-attribute] + return f"static_cast({self._print(lhs)}) / static_cast({self._print(rhs)})" + + def _print_PowByNatural(self, expr: sympy.Expr) -> str: + if len(expr.args) != 2: + raise AssertionError(f"expected 2 args, got {len(expr.args)}") + x, y = map(self.doprint, expr.args) + return f"metal::precise::pow(static_cast({x}), static_cast({y}))" + + def _print_ToFloat(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + x = self.doprint(expr.args[0]) + return f"static_cast({x})" + + def _print_Float(self, expr: sympy.Expr) -> str: + if expr.is_integer: + # sympy considers 0.0 to be integer, but Metal doesn't. + # this workaround prints the float as an integer + # xref: https://github.com/sympy/sympy/issues/26620 + return str(int(expr)) + else: + return str(expr) + + def _print_FloorToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + x = self.doprint(expr.args[0]) + return f"static_cast(metal::floor(static_cast({x})))" + + _print_floor = _print_FloorToInt + + def _print_TruncToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + x = self.doprint(expr.args[0]) + return f"static_cast(metal::trunc({x}))" + + def _print_OpaqueUnaryFn_log2(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError(f"expected 1 arg, got {len(expr.args)}") + x = self.doprint(expr.args[0]) + return f"metal::precise::log2({x})" + + def _print_Where(self, expr: sympy.Expr) -> str: + c, p, q = ( + self.parenthesize(arg, PRECEDENCE["Atom"] - 0.5) for arg in expr.args + ) + return f"{c} ? {p} : {q}" + + +class MetalOverrides(OpOverrides): + """Implements Metal-specific overrides for ops. Base class emits Python-friendly overrides.""" + + @staticmethod + def to_dtype( + x: CSEVariable, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types: bool = True, + ) -> str: + if dtype == torch.double: + log.warning( + "float64 cast requested, probably from tensorify_python_scalars" + ) + return f"static_cast({x})" + return f"static_cast<{DTYPE_TO_METAL[dtype]}>({x})" + + @staticmethod + def to_dtype_bitcast( + x: CSEVariable, dtype: torch.dtype, src_dtype: torch.dtype + ) -> str: + return f"as_type<{DTYPE_TO_METAL[dtype]}>(static_cast<{DTYPE_TO_METAL[src_dtype]}>({x}))" + + @staticmethod + def constant(val: bool | float | int, dtype: torch.dtype) -> str: + return value_to_metal(val) + + @staticmethod + def index_expr(expr: sympy.Expr, dtype: torch.dtype) -> str: + idx_str = V.kernel.index_to_str(V.kernel.prepare_indexing(expr)) + var = V.kernel.cse.generate( + V.kernel.compute, idx_str, bounds=get_bounds_index_expr(expr) + ) + return ops.to_dtype(var, dtype) + + @staticmethod + def value_expr(expr: sympy.Expr, dtype: torch.dtype) -> str: + # Metal index_expr already emits the requested dtype, so value_expr has + # the same lowering here. + return MetalOverrides.index_expr(expr, dtype) + + @staticmethod + def masked(mask: CSEVariable, body: sympy.Expr, other: CSEVariable) -> str: + # TODO: Type annotation for other is wrong, it's often float or int + # TODO: Should it be converted to lambda on MacOS-15+? + + other_str = value_to_metal(other) + scoped_body = IndentedBuffer() + with V.kernel.swap_buffers(scoped_body), scoped_body.indent(): + # Reset the scoped variable counter so that each invocation of the same body + # generates identical variable names. Without this reset, repeated calls to + # body() would keep incrementing the counter, resulting in different cache key. + V.kernel.cse.iter_buffer_ids = itertools.count() + # Append "_scoped" to the current prefix so each nesting level gets unique vars + V.kernel.cse.name_prefix += "_scoped" + rc = body() + + # Compute cache key manually as variable name is needed to actually generate the code + cache_key = f"{mask}:{scoped_body.getvalue()}:{other_str}" + var = V.kernel.cse.try_get(cache_key) + if not var: + var = V.kernel.cse.newvar(dtype=rc.dtype) + V.kernel.cse.put(cache_key, var) + V.kernel.compute.writelines( + [f"{DTYPE_TO_METAL[rc.dtype]} {var};", f"if ({mask}) {{"] + ) + with V.kernel.compute.indent(): + V.kernel.compute.splice(scoped_body) + V.kernel.compute.writeline( + f"{var} = static_cast({rc});" + ) + V.kernel.compute.writeline( + f"}} else {var} = static_cast({other_str});" + ) + return var + + @staticmethod + # pyrefly: ignore [bad-override] + def where(a: OpVarT, b: OpVarT, c: OpVarT) -> str: + return f"{a} ? {b} : static_cast({value_to_metal(c)})" + + @staticmethod + def remainder(a: OpVarT, b: OpVarT) -> str: + return f"c10::metal::remainder({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def maximum(a: CSEVariable, b: CSEVariable) -> str: + typecast_a = f"static_cast({a})" + typecast_b = f"static_cast({b})" + return f"c10::metal::max({typecast_a}, {typecast_b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def minimum(a: CSEVariable, b: CSEVariable) -> str: + typecast_a = f"static_cast({a})" + typecast_b = f"static_cast({b})" + return f"c10::metal::min({typecast_a}, {typecast_b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_or(a: CSEVariable, b: CSEVariable) -> str: + return f"{a} || {b}" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_and(a: CSEVariable, b: CSEVariable) -> str: + return f"{a} && {b}" + + @staticmethod + # pyrefly: ignore [bad-override] + def isnan(x: CSEVariable) -> str: + return f"metal::isnan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def isinf(x: CSEVariable) -> str: + return f"metal::isinf({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def log(x: CSEVariable) -> str: + return f"metal::precise::log({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def exp(x: CSEVariable) -> str: + return f"metal::precise::exp({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def abs(x: CSEVariable) -> str: + return f"metal::abs({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def signbit(x: CSEVariable) -> str: + return f"metal::signbit({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sin(x: CSEVariable) -> str: + return f"metal::precise::sin({x})" + + @staticmethod + def sinc(x: CSEVariable) -> str: + return f"c10::metal::sinc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cos(x: CSEVariable) -> str: + return f"metal::precise::cos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tan(x: CSEVariable) -> str: + return f"metal::precise::tan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asin(x: CSEVariable) -> str: + return f"metal::precise::asin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acos(x: CSEVariable) -> str: + return f"metal::precise::acos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan(x: CSEVariable) -> str: + return f"metal::precise::atan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan2(x: CSEVariable, y: CSEVariable) -> str: + return f"::metal::precise::atan2({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sqrt(x: CSEVariable) -> str: + return f"metal::precise::sqrt({x})" + + @staticmethod + def neg(x: CSEVariable) -> str: + # TODO: Does it rely on undefined behavior? + # If so, add special logic for unsigned types + return f"static_cast(-{x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def rsqrt(x: CSEVariable) -> str: + return f"metal::precise::rsqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tanh(x: CSEVariable) -> str: + return f"metal::precise::tanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atanh(x: CSEVariable) -> str: + return f"metal::precise::atanh({x})" + + @staticmethod + def floordiv(a: CSEVariable, b: CSEVariable) -> str: + # a and b must be of integer type + return f"c10::metal::floor_divide({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def floor(x: CSEVariable) -> str: + return f"metal::floor({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sign(x: CSEVariable) -> str: + return f"metal::sign({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmod(a: CSEVariable, b: CSEVariable) -> str: + typecast_a = f"static_cast({a})" + typecast_b = f"static_cast({b})" + return f"metal::fmod({typecast_a}, {typecast_b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def trunc(x: CSEVariable) -> str: + return f"metal::trunc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def truncdiv(a: CSEVariable, b: CSEVariable) -> str: + quot = f"{a} / {b}" + if (a.dtype is not None and a.dtype.is_floating_point) or ( + b.dtype is not None and b.dtype.is_floating_point + ): + return f"metal::trunc({quot})" + return quot + + @staticmethod + # pyrefly: ignore [bad-override] + def ceil(x: CSEVariable) -> str: + return f"metal::ceil({x})" + + @staticmethod + def rand(seed: CSEVariable, offset: CSEVariable) -> str: + V.kernel.headers.add("random") + return f"c10::metal::rand({seed}, {offset})" + + @staticmethod + def randn(seed: CSEVariable, offset: CSEVariable) -> str: + V.kernel.headers.add("random") + return f"c10::metal::randn({seed}, {offset})" + + @staticmethod + def randint64( + seed: CSEVariable, offset: CSEVariable, low: CSEVariable, high: CSEVariable + ) -> str: + V.kernel.headers.add("random") + return f"c10::metal::randint64({seed}, {offset}, {low}, {high})" + + @staticmethod + # pyrefly: ignore [bad-override] + def round(x: CSEVariable) -> str: + return f"metal::rint({x})" + + @staticmethod + def pow(a: CSEVariable, b: CSEVariable) -> str: + cast_a = f"static_cast({a})" + cast_b = f"static_cast({b})" + return f"metal::pow({cast_a}, {cast_b})" + + def _special_unary(self, a: CSEVariable, name: str) -> str: + V.kernel.headers.add("special_math") + return f"c10::metal::{name}({a})" + + def _special_binary(self, a: CSEVariable, b: CSEVariable, name: str) -> str: + V.kernel.headers.add("special_math") + return f"c10::metal::{name}({a}, {b})" + + @classmethod + def _initialize_special_ops(cls) -> None: + # Unary special ops + for name in [ + "erf", + "erfc", + "erfinv", + "i0", + "i0e", + "i1", + "i1e", + "digamma", + "spherical_bessel_j0", + ]: + setattr(cls, name, functools.partialmethod(cls._special_unary, name=name)) + + cls.lgamma = functools.partialmethod(cls._special_unary, name="log_gamma") # type: ignore[assignment] + + # Unary special ops with forward in method name + for name in [ + "bessel_j0", + "bessel_j1", + "bessel_y0", + "bessel_y1", + "modified_bessel_i0", + "modified_bessel_i1", + "modified_bessel_k0", + "modified_bessel_k1", + "scaled_modified_bessel_k0", + "scaled_modified_bessel_k1", + ]: + setattr( + cls, + name, + functools.partialmethod(cls._special_unary, name=name + "_forward"), + ) + + # Binary special ops + for name in [ + "polygamma", + "igamma", + "igammac", + "zeta", + ]: + setattr(cls, name, functools.partialmethod(cls._special_binary, name=name)) + + # Binary special ops with forward in method name + for name in [ + "chebyshev_polynomial_t", + "chebyshev_polynomial_u", + "chebyshev_polynomial_v", + "chebyshev_polynomial_w", + "hermite_polynomial_h", + "hermite_polynomial_he", + "shifted_chebyshev_polynomial_t", + "shifted_chebyshev_polynomial_u", + "shifted_chebyshev_polynomial_v", + "shifted_chebyshev_polynomial_w", + ]: + setattr( + cls, + name, + functools.partialmethod(cls._special_binary, name=name + "_forward"), + ) + + +MetalOverrides._initialize_pointwise_overrides("mps") +MetalOverrides._initialize_special_ops() + + +class MetalKernel(SIMDKernel): + """Implement Metal codegen based on the SIMDKernel abstraction""" + + overrides = MetalOverrides # type: ignore[assignment] + suffix = ";" + newvar_prefix = "auto " + max_threadgroup_size = 1024 + simd_group_size = 32 + pexpr = PythonPrinter().doprint + cexpr = CppPrinter().doprint + sexpr = MetalExprPrinter().doprint + kexpr = sexpr + headers: OrderedSet[str] = OrderedSet(["utils"]) + multistage_reduction_entry: list[IterationRangesEntry] = [] + + def __init__( + self, + tiling: dict[str, sympy.Expr], + **kwargs: Any, + ) -> None: + super().__init__(tiling, **kwargs) + self.acc_var_ids = itertools.count() + + def dtype_to_str(self, dtype: torch.dtype) -> str: + return DTYPE_TO_METAL[dtype] + + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + """Codegen a load from an InputBuffer""" + var = self.args.input(name) + index = self.prepare_indexing(index) + dtype = V.graph.get_dtype(name) + line = f"{var}[{self.index_to_str(index)}]" + if dtype in [torch.float16, torch.bfloat16]: + # TODO(NS): Figure out the right balance between optype casts + # op_math_t for half-precision floats should be float32 + # Otherwise it can lead to a correctness issues with eager + line = f"static_cast({line})" + dtype = torch.float32 + return self.cse.generate(self.loads, line, dtype=dtype) + + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None + ) -> None: + var = self.args.output(name) + index = self.prepare_indexing(index) + dtype_str = self.dtype_to_str(V.graph.get_dtype(name)) + cast_val = f"static_cast<{dtype_str}>({value})" + if mode is None: + line = f"{var}[{self.index_to_str(index)}] = {cast_val};" + elif mode == "atomic_add": + self.headers.add("atomic") + atomic_type = f"c10::metal::AtomicType<{dtype_str}>" + cast_var = f"reinterpret_cast({var})" + line = f"{atomic_type}::atomic_add({cast_var}, {self.index_to_str(index)}, {cast_val});" + else: + raise RuntimeError(f"Unimplemented store mode {mode}") + if self.inside_reduction: + self.compute.writeline(DeferredLine(name, line)) + else: + self.stores.writeline(DeferredLine(name, line)) + + def store_reduction(self, name: str, index: sympy.Expr, value: CSEVariable) -> None: + var = self.args.output(name) + index = self.prepare_indexing(index) + dtype_str = self.dtype_to_str(V.graph.get_dtype(name)) + + reduction_dim = next(t for t in self.range_trees if t.is_reduction) + # Only one thread in the reduction group needs to store the results + line = f"{var}[{self.index_to_str(index)}] = static_cast<{dtype_str}>({value});" + line = f"if ({reduction_dim.name} == 0) {line}" + self.stores.writeline(DeferredLine(name, line)) + + def _new_idxvar( + self, + dtype: str | torch.dtype, + elem_count: int | None = None, + default_value: Any | None = None, + is_threadgroup: bool = True, + bounds: ValueRanges[Any] = ValueRanges.unknown(), + ) -> CSEVariable: + if isinstance(dtype, torch.dtype): + dtype = self.dtype_to_str(dtype) + var_name = f"tmp_acc_{next(self.acc_var_ids)}" + var = V.kernel.create_cse_var(var_name, bounds, dtype) + var_def = "threadgroup " if is_threadgroup else "" + var_def += f"{dtype} {var_name}" + if elem_count: + var_def += f"[{self.sexpr(elem_count)}]" + if default_value is not None: + if is_threadgroup: + raise AssertionError("Thread group var can not have default value") + var_def += f" = {default_value}" + self.indexing_code.writeline(var_def + self.suffix) + return var + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: + "Caching wrapper around _reduction_nocache" + cache_key = (src_dtype, reduction_type, value) + # Return cached reduction + if cache_key in self.cse.reduction_cache: + return self.cse.reduction_cache[cache_key] + result = self._reduction_nocache(dtype, src_dtype, reduction_type, value) + self.cse.reduction_cache[cache_key] = result # type: ignore[assignment] + return result + + def _reduction_nocache( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: + """Codegen a reduction operation. + Only sum and prod operations are somewhat reasonable optimized""" + if not self.inside_reduction: + raise AssertionError("expected to be inside reduction") + if self._load_mask: + raise AssertionError("expected no load mask during reduction") + + def _unwrap_helper(res3: CSEVariable) -> tuple[CSEVariable, ...]: + # Unwraps vec3 dtype into individual components + return OpsWrapper._unwrap( + [CSEVariable(f"{res3}.{t}", res3.bounds, res3.dtype) for t in "xyz"] + ) + + # Establish reduction buffer size and index expression + reduction_idx = "" + acc_buf_size = 1 + for rd in self.range_trees: + if not rd.is_reduction: + continue + if reduction_idx: + reduction_idx += " + " + reduction_idx += f"{rd.name} * {acc_buf_size}" + + if isinstance(rd.numel, sympy.Integer): + acc_buf_size *= rd.numel + else: + acc_buf_size *= sympy.Symbol( + f"{rd.prefix}numel", integer=True, positive=True + ) + + acc_buf_size = Min(acc_buf_size, self.max_threadgroup_size) + acc_buf_size_str = self.sexpr(acc_buf_size) + # metal threadgroup arrays need a compile time constant size, so + # fall back to the static upper bound when acc buf size is symbolic + # happens when dynamic=True + acc_buf_alloc_size = ( + acc_buf_size + if isinstance(acc_buf_size, sympy.Integer) + else self.max_threadgroup_size + ) + shmem_buf_size = ( + ceildiv(acc_buf_size, self.simd_group_size) + if isinstance(acc_buf_size, sympy.Integer) + else self.simd_group_size + ) + + if reduction_type == "any": + acc = self._new_idxvar(dtype) + self.indexing_code.writeline(f"{acc} = false;") + self.indexing_code.writeline( + "threadgroup_barrier(metal::mem_flags::mem_threadgroup);" + ) + self.compute.splice( + f""" + if ({value}) {{ + {acc} = true; + }} + """ + ) + self.stores.writeline( + "threadgroup_barrier(metal::mem_flags::mem_threadgroup);" + ) + return acc + + self.headers.add("reduction_utils") + + if reduction_type in ["prod", "sum"]: + acc_dtype = DTYPE_TO_COMPUTATION_DTYPE[src_dtype] + acc_buf = self._new_idxvar(acc_dtype, shmem_buf_size) + if not self.multistage_reduction_entry: + val = value + else: + default_val, reduction_op = ( + (0, "+") if reduction_type == "sum" else (1, "*") + ) + val = self._new_idxvar( + acc_dtype, default_value=default_val, is_threadgroup=False + ) + self.compute.splice(f"{val} {reduction_op}= {value};") + + return self.cse.generate( + self.stores, + f"c10::metal::threadgroup_{reduction_type}({acc_buf}, {val}, {reduction_idx}, {acc_buf_size_str})", + dtype=DTYPE_TO_COMPUTATION_DTYPE[dtype], + ) + if reduction_type in ["max", "min"]: + acc_buf = self._new_idxvar(src_dtype, shmem_buf_size) + src_metal_type = DTYPE_TO_METAL[src_dtype] + cast_value = f"static_cast<{src_metal_type}>({value})" + if not self.multistage_reduction_entry: + val = cast_value # type: ignore[assignment] + else: + op_struct = "MaxOp" if reduction_type == "max" else "MinOp" + limit_val = f"::c10::metal::{op_struct}<{src_metal_type}>::identity()" + val = self._new_idxvar( + src_dtype, default_value=limit_val, is_threadgroup=False + ) + self.compute.splice( + f"{val} = ::c10::metal::{reduction_type}({val}, {cast_value});" + ) + return self.cse.generate( + self.stores, + f"c10::metal::threadgroup_{reduction_type}({acc_buf}, {val}, {reduction_idx}, {acc_buf_size_str})", + dtype=DTYPE_TO_COMPUTATION_DTYPE[dtype], + ) + if reduction_type in ["argmin", "argmax"]: + data_acc_buf = self._new_idxvar(src_dtype, shmem_buf_size) + idx_acc_buf = self._new_idxvar(dtype, shmem_buf_size) + src_metal_type = DTYPE_TO_METAL[src_dtype] + cast_value = f"static_cast<{src_metal_type}>({value})" + if not self.multistage_reduction_entry: + val = cast_value # type: ignore[assignment] + idx_val = f"static_cast<{DTYPE_TO_METAL[dtype]}>({reduction_idx})" + else: + op_struct = "MaxOp" if reduction_type == "argmax" else "MinOp" + limit_val = f"::c10::metal::{op_struct}<{src_metal_type}>::identity()" + val = self._new_idxvar( + src_dtype, default_value=limit_val, is_threadgroup=False + ) + idx_val = self._new_idxvar(dtype, default_value=0, is_threadgroup=False) # type: ignore[assignment] + idx_var = next( + t for t in self.range_tree_nodes.values() if t.is_reduction + ) + self.compute.splice(f""" + if (::c10::metal::{op_struct}<{src_metal_type}>::replace({cast_value}, {val})) {{ + {val} = {cast_value}; + {idx_val} = {idx_var.name}; + }} + """) + return self.cse.generate( + self.stores, + f"c10::metal::threadgroup_{reduction_type}({data_acc_buf}, {idx_acc_buf}, " + f"{val}, {idx_val}, {reduction_idx}, {acc_buf_size_str})", + dtype=dtype, + ) + if reduction_type == "welford_reduce": + if not self.multistage_reduction_entry: + acc_buf = self._new_idxvar("float3", acc_buf_alloc_size) + self.compute.splice( + f"{acc_buf}[{reduction_idx}] = float3({value}, 0.0, 1.0);" + ) + wf_res = self.cse.generate( + self.compute, + f"c10::metal::threadgroup_welford_combine({acc_buf}, {reduction_idx}, {acc_buf_size_str})", + dtype=torch.float32, + ) + return _unwrap_helper(wf_res) + acc_buf = self._new_idxvar("float3", acc_buf_alloc_size) + acc_thread_var = f"{acc_buf}[{reduction_idx}]" + self.indexing_code.splice(f"{acc_thread_var} = 0.0;") + self.compute.writeline( + f"{acc_thread_var} = ::c10::metal::welford_combine({acc_thread_var}, float3({value}, 0.0, 1.0));" + ) + wf_res = self.cse.generate( + self.stores, + f"c10::metal::threadgroup_welford_combine({acc_buf}, {reduction_idx}, {acc_buf_size_str})", + dtype=torch.float32, + ) + return _unwrap_helper(wf_res) + if reduction_type == "welford_combine": + if not isinstance(value, tuple): + raise AssertionError("Input to welford combine must be tuple") + acc_buf = self._new_idxvar("float3", acc_buf_alloc_size) + acc_thread_var = f"{acc_buf}[{reduction_idx}]" + inp_value = f"float3({value[0]}, {value[1]}, {value[2]})" + self.indexing_code.splice(f"{acc_thread_var} = 0.0;") + if self.multistage_reduction_entry: + self.indexing_code.splice(f"{acc_thread_var} = 0.0;") + self.compute.writeline( + f"{acc_thread_var} = ::c10::metal::welford_combine({acc_thread_var}, {inp_value});" + ) + else: + self.compute.writeline(f"{acc_thread_var} = {inp_value};") + wf_res = self.cse.generate( + self.stores if self.multistage_reduction_entry else self.compute, + f"c10::metal::threadgroup_welford_combine({acc_buf}, {reduction_idx}, {acc_buf_size_str})", + dtype=torch.float32, + ) + return _unwrap_helper(wf_res) + raise NotImplementedError(reduction_type) + + def codegen_iteration_ranges_entry(self, entry: IterationRangesEntry) -> None: + index_expr = self.rename_indexing(entry.expr) + index_str = self.sexpr(index_expr) # type: ignore[misc] + + if not entry.is_reduction or ( + isinstance(entry.root.numel, sympy.Integer) + and entry.root.numel <= self.max_threadgroup_size + ): + self.indexing_code.writeline( + f"{self.index_dtype} {entry.name} = {index_str};" + ) + return + + acc_size = ( + entry.root.numel + if isinstance(entry.root.numel, sympy.Integer) + else sympy.Symbol(f"{entry.root.prefix}numel", integer=True, positive=True) + ) + + # Check if we've already generated a loop for this reduction root + root_already_processed = any( + e.root is entry.root for e in self.multistage_reduction_entry + ) + + linear_idx_name = f"{entry.root.prefix}_linear_idx" + + if not root_already_processed: + self.multistage_reduction_entry.append(entry) + # When reducing the tensor whose size exceeds max threadgroup size + # loop over extra indices per reduction thread and perform part of the operation + # using values in the shared memory + + # Use floats so that it doesn't do integer division + loop_size = (acc_size + float(self.max_threadgroup_size - 1)) // float( + self.max_threadgroup_size + ) + loop_size_str = self.sexpr(loop_size) + + root_name = entry.root.name + + self.body.writeline( + f"for(auto {entry.root.prefix}_cnt = 0; {entry.root.prefix}_cnt < {loop_size_str}; ++{entry.root.prefix}_cnt) {{" + ) + with self.body.indent(): + if isinstance(acc_size, sympy.Symbol): + self.body.writeline( + f"{self.index_dtype} {linear_idx_name} = " + f"{self.max_threadgroup_size} * {entry.root.prefix}_cnt + {root_name};" + ) + else: + self.body.writeline( + f"{self.index_dtype} {linear_idx_name} = {loop_size_str} * {root_name} + {entry.root.prefix}_cnt;" + ) + + # Check that reduction is performed only within tensor boundary + if ( + isinstance(acc_size, sympy.Symbol) + or loop_size * self.max_threadgroup_size != acc_size + ): + self.body.writeline(f"if ({linear_idx_name} >= {acc_size}) break;") + + # Compute entry value from linear index by substituting root name + sub_index_str = index_str.replace(entry.root.name, linear_idx_name) + self.body.writeline( + f"{self.index_dtype} {entry.name} = {sub_index_str};" + ) + else: + # root is already processed so just need to compute this entry's value inside the existing loop + with self.body.indent(): + sub_index_str = index_str.replace(entry.root.name, linear_idx_name) + self.body.writeline( + f"{self.index_dtype} {entry.name} = {sub_index_str};" + ) + + def codegen_body(self) -> None: + """ + 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 self.multistage_reduction_entry: + with self.body.indent(): + self.body.splice(self.loads) + self.body.splice(self.compute) + self.body.writeline("}" * len(self.multistage_reduction_entry)) + # Invalidate variables instantiated inside loop + # But results of reduction alive. Reduction cache values can be + # either CSEVariable or tuple of CSEVariables, in which case all + # variables in the tuple must be preserved + self.cse.invalidate( + OrderedSet( + v + for item in self.cse.reduction_cache.values() + for v in (item if isinstance(item, tuple) else (item,)) + ) + ) + # And loop codegen + roots = [e.root for e in self.multistage_reduction_entry] + self.multistage_reduction_entry.clear() + for node in self.range_tree_nodes.values(): + if any(node.root is r for r in roots): + node.cache_clear() + else: + self.body.splice(self.loads) + self.body.splice(self.compute) + self.body.splice(self.stores) + self.loads.clear() + self.compute.clear() + self.stores.clear() + + def codegen_kernel(self, name: str = "generated_kernel") -> str: + """Called at the end to generate a final kernel string""" + self.codegen_body() + code = IndentedBuffer() + fn_name = name + + if V.graph.cpp_wrapper: + code.writeline('(R"MTL(') + else: + code.writeline("compile_mps_shader('''") + + idx_vars = self.active_range_trees() + with code.indent(): + if not V.graph.cpp_wrapper: + for header in self.headers: + code.writeline(f"#include ") + else: + headers = [ + f"#include " for header in self.headers + ] + header_contents = _embed_headers( + headers, + [Path(__file__).parent.parent.parent / "include"], + OrderedSet(), # type: ignore[arg-type] + ) + code.writeline(header_contents) + + if self.inside_reduction: + total_reduction_size = math.prod( + t.numel for t in self.range_trees if t.is_reduction + ) + # If using dynamic shapes, set the threadgroup size to be the + # max possible size + threadgroup_size = ( + min(total_reduction_size, self.max_threadgroup_size) + if isinstance(total_reduction_size, sympy.Integer) + else self.max_threadgroup_size + ) + code.writeline( + f"[[max_total_threads_per_threadgroup({threadgroup_size})]]" + ) + code.writeline(f"kernel void {fn_name}(") + with code.indent(): + for outer, inner in self.args.output_buffers.items(): + if outer in self.removed_buffers: + continue + dtype_str = self.dtype_to_str(V.graph.get_dtype(outer)) + code.writeline(f"device {dtype_str}* {inner},") + for outer, inner in self.args.input_buffers.items(): + dtype = V.graph.get_dtype(outer) + # MPS does not support float64, but scalar inputs are fine + if dtype == torch.float64: + outer_buf = V.graph.try_get_buffer(outer) + if outer_buf is None or outer_buf.get_size() != []: + raise RuntimeError("float64 is not supported by MPS") + dtype_str = "float" + else: + dtype_str = self.dtype_to_str(dtype) + code.writeline(f"constant {dtype_str}* {inner},") + for inner in self.args.sizevars.values(): + code.writeline(f"constant long& {inner},") + + # Write dynamic values as inputs + for idx_var in idx_vars: + if isinstance(idx_var.numel, sympy.Integer): + pass + else: + code.writeline(f"constant long& {idx_var.prefix}numel,") + + # Add error buffer parameter if error header is used + if "error" in self.headers: + code.writeline("device c10::metal::ErrorMessages* error_buf,") + + if len(idx_vars) >= 4: + raise AssertionError("Up to 3 index variables are supported") + thread_pos_dtype = ( + f"uint{len(idx_vars)}" if len(idx_vars) > 1 else "uint" + ) + thread_pos_var_name = ( + idx_vars[0].name if len(idx_vars) == 1 else "thread_pos" + ) + thread_pos_suffix = "," if self.inside_reduction else "" + code.writeline( + f"{thread_pos_dtype} {thread_pos_var_name} [[thread_position_in_grid]]{thread_pos_suffix}" + ) + if self.inside_reduction: + code.writeline( + f"{thread_pos_dtype} group_pos [[thread_position_in_threadgroup]]" + ) + code.writeline(") {") + with code.indent(): + if len(idx_vars) > 1: + for idx, var in enumerate(idx_vars): + code.writeline( + f"auto {var.name} = thread_pos.{chr(120 + idx)};" + ) + code.splice(self.indexing_code) + code.splice(self.body) + code.writeline("}") + + if V.graph.cpp_wrapper: + code.writeline(')MTL");') + else: + code.writeline("''')") + + return code.getvalue() + + def call_kernel( + self, name: str, node: Any = None, deallocate_ws: bool = True + ) -> None: + """ + Codegens a call to this kernel + """ + wrapper = V.graph.wrapper_code + # Make sure sizevars has been computed + for v in self.args.sizevars: + wrapper.ensure_size_computed(v) + + _, call_args, _, arg_types = self.args.python_argdefs() + arg_name_to_type = { + str(call_arg): arg_type for call_arg, arg_type in zip(call_args, arg_types) + } + + args = [*self.args.output_buffers.keys(), *self.args.input_buffers.keys()] + args = [arg for arg in args if arg not in self.removed_buffers] + args += [str(v) for v in self.args.sizevars] + arg_types = [arg_name_to_type[arg] for arg in args] + + # Add any dynamic ints as inputs + for tree in self.range_trees: + if isinstance(tree.numel, (sympy.Integer, int)): + # Don't need to pass in integers as inputs + continue + elif isinstance(tree.numel, sympy.Symbol): + expr = tree.numel + else: + expr = V.graph.wrapper_code.generate_numel_expr(name, tree).inner + + if not tree.is_reduction or self.inside_reduction: + args.append(str(expr)) + arg_types.append(int) + + expr_printer = self.cexpr if V.graph.cpp_wrapper else self.pexpr + + def format_threads(threads: list[str], kwarg: str) -> str: + if V.graph.cpp_wrapper: + threads = [f"static_cast({t})" for t in threads] + return f"{{{', '.join(threads)}}}" + else: + return f"{kwarg}=[{', '.join(threads)}]" + + # For reduction kernels, limit the maximum size over reduction dimensions to + # a maximum threadgroup size + if len(self.active_range_trees()) > 0: + threads = [ + expr_printer( + Min(v.numel, self.max_threadgroup_size) # type: ignore[misc] + if v.is_reduction + else v.numel + ) + for v in self.active_range_trees() + ] + + args.append(format_threads(threads, "threads")) + arg_types.append(list) + else: + if V.graph.cpp_wrapper: + raise RuntimeError("We should always have threads?") + + if self.inside_reduction: + threads = [ + expr_printer(Min(v.numel, self.max_threadgroup_size)) # type: ignore[misc] + if v.is_reduction + else "1" + for v in self.active_range_trees() + ] + args.append(format_threads(threads, "group_size")) + arg_types.append(list) + else: + if V.graph.cpp_wrapper: + # Add a None so that we always have a group_size in the + # arguments. We won't use it if the value is None. + args += [None] # type: ignore[list-item] + arg_types.append(None) + + # Add error buffer index if error reporting is used + # TODO(malfet) Figure out how to do it for aoti + if "error" in self.headers and not V.graph.cpp_wrapper: + args.append( + f"error_buf_idx={len([arg for arg in args if arg is not None and '=' not in arg])}" + ) + + wrapper.generate_kernel_call( + name, + args, + device=torch.device("mps"), + triton=False, + arg_types=arg_types, + ) + + def device_assert_async(self, cond: CSEVariable, msg: str) -> None: + if V.graph.cpp_wrapper: + self.cse.generate(self.compute, f"if (!{cond}) return", assignment=False) + else: + self.headers.add("error") + self.compute.writelines( + [ + f"if (!{cond}) {{", + f" TORCH_REPORT_ERROR(error_buf, {repr(msg)});", + " return;", + "}", + ] + ) + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + if not (lower or upper): + return + + expr_str = self.index_to_str(expr) + size_str = self.index_to_str(size) + + # Generate bounds checking with error reporting + # TODO(malfet): Is upper bound inclusive or exclusive? + if lower and upper: + # Check both lower and upper bounds + condition = f"({expr_str} < 0 || {expr_str} >= {size_str})" + elif lower: + condition = f"{expr_str} < 0" + else: + condition = f"{expr_str} >= {size_str}" + + # Generate error reporting code + if V.graph.cpp_wrapper: + self.cse.generate( + self.compute, f"if ({condition}) return", assignment=False + ) + else: + # Add error header for error reporting + self.headers.add("error") + self.compute.writelines( + [ + f"if ({condition}) {{", + f' TORCH_REPORT_ERROR(error_buf, "Index ", {expr_str}, " out of range [0, ", {size_str}, ")");', + " return;", + "}", + ] + ) + + +class MetalScheduling(SIMDScheduling): + kernel_type = MetalKernel # type: ignore[assignment] + + def __init__(self, scheduler: Scheduler | None) -> None: + super().__init__(scheduler) + + def define_kernel( + self, src_code: str, node_schedule: list[SchedulerNode], kernel: MetalKernel + ) -> str: + wrapper = V.graph.wrapper_code + if src_code in wrapper.src_to_kernel: + return wrapper.src_to_kernel[src_code] + + if V.graph.cpp_wrapper: + # C++ path: one library per kernel (each has a single "generated_kernel" function) + mps_lib_name = f"mps_lib_{wrapper.next_kernel_suffix()}" + kernel_name = mps_lib_name + wrapper.src_to_kernel[src_code] = kernel_name + src_code = f"const char* {mps_lib_name}_source = " + src_code + origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper) + wrapper.define_kernel( + mps_lib_name, src_code, f"{origins}\n{detailed_origins}", gpu=False + ) + return kernel_name + + # Python path: register kernel with async_compile; wait() will compile all + # accumulated Metal kernels into a single library and replace each placeholder. + fn_name = f"generated_kernel_{wrapper.next_kernel_suffix()}" + wrapper.src_to_kernel[src_code] = fn_name + + # Extract Metal source from compile_mps_shader('''...''') call + metal_src_start = "compile_mps_shader('''" + start = src_code.index(metal_src_start) + len(metal_src_start) + end = src_code.rindex("''')") + metal_src = src_code[start:end] + + # Strip #include lines and rename the kernel function + body_lines = [] + for line in metal_src.split("\n"): + if line.strip().startswith("#include"): + continue + body_lines.append( + line.replace("kernel void generated_kernel(", f"kernel void {fn_name}(") + ) + + headers_repr = repr(sorted(kernel.headers)) + wrapper.header.writeline(f"{fn_name} = async_compile.metal({fn_name!r}, '''") + for line in body_lines: + wrapper.header.writeline(line) + wrapper.header.writeline(f"''', {headers_repr})") + + return fn_name diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps_device_op_overrides.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps_device_op_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..f8611b73787fcbc1cf9850d7bac42a7db013ae5d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mps_device_op_overrides.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from .common import DeviceIdx, DeviceOpOverrides, register_device_op_overrides + + +class MPSDeviceOpOverrides(DeviceOpOverrides): + # MPS is single-device, so a non-zero index is unexpected. device_idx may be a + # runtime expr (str) under compile-on-one-rank, but MPS never receives that (it has + # no current_device_idx_expr override), so guard only the int case. + def device_guard(self, device_idx: DeviceIdx) -> str: + if isinstance(device_idx, int) and device_idx != 0: + raise AssertionError(f"expected device_idx == 0, got {device_idx}") + return "torch._ops.contextlib.nullcontext()" + + def set_device(self, device_idx: DeviceIdx) -> str: + if isinstance(device_idx, int) and device_idx != 0: + raise AssertionError(f"expected device_idx == 0, got {device_idx}") + return "pass # MPS set device" + + def kernel_driver(self) -> str: + return """ + #include + """ + + def cpp_kernel_type(self) -> str: + return "MTLFunction_t" + + +register_device_op_overrides("mps", MPSDeviceOpOverrides()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e58decc8e5387019b4d56f62c9f942c86b8d3b11 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/device_op_overrides.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/device_op_overrides.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b65b12c1e6df33c614febaf9e715a1ed1675baee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/__pycache__/device_op_overrides.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/device_op_overrides.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/device_op_overrides.py new file mode 100644 index 0000000000000000000000000000000000000000..deb1294a0ea72bd6a2bb735b389416208014b45e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/mtia/device_op_overrides.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +from ..common import DeviceIdx, DeviceOpOverrides, register_device_op_overrides + + +class MTIADeviceOpOverrides(DeviceOpOverrides): + def import_get_raw_stream_as(self, name: str) -> str: + return f"from torch._C import _mtia_getCurrentRawStream as {name}" + + def set_device(self, device_idx: DeviceIdx) -> str: + return f"torch.mtia.set_device({device_idx})" + + def synchronize(self) -> str: + return "torch.mtia.synchronize()" + + def device_guard(self, device_idx: DeviceIdx) -> str: + return f"torch.mtia.device({device_idx})" + + def current_stream(self) -> str: + return "torch.mtia.current_stream()" + + +register_device_op_overrides("mtia", MTIADeviceOpOverrides()) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/multi_kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/multi_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..f3441b622cfb0df19e6a3757495429d5a6f513ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/multi_kernel.py @@ -0,0 +1,650 @@ +# mypy: allow-untyped-defs +import functools +import logging +import math +import os +import pathlib +from typing import Any + +from torch._inductor.ir import MultiTemplateBuffer +from torch._inductor.metrics import get_metric_table, is_metric_table_enabled +from torch.utils._ordered_set import OrderedSet + +from .. import config +from ..codecache import code_hash, CodeCacheFuture, get_path, write_atomic +from ..runtime.benchmarking import benchmarker +from ..utils import cache_on_self, IndentedBuffer +from ..virtualized import V +from .common import TensorArg, WorkspaceArg + + +log = logging.getLogger(__name__) + + +class MultiKernelState: + """ + Maintain state of multi-kernel compilation so we don't define duplicated + multi-kernel for the same set of sub-kernels. + + V.graph.wrapper_code has a reference to MultiKernelState instance. + """ + + def __init__(self): + self.subkernel_to_kernel_name = {} + self.kernel_defs = IndentedBuffer() + + def define_kernel( + self, + kernels: list[Any], + kernel_shape_keys: list[None | tuple[tuple[int, ...], ...]] | None = None, + ) -> str: + """ + Previously we name the multi kernel as "multi_kernel_{kernel_names[0]}". + This has some minor issue. + + E.g. for persistent reduction https://gist.github.com/shunting314/39e7c00ff8bb2055942ed5a3255d61ca , + there are 2 flavors of non-persistent reduction: + https://gist.github.com/shunting314/056d43d35907e87efb883970b35c17d4 + and + https://gist.github.com/shunting314/02ee753b65c513c54e695626afe682bd + + The only different is cache eviction policy. + + We should name the multi-kernel differently in these 2 cases. + + kernels: + A list of kernels + kernel_shape_keys: + Specified for size-hint multi-kernels. + Each list element is a shape key, corresponding to the concrete input & output size hints each kernel was tuned for. + """ + # Prevent circular import + from ..select_algorithm import TritonTemplateKernel + + kernel_names = tuple(k.kernel_name for k in kernels) + if kernel_names in self.subkernel_to_kernel_name: + return self.subkernel_to_kernel_name[kernel_names] + + # name the multi kernel based on the first kernel + multi_kernel_name = f"multi_kernel_{len(self.subkernel_to_kernel_name)}" + self.subkernel_to_kernel_name[kernel_names] = multi_kernel_name + + if V.graph.cpp_wrapper and not config.triton.autotune_at_compile_time: + # we should not generate any python code for multi-kernel during + # the second pass of cpp-wrapper. + return multi_kernel_name + + arg_index: dict[int, list[slice]] = {} + _, call_args, _, arg_types = kernels[0].args.python_argdefs() + if isinstance(kernels[0], TritonTemplateKernel) and isinstance( + kernels[0].output_node, MultiTemplateBuffer + ): + for i, kernel in enumerate(kernels): + additional_call_args, _ = kernel.additional_call_args_and_types() + if i not in arg_index: + arg_index[i] = [] + arg_index[i].append(slice(0, len(call_args))) + arg_index[i].append( + slice( + len(call_args) + i * len(additional_call_args), + len(call_args) + (i + 1) * len(additional_call_args), + ) + ) + else: + kernels[0].add_numel_to_call_args(multi_kernel_name, call_args, arg_types) + for i in range(len(kernels)): + arg_index[i] = [slice(0, len(call_args))] + + keyed_by_sizes = kernel_shape_keys is not None + buf = self.kernel_defs + buf.writeline("") + buf.writeline("arg_index = {") + for key, slice_list in arg_index.items(): + slice_reprs = ", ".join(repr(s) for s in slice_list) + buf.writeline(f" {key}: [{slice_reprs}],") + buf.writeline("}") + + if not keyed_by_sizes: # no size hint keys, just call with list of kernels + buf.writeline( + f"{multi_kernel_name} = async_compile.multi_kernel({multi_kernel_name!r}, [" + ) + with buf.indent(): + for name in kernel_names: + buf.writeline(f"{name},") + buf.writeline("], arg_index=arg_index)") + else: # call with dict[size hint key, kernel] + if not isinstance(kernels[0], TritonTemplateKernel): + raise AssertionError("expected kernels[0] to be a TritonTemplateKernel") + if not isinstance(kernel_shape_keys, list): + raise AssertionError("expected kernel_shape_keys to be a list") + if len(kernels) != len(kernel_shape_keys): + raise AssertionError( + f"expected len(kernels) == len(kernel_shape_keys), " + f"got {len(kernels)} != {len(kernel_shape_keys)}" + ) + buf.writeline( + f"{multi_kernel_name} = async_compile.size_hint_multi_kernel({multi_kernel_name!r}, {{" + ) + with buf.indent(): + for shape_key, name in zip(kernel_shape_keys, kernel_names): + buf.writeline(f"{shape_key}: {name},") + buf.writeline("}, arg_index=arg_index)") + + if config.triton.autotune_at_compile_time: + V.graph.wrapper_code.src_to_kernel["\n".join(kernel_names)] = ( + multi_kernel_name + ) + + return multi_kernel_name + + +class MultiKernel: + """ + This class maintains the compile time state for multi kernels. + + Assume we do codegen for a MultiKernel encapsulating kernel1 and kernel2. + The generated definition for the multi-kernel will looks like: + ``` + multi_kernel_kernel1 = MultiKernelCall( + [kernel1, kernel2], multi_kernel_definition_code + ) + ``` + + Here is a concrete example: https://gist.github.com/shunting314/d9f3fb6bc6cee3dbae005825ca196d39 + """ + + def __init__(self, kernels): + if len(kernels) < 2: + raise AssertionError(f"expected at least 2 kernels, got {len(kernels)}") + + self.kernels = kernels + self.kernel_name = V.graph.wrapper_code.multi_kernel_state.define_kernel( + kernels + ) + + # need this since some code in inductor check if the kernel object has an args + # attribute to decide if it's a non-null kernel. + self.args = object() + + @staticmethod + def _merge_workspace_args(left: list[WorkspaceArg], right: list[WorkspaceArg]): + if left == right: + return left + result = {x.inner_name: x for x in left} + for arg in right: + if arg.inner_name in result: + result[arg.inner_name] = WorkspaceArg.maximum( + result[arg.inner_name], arg + ) + else: + result[arg.inner_name] = arg + return [*result.values()] + + @staticmethod + def merge_workspaces_inplace(kernels): + if len(kernels) < 2: + return + # All kernels must share the same workspace + workspace_args = functools.reduce( + MultiKernel._merge_workspace_args, + [kernel.args.workspace_args for kernel in kernels], + ) + for kernel in kernels: + kernel.args.workspace_args = workspace_args + return workspace_args + + def call_kernel(self, kernel_name): + """ + Collect the union of arguments from all subkernels as the arguments + for the multi-kernel. + """ + # Prevent circular import + from ..select_algorithm import TritonTemplateKernel + + if kernel_name != self.kernel_name: + raise AssertionError( + f"expected kernel_name == self.kernel_name, " + f"got {kernel_name} != {self.kernel_name}" + ) + V.graph.wrapper_code.write_triton_header_once() + _, call_args, _, arg_types = self.kernels[0].args.python_argdefs() + for kernel in self.kernels[1:]: + _, other_call_args, _, other_arg_types = kernel.args.python_argdefs() + if call_args != other_call_args: + raise AssertionError((call_args, other_call_args)) + if arg_types != other_arg_types: + raise AssertionError( + f"expected arg_types == other_arg_types, " + f"got {arg_types} != {other_arg_types}" + ) + + if V.graph.cpp_wrapper and not config.triton.autotune_at_compile_time: + # for the second pass of cpp-wrapper codegen, we should call + # the fast kernel directly + kernel_name = MultiKernelCall.lookup_choice(self.kernel_name) + + if isinstance(self.kernels[0], TritonTemplateKernel) and isinstance( + self.kernels[0].output_node, MultiTemplateBuffer + ): + # For matmuls the grid arguments are passed in as additional arguments + # to the kernel run method. These grids change based on the various + # parameters of the matmul. So we need to pass each kernel's grid into + # the multi call kernel. + multi_call_args = call_args + multi_call_arg_types = arg_types + for kernel in self.kernels: + additional_call_args, additional_arg_types = ( + kernel.additional_call_args_and_types() + ) + multi_call_args.extend(list(additional_call_args)) + multi_call_arg_types.extend(list(additional_arg_types)) + else: + # numels for all subkernels should be the same. Use kernels[0] here + self.kernels[0].add_numel_to_call_args(kernel_name, call_args, arg_types) + multi_call_args = call_args + multi_call_arg_types = arg_types + + for ws in self.kernels[0].args.workspace_args: + V.graph.wrapper_code.generate_workspace_allocation(ws) + + if V.graph.cpp_wrapper: + # We have already selected the best kernel at compile time + # so we only have one set of call args. NB: this currently + # doesn't work with MultiTemplateBuffer kernels. @bobrenjc93 + # will add it in a subsequent PR. + V.graph.wrapper_code.generate_kernel_call( + kernel_name, call_args, arg_types=arg_types + ) + else: + V.graph.wrapper_code.generate_kernel_call( + kernel_name, multi_call_args, arg_types=multi_call_arg_types + ) + + for ws in reversed(self.kernels[0].args.workspace_args): + V.graph.wrapper_code.generate_workspace_deallocation(ws) + + def codegen_nan_check(self): + wrapper = V.graph.wrapper_code + seen: OrderedSet[str] = OrderedSet() + for k in self.kernels: + _, call_args, precompile_args, _ = k.args.python_argdefs() + for arg, precompile_arg in zip(call_args, precompile_args): + if arg in seen: + continue + seen.add(arg) + if isinstance(precompile_arg, TensorArg): + line = f"assert not {arg}.isnan().any().item()" + wrapper.writeline(line) + line = f"assert not {arg}.isinf().any().item()" + wrapper.writeline(line) + + @property + def removed_buffers(self): + return OrderedSet.intersection(*[k.removed_buffers for k in self.kernels]) + + @property + def inplaced_to_remove(self): + return OrderedSet.intersection(*[k.inplaced_to_remove for k in self.kernels]) + + @property + @cache_on_self + def inplace_update_buffers(self): + """ + Make sure all kernels have the same inplace update mappings. + """ + for k in self.kernels[1:]: + if k.inplace_update_buffers != self.kernels[0].inplace_update_buffers: + raise AssertionError( + "expected all kernels to share the same inplace_update_buffers" + ) + return self.kernels[0].inplace_update_buffers + + def warn_mix_layout(self, kernel_name: str): + pass + + +class MultiKernelCall: + """ + This class is called at run time to actually run the kernel + """ + + def __init__(self, multi_kernel_name, kernels, arg_index): + if len(kernels) < 1: + raise AssertionError(f"expected at least 1 kernel, got {len(kernels)}") + self._kernels = kernels + self.multi_kernel_name = multi_kernel_name + + self.disable_cache = os.environ.get( + "TORCHINDUCTOR_DISABLE_MULTI_KERNEL_CACHE" + ) == "1" or is_metric_table_enabled("persistent_red_perf") + + self.picked_kernel = None + self.arg_index = arg_index + if config.triton.multi_kernel > 1: + # manually force a subkernel to ease perf testing + picked_by_config = config.triton.multi_kernel - 2 + if picked_by_config >= len(self._kernels): + raise AssertionError( + f"expected picked_by_config < len(self._kernels), " + f"got {picked_by_config} >= {len(self._kernels)}" + ) + # pyrefly: ignore [bad-assignment] + self.picked_kernel = picked_by_config + elif not self.disable_cache: + self.load_cache() + + self._recorded = False + + def cache_file_path(self): + key = code_hash( + ",".join( + [ + f"{k.fn.cache_key}{k.size_hints!r}{k.triton_meta!r}" + for k in self.kernels + ] + ) + ) + _, _, path = get_path(key, "picked_kernel") + return pathlib.Path(path) + + def load_cache(self): + if self.picked_kernel is not None: + raise AssertionError("expected self.picked_kernel to be None") + path = self.cache_file_path() + if path.exists(): + with path.open() as fd: + # pyrefly: ignore [bad-assignment] + self.picked_kernel = int(fd.read()) + # pyrefly: ignore [unsupported-operation] + if not ( + self.picked_kernel >= 0 and self.picked_kernel < len(self._kernels) + ): + raise AssertionError( + f"expected 0 <= picked_kernel < {len(self._kernels)}, " + f"got {self.picked_kernel}" + ) + log.debug( + "Load picked kernel %d from cache file %s", self.picked_kernel, path + ) + + def store_cache(self): + if self.picked_kernel is None: + raise AssertionError("expected self.picked_kernel to not be None") + path = self.cache_file_path() + path.parent.mkdir(parents=True, exist_ok=True) + + write_atomic(path, str(self.picked_kernel)) + log.debug("Store picked kernel %d to cache file %s", self.picked_kernel, path) + + @property + def kernels(self): + """ + Read results from future. + + This should be called after parallel compilation is done. + In case you call this before compilation is done, + it may slow down the parallel compilation. + """ + for i, kernel in enumerate(self._kernels): + if isinstance(kernel, CodeCacheFuture): + self._kernels[i] = kernel.result() + + return self._kernels + + def benchmark_sub_kernels(self, *args, **kwargs): + """ + Benchmark all the sub kernels and return the execution time + (in milliseconds) for each of time. + + Unit test may mock this method to force a specific kernel to + be picked. + """ + + def wrap_fn(kernel, index): + def inner(): + filtered_args = self._get_filtered_args(args, index) + args_clone, kwargs_clone = kernel.clone_args(*filtered_args, **kwargs) + return kernel.run(*args_clone, **kwargs_clone) + + return inner + + return [ + benchmarker.benchmark( + wrap_fn(kernel, index), + # Currently the kernel type must be a CachingAutotuner + device=kernel.device_props.type, + rep=40, + ) + for index, kernel in enumerate(self.kernels) + ] + + def _get_filtered_args(self, args, index): + """ + We pass in all arguments to all kernels into the MultiKernelCall + so when invoking a particular kernel we need to filter to only the + arguments for that specific kernel. + """ + + # This is sometimes invoked at runtime where V.graph is + # a NullHandler + if hasattr(V.graph, "cpp_wrapper") and V.graph.cpp_wrapper: + # for cpp-wrapper, we should not filter the args since + # we already have chosen a single kernel and arg set. + return args + return [item for s in self.arg_index[index] for item in args[s]] + + # record_choice and lookup_choice are helper functions for cpp-wrapper + # codegen. The first pass use record_choice to keep the choice and + # the second pass do lookup by calling lookup_choice. + # + # An alternative that reused the multi-kernel cache does not work well + # since during codegen of the second pass, it's very hard to know the + # path for the cache file. Also reading the cache file need do some IO + # which can be slower. + @staticmethod + def record_choice(multi_kernel_name: str, picked_kernel_name: str): + """ + Record the multi-kernel choice for cpp-wrapper after autotuning + + We should do nothing if this function is not called during codegen. + """ + from torch._inductor.graph import GraphLowering + + if not isinstance(V.graph, GraphLowering): + return + + if not V.graph.record_multi_kernel_choice: + return + + V.graph.multi_kernel_to_choice[multi_kernel_name] = picked_kernel_name + + @staticmethod + def lookup_choice(multi_kernel_name: str) -> str: + # this should always been done during cpp-wrapper codegen + if not ( + V.graph.record_multi_kernel_choice + and multi_kernel_name in V.graph.multi_kernel_to_choice + ): + raise AssertionError( + f"expected multi_kernel_name {multi_kernel_name} to be recorded " + f"during cpp-wrapper codegen" + ) + # there should be no miss + return V.graph.multi_kernel_to_choice[multi_kernel_name] + + def run(self, *args, **kwargs): + if self.picked_kernel is None: + timings = self.benchmark_sub_kernels(*args, **kwargs) + self.picked_kernel = timings.index(min(timings)) + k0 = self.kernels[0] + log.debug( + "pick %dth sub-kernel in %s. Size hints %s. Reduction hint %s. Timings %s", + self.picked_kernel, + [k.inductor_meta.get("kernel_name") for k in self.kernels], + k0.size_hints, + k0.inductor_meta.get("reduction_hint"), + timings, + ) + get_metric_table("persistent_red_perf").add_row( + functools.partial(self._metrics_table_row, timings) + ) + + if not self.disable_cache: + self.store_cache() + + if not self._recorded: + self._recorded = True + picked_kernel_name = self.kernels[self.picked_kernel].inductor_meta.get( + "kernel_name" + ) + if picked_kernel_name is None: + raise AssertionError("expected picked_kernel_name to not be None") + self.record_choice(self.multi_kernel_name, picked_kernel_name) + + run = self.kernels[self.picked_kernel].run # type: ignore[method-assign] + filtered_args = self._get_filtered_args(args, self.picked_kernel) + run(*filtered_args, **kwargs) + + def _metrics_table_row(self, timings): + def get_kernel_path(k): + return k.fn.fn.__code__.co_filename + + k0 = self.kernels[0] + row = { + "size_hints": k0.size_hints, + "reduction_hint": k0.inductor_meta.get("reduction_hint"), + } + max_kernels = 4 + if len(timings) > max_kernels: + raise AssertionError( + f"expected len(timings) <= {max_kernels}, got {len(timings)}" + ) + for i in range(max_kernels): + if i < len(self.kernels): + row[f"kernel{i}_path"] = get_kernel_path(self.kernels[i]) + row[f"kernel{i}_latency"] = timings[i] + else: + row[f"kernel{i}_path"] = "" + row[f"kernel{i}_latency"] = "" + return row + + +class SizeHintMultiKernel(MultiKernel): + """ + Version of multi-kernel that generates kernels based on specified size hints. + Currently only performs 1-d search over hints; doesn't perform combinatorial n-d search + if n > 1 dynamic dimensions are specified. + + e.g. matmul([s0, s1], [s1, s2]) with size-hints [64, 256] only generates 2 kernels, + based on tuning shapes ([64, 64], [64, 64]) and ([256, 256], [256, 256]) + """ + + def __init__(self, kernels): + if not (isinstance(kernels, dict) and len(kernels) >= 1): + raise AssertionError("expected kernels to be a non-empty dict") + + self.kernels, self.kernel_shape_keys = [], [] + for shape_key, kernel in kernels.items(): + self.kernels.append(kernel) + self.kernel_shape_keys.append(shape_key) + self.kernel_name = V.graph.wrapper_code.multi_kernel_state.define_kernel( + self.kernels, self.kernel_shape_keys + ) + + # need this since some code in inductor check if the kernel object has an args + # attribute to decide if it's a non-null kernel. + self.args = object() + + +class SizeHintMultiKernelCall(MultiKernelCall): + """ + Runtime class for size-hint multi-kernels. + Instead of having a plain list of kernels to benchmark over, keys them by input & output shapes, + and optionally perform shape-based selection. The pre-generated kernel is chosen based on the shape keys, + with the heuristic being log2 l1 distance between the pre-generated / runtime input & output shapes. + """ + + def __init__(self, multi_kernel_name, kernels, arg_index): + super().__init__(multi_kernel_name, list(kernels.values()), arg_index) + self._kernel_hints = list(kernels.keys()) + + # Caches results for unique shapes. + self._shape_cache = {} + + def _get_shape_cache_key(self, *args, **kwargs): + """ + Generate a cache key based on tensor shapes for shape-specialized dispatch. + """ + shapes = [] + for arg in args: + if hasattr(arg, "shape"): + shapes.append(tuple(arg.shape)) + return tuple(shapes) + + def _get_cached_shape_choice(self, cache_key): + """ + Get cached kernel choice for a specific shape. + """ + return self._shape_cache.get(cache_key) + + def _cache_shape_choice(self, cache_key, kernel_idx): + """ + Cache kernel choice for a specific shape. + """ + self._shape_cache[cache_key] = kernel_idx + + def _dist_heuristic(self, k1, k2): + """ + log2 L1 distance heuristic for kernel selection. + """ + + def dist(x, y): + lx = math.log2(x) if x > 0 else -1 + ly = math.log2(y) if y > 0 else -1 + return abs(lx - ly) + + out = 0 + for s1, s2 in zip(k1, k2): + out += sum(dist(x, y) for x, y in zip(s1, s2)) + return out + + def run(self, *args, **kwargs): + cache_key = self._get_shape_cache_key(*args, **kwargs) + cached_choice = self._get_cached_shape_choice(cache_key) + if cached_choice is not None: + self.picked_kernel = cached_choice + log.debug( + "using cached shape-specialized choice %dth sub-kernel in %s. Cache key: %s", + self.picked_kernel, + [k.inductor_meta.get("kernel_name") for k in self.kernels], + cache_key, + ) + else: + self._select_kernel_by_shape(*args, **kwargs) + + if not self._recorded: + self._recorded = True + picked_kernel_name = self.kernels[self.picked_kernel].inductor_meta.get( + "kernel_name" + ) + if picked_kernel_name is None: + raise AssertionError("expected picked_kernel_name to not be None") + self.record_choice(self.multi_kernel_name, picked_kernel_name) + + run = self.kernels[self.picked_kernel].run # type: ignore[method-assign] + filtered_args = self._get_filtered_args(args, self.picked_kernel) + run(*filtered_args, **kwargs) + + def _select_kernel_by_shape(self, *args, **kwargs): + """ + Benchmark kernels for a particular shape and return the + best kernel for this shape. + """ + shape_key = self._get_shape_cache_key(*args, **kwargs) + dists = [ + self._dist_heuristic(shape_key, key) if key is not None else 2**62 + for key in self._kernel_hints + ] + # pyrefly: ignore [bad-assignment] + self.picked_kernel = dists.index(min(dists)) + self._cache_shape_choice(shape_key, self.picked_kernel) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe56018556a87428ade608318df42c05540fb0b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__init__.py @@ -0,0 +1,19 @@ +# mypy: allow-untyped-defs +from .nv_universal_gemm import ( + add_nv_universal_addmm_choices, + add_nv_universal_gemm_choices, + add_nv_universal_grouped_gemm_choices, + add_nv_universal_scaled_gemm_choices, + GemmVariant, + NVUniversalGemmCaller, +) + + +__all__ = [ + "GemmVariant", + "NVUniversalGemmCaller", + "add_nv_universal_addmm_choices", + "add_nv_universal_gemm_choices", + "add_nv_universal_grouped_gemm_choices", + "add_nv_universal_scaled_gemm_choices", +] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e1be744dba6f4aa648dc5bb4b209154e173f72e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/kernel_cache.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/kernel_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa78f9c008c3431b28e35186c59d62e953a891f2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/kernel_cache.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c802f9021a6e5f1040c2e160b3a7ff6823054b1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f09bd0abbf44f2de0e65934616f0e97a568e077c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2faf4b8284baca4502ae5adf8e5c199460deae31 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2ba65a17ce017406d0fbcbc84cc4c8e21a80e3b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/kernel_cache.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/kernel_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..09fb1b38a7e2f80962823430917c8e68a7985b3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/kernel_cache.py @@ -0,0 +1,641 @@ +# mypy: allow-untyped-defs +""" +Global kernel cache for NVIDIA Universal GEMM. + +This module provides a lazy-initialized cache for cutlass.operators kernels, +avoiding expensive manifest scans on every kernel lookup. + +The first call to get_kernel_by_name() loads all kernels from cutlass.operators +(~10 seconds) and builds a name->kernel dict. Subsequent calls use the +dict for O(1) lookup (~0.1 μs). +""" + +import dataclasses +import functools +import logging +import threading +from collections.abc import Callable +from typing import Any, Literal + +import torch + + +log = logging.getLogger(__name__) + + +@functools.cache +def _device_target(cc: int) -> Any: + """The CUDA arch target for this device (e.g. cc=100 -> TargetSm '100a'). + + Used to reject kernels whose `supported_targets` don't cover this device. + `designed_for_min_cc` alone is insufficient: an arch-conditional sm90 kernel + reports min_cc=90 (which is <= a 100 device) yet only lists a cc=90 target + and fails to compile on sm100 ("expects arch sm_90a, but got sm_100a"). + """ + from cutlass.operators.arch import TargetSm + + return TargetSm.ensure(f"{cc}a") + + +def _epilogue_args_signature(epilogue_args: Any) -> tuple: + """Extract a hashable signature of epilogue args for cache keying. + + Two callers with the same `(efc_kernel_name, epilogue_source)` but + different aux-tensor specs (dtype, shape, stride) would otherwise share + a kernel object whose internal JIT state is mutated by each call to + `kernel.compile(args)` — a silent miscompile, since the compiled + artifact's launch closure reads the kernel's CURRENT JIT at launch time + rather than the one from when the artifact was built. + """ + if epilogue_args is None: + return () + tensors = getattr(epilogue_args, "tensors", None) + if not tensors: + return () + sig: list[tuple] = [] + for name, val in tensors.items(): + if torch.is_tensor(val): + sig.append( + (name, "tensor", val.dtype, tuple(val.shape), tuple(val.stride())) + ) + else: + sig.append((name, type(val).__name__)) + return tuple(sig) + + +# Reentrant: get_efc_kernel_with_epilogue holds this lock and may call +# get_kernel_by_name -> _ensure_caches, which re-acquires it on the same thread. +_cache_lock = threading.RLock() + +# Full kernel manifest: kernel_name -> kernel object. Built lazily (~14s, ~290K +# operators) only as a LAST-RESORT fallback -- the common paths (choice +# generation and subprocess precompile) resolve operators via cheap +# args-filtered queries and cache them in _ops_by_name. +_kernel_by_name_cache: dict[str, Any] | None = None + + +def _operand_dtype_str(operand: Any) -> str | None: + """Best-effort cutlass dtype name for a kernel operand or args operand.""" + dtype = getattr(operand, "dtype", None) + if dtype is None: + tensor = getattr(operand, "tensor", None) + dtype = getattr(tensor, "dtype", None) + return None if dtype is None else str(dtype) + + +def _build_kernel_cache() -> dict[str, Any]: + """Build the full kernel name -> kernel manifest (fallback path only).""" + import cutlass.operators + + log.debug("Building NVGEMM kernel cache (this may take a few seconds)...") + + try: + from torch._inductor.kernel.vendored_templates.cutedsl import ( # noqa: F401 + wrappers, + ) + except ImportError: + log.debug("Vendored kernel wrappers not available") + + all_kernels = cutlass.operators.get_operators() + cache = {k.metadata.operator_name: k for k in all_kernels} + log.debug("NVGEMM kernel manifest built: %d kernels", len(cache)) + return cache + + +def _ensure_caches() -> None: + global _kernel_by_name_cache + if _kernel_by_name_cache is None: + with _cache_lock: + if _kernel_by_name_cache is None: + _kernel_by_name_cache = _build_kernel_cache() + + +def _get_kernel_cache() -> dict[str, Any]: + """Return the fallback manifest, building it lazily if needed. + + Snapshot to local frame: a concurrent clear_cache() rebinding the global to + None cannot turn the caller's subsequent read into AttributeError. + """ + _ensure_caches() + cache = _kernel_by_name_cache + if cache is None: + raise AssertionError("expected cache to be not None") + return cache + + +def _operand_sig(operand: Any) -> tuple | None: + """Hashable (dtype, shape, stride, scale-sig, mode, swizzle) signature.""" + if operand is None: + return None + w = getattr(operand, "tensor", operand) + dtype = _operand_dtype_str(operand) + shape = getattr(w, "shape", None) + stride = getattr(w, "stride", None) + if dtype is None or shape is None or stride is None: + return None + scale = getattr(operand, "scale", None) + scale_sig = _operand_sig(scale) if scale is not None else None + # ScaledOperand.mode/.swizzle are distinct from the scale tensor's layout + # and are not folded into it, yet supports(args) depends on them -- two + # scaled GEMMs with identical operand/scale layouts but different scale or + # swizzle modes must not collide. Read from __dict__ (only ScaledOperand + # sets these) so a dense operand's torch.Tensor.mode method isn't captured. + d = getattr(operand, "__dict__", {}) + mode, swizzle = d.get("mode"), d.get("swizzle") + # mode/swizzle are cutlass.operators enums (ScaleMode/ScaleSwizzleMode) that + # are unhashable, so key on their .name to keep the sig usable as a dict key. + mode = getattr(mode, "name", mode) + swizzle = getattr(swizzle, "name", swizzle) + return (dtype, tuple(shape), tuple(stride), scale_sig, mode, swizzle) + + +def _partition_sig(args: Any) -> tuple | None: + """Signature capturing everything `supports(args)` depends on, or None if + it can't be fully determined (falls back to a non-memoized scan).""" + a = _operand_sig(getattr(args, "A", None)) + b = _operand_sig(getattr(args, "B", None)) + o = _operand_sig(getattr(args, "out", None)) + if a is None or b is None or o is None: + return None + return (a, b, o, getattr(args, "accumulator_type", None)) + + +# Per-process cache of instantiated operators, keyed by operator_name. Populated +# incrementally by the args-filtered queries below (choice generation and the +# subprocess precompile fast path). One args query returns the whole set of +# operators compatible with a shape (hundreds); we index all of them, so any +# later lookup -- another config of that shape, another shape sharing those +# templates, or get_kernel_by_name for a chosen +# kernel -- resolves in O(1) without rebuilding the ~14s manifest. Operator +# names embed the arch (e.g. "..._sm100_..."), so the name alone is unambiguous +# within a process. Reusing an operator across different args is safe for the +# same reason the manifest always has been: an operator is a config template +# (its args-specific state lives in the artifact returned by compile(args)), and +# every (name, args) pairing routed here was validated by supports(args). +_ops_by_name: dict[str, Any] = {} + +# Memoizes partition results. `partition_compatible_kernels` is called once per +# GEMM node during choice generation, but FLUX has hundreds of nodes sharing a +# handful of shapes (e.g. 114 nodes are all 4608x3072x3072); memoizing collapses +# that to one args query per unique shape. +_partition_cache: dict[tuple, list[list[Any]]] = {} + + +def _args_query_candidates(args: Any, cc: int, efc_only: bool) -> list[Any]: + """Compatible operators via an args-filtered get_operators query (~0.05s). + + cutlass prunes by supports(args) and the device target internally. Only + valid for the dense GEMM path: for that path this returns the identical set + as the full-manifest scan (verified), avoiding the ~14s manifest build. + """ + import cutlass.operators + + metadata_filter = ( + (lambda md: "EFC" in md.operator_class.__name__) if efc_only else None + ) + return cutlass.operators.get_operators( + args=args, target_sm=f"{cc}a", metadata_filter=metadata_filter + ) + + +def _filter_supported(kernels: Any, args: Any, cc: int) -> list[Any]: + """Keep the kernels that support `args` on this device. + + Prunes by (A, B) operand dtype first (a cheap string compare) so the + expensive supports() runs only on the ~hundreds that could possibly match -- + the ~290K manifest spans all dtypes, and a GEMM only matches its own. + """ + device_target = _device_target(cc) + dtype_a = _operand_dtype_str(getattr(args, "A", None)) + dtype_b = _operand_dtype_str(getattr(args, "B", None)) + out = [] + for kernel in kernels: + if kernel.designed_for_min_cc > cc: + continue + operands = kernel.metadata.operands + if ( + _operand_dtype_str(getattr(operands, "A", None)) != dtype_a + or _operand_dtype_str(getattr(operands, "B", None)) != dtype_b + ): + continue + if not device_target.supports_operators_from(kernel.metadata.supported_targets): + continue + if kernel.supports(args).error is not None: + continue + out.append(kernel) + return out + + +def _manifest_candidates(args: Any, cc: int, efc_only: bool) -> list[Any]: + """Compatible operators via a full-manifest scan (last-resort fallback).""" + kernels = _get_kernel_cache().values() + if efc_only: + kernels = ( + kernel + for kernel in kernels + if "EFC" in kernel.metadata.operator_class.__name__ + ) + return _filter_supported(kernels, args, cc) + + +def _blockscaled_provider_classes() -> list[Any]: + """The operator classes that produce block-scaled (fp4/fp8) kernels. + + Both the cutlass built-in and the vendored provider matter: for NVFP4 the + vendored kernels supply most of the working configs (60 of 96), so missing + either under-generates and breaks scaled autotuning. + """ + classes: list[Any] = [] + try: + from cutlass.operators.providers.cutedsl.gemm.sm100_dense_blockscaled_static_persistent import ( + PersistentDenseBlockScaledGemmOperator, + ) + + classes.append(PersistentDenseBlockScaledGemmOperator) + except ImportError: + pass + try: + from torch._inductor.kernel.vendored_templates.cutedsl.wrappers.dense_blockscaled_gemm_kernel import ( + VendoredDenseBlockScaledGemmKernel, + ) + + classes.append(VendoredDenseBlockScaledGemmKernel) + except ImportError: + pass + return classes + + +@functools.cache +def _blockscaled_operators() -> tuple: + """Generate the architecture-neutral block-scaled operator pool.""" + ops: list[Any] = [] + for cls in _blockscaled_provider_classes(): + ops.extend(cls.generate_operators(lambda md: True, args=None)) + return tuple(ops) + + +def _scaled_operand_type_signature(args: Any) -> tuple: + def operand_signature(operand: Any) -> tuple: + scale = getattr(operand, "scale", None) + return ( + _operand_dtype_str(operand), + _operand_dtype_str(scale), + str(getattr(operand, "mode", None)), + str(getattr(operand, "swizzle", None)), + ) + + return ( + operand_signature(args.A), + operand_signature(args.B), + _operand_dtype_str(args.out), + str(getattr(args, "accumulator_type", None)), + ) + + +def _scaled_metadata_type_signature(metadata: Any) -> tuple: + operands = metadata.operands + + def operand_signature(operand: Any) -> tuple: + scale = getattr(operand, "scale", None) + return ( + _operand_dtype_str(operand), + _operand_dtype_str(scale), + str(getattr(operand, "mode", None)), + str(getattr(operand, "swizzle", None)), + ) + + return ( + operand_signature(operands.A), + operand_signature(operands.B), + _operand_dtype_str(operands.out), + str(getattr(operands, "accumulator_type", None)), + ) + + +@functools.cache +def _blockscaled_manifest(cc: int, type_signature: tuple): + """Build a block-scaled manifest for one operand type recipe. + + The provider set is generated without a concrete target to preserve its + complete design space. The manifest applies shape and target filtering when + candidates are requested. + """ + import cutlass.operators + + manifest = cutlass.operators.Manifest() + manifest.add_operators( + [ + op + for op in _blockscaled_operators() + if _scaled_metadata_type_signature(op.metadata) == type_signature + ] + ) + return manifest + + +def _scaled_candidates(args: Any, cc: int, efc_only: bool) -> list[Any]: + """Compatible operators for a scaled GEMM via direct block-scaled enumeration. + + get_operators(args=...) derives operand configs from the args and + under-generates for scaled (e.g. ~36 of 96 valid fp4 kernels), so we scan the + block-scaled sub-provider's full design space instead -- complete, and ~50x + cheaper than the manifest. Falls back to the manifest if the provider is + unavailable or nothing matches (e.g. a future non-block-scaled scaled dtype). + """ + from torch._inductor.kernel.vendored_templates.cutedsl.wrappers.dense_blockscaled_gemm_kernel import ( + VendoredDenseBlockScaledGemmEFC, + VendoredDenseBlockScaledGemmKernel, + ) + + manifest = _blockscaled_manifest(cc, _scaled_operand_type_signature(args)) + if manifest.operators: + out = manifest.filter_operators( + args=args, + target_sm=f"{cc}a", + ) + if out: + efc = [] + for op in out: + if op.metadata.operator_class is not VendoredDenseBlockScaledGemmKernel: + continue + metadata = dataclasses.replace( + op.metadata, + operator_name=op.metadata.operator_name.replace( + "VendoredDenseBlockScaledGemmKernel", + "VendoredDenseBlockScaledGemmEFC", + 1, + ), + operator_class=VendoredDenseBlockScaledGemmEFC, + ) + efc.append(VendoredDenseBlockScaledGemmEFC(metadata)) + if efc: + return efc if efc_only else [*out, *efc] + if not efc_only: + return out + return _manifest_candidates(args, cc, efc_only) + + +def partition_compatible_kernels( + args: Any, + cc: int, + classifier: Callable[[Any], int], + num_buckets: int, + efc_only: bool = False, + candidate_source: Literal["args", "scaled", "manifest"] = "manifest", + classifier_key: str | None = None, +) -> list[list[Any]]: + """Partition the operators compatible with `args` into N buckets. + + `classifier(metadata)` returns a bucket index in [0, num_buckets-1] or -1 to + drop the kernel. `candidate_source` selects how the compatible set is found, + all of which avoid the ~14s full manifest except "manifest": + - "args" dense GEMM: cheap args-filtered get_operators query + - "scaled" scaled GEMM: direct block-scaled sub-provider enumeration + - "manifest" fallback (e.g. grouped GEMM): full-manifest scan + `efc_only` restricts to epilogue-fusion-capable kernels (the addmm/bias + path). Results are memoized per (shape, cc, num_buckets, efc_only, source). + """ + sig = _partition_sig(args) + cache_key = ( + (sig, cc, num_buckets, efc_only, candidate_source, classifier_key) + if sig is not None and classifier_key is not None + else None + ) + if cache_key is not None: + cached = _partition_cache.get(cache_key) + if cached is not None: + return [list(b) for b in cached] + + if candidate_source == "args": + candidates = _args_query_candidates(args, cc, efc_only) + elif candidate_source == "scaled": + candidates = _scaled_candidates(args, cc, efc_only) + elif candidate_source == "manifest": + candidates = _manifest_candidates(args, cc, efc_only) + else: + raise ValueError(f"Unknown NVGEMM candidate source: {candidate_source}") + + buckets: list[list[Any]] = [[] for _ in range(num_buckets)] + for kernel in candidates: + # Share every compatible operator so a later get_kernel_by_name (e.g. the + # scheduling max_active_clusters lookup for the chosen kernel) hits + # without building the manifest. + _ops_by_name.setdefault(kernel.metadata.operator_name, kernel) + bucket = classifier(kernel.metadata) + if bucket < 0: + continue + buckets[bucket].append(kernel) + log.debug( + "Partitioned %d compatible operators into buckets %s", + len(candidates), + [len(b) for b in buckets], + ) + if cache_key is not None: + _partition_cache[cache_key] = [list(b) for b in buckets] + return buckets + + +def get_kernel_by_name(kernel_name: str) -> Any: + """Get a kernel by name. + + Checks the incrementally-populated operator cache first (filled by the + args-filtered queries during choice generation / precompile), falling back + to the full manifest only if the name was never resolved via args. + """ + kernel = _ops_by_name.get(kernel_name) + if kernel is not None: + return kernel + return _get_kernel_cache().get(kernel_name) + + +def get_kernel_by_name_via_args(kernel_name: str, args: Any, cc: int) -> Any: + """Fast single-kernel lookup via an args-filtered get_operators query. + + Passing concrete `args` (a cutlass RuntimeArguments) plus the device target + prunes the operator space to the ~hundreds compatible with this exact GEMM + in ~0.05s, versus ~14s to enumerate/construct the full ~294K-kernel manifest + (`get_kernel_by_name`). Used by subprocess precompile workers, which need + only the single named kernel and would otherwise each rebuild the whole + manifest. + + A miss runs one args query and indexes every operator it returns into + _ops_by_name, so the ~50ms cost is paid once per distinct operator (not once + per lookup) and is amortized across all configs and shapes a persistent + worker handles. Returns None if no operator matches the name (caller then + falls back to the full manifest). + """ + import cutlass.operators + + cached = _ops_by_name.get(kernel_name) + if cached is not None: + return cached + + ops = cutlass.operators.get_operators(args=args, target_sm=f"{cc}a") + for op in ops: + # setdefault: keep an already-cached (possibly already-compiled) object + # rather than replacing it with a fresh instance from this query. + _ops_by_name.setdefault(op.metadata.operator_name, op) + if ( + kernel_name not in _ops_by_name + and "VendoredDenseBlockScaledGemmEFC" in kernel_name + ): + from cutlass.operators.arguments import GemmArguments + + base_args = GemmArguments( + args.A, + args.B, + args.out, + accumulator_type=args.accumulator_type, + ) + scaled_ops = _scaled_candidates(base_args, cc, efc_only=False) + log.debug( + "Scaled by-name fallback found %d candidates for %s", + len(scaled_ops), + kernel_name, + ) + for op in scaled_ops: + _ops_by_name.setdefault(op.metadata.operator_name, op) + return _ops_by_name.get(kernel_name) + + +def ensure_cache_initialized() -> None: + """Ensure the kernel cache is initialized.""" + _get_kernel_cache() + + +_efc_epilogue_cache: dict[tuple[str, str, tuple], Any] = {} + + +def clear_cache() -> None: + """Clear all kernel caches.""" + global _kernel_by_name_cache, _efc_epilogue_cache + with _cache_lock: + _kernel_by_name_cache = None + _efc_epilogue_cache = {} + _partition_cache.clear() + _ops_by_name.clear() + _blockscaled_operators.cache_clear() + _blockscaled_manifest.cache_clear() + + +class _NVGEMMCacheWrapper: + def cache_clear(self) -> None: + clear_cache() + + +from torch._inductor.utils import clear_on_fresh_cache + + +clear_on_fresh_cache(_NVGEMMCacheWrapper()) + + +def _meta_epilogue_metadata(epilogue_args: Any) -> Any: + """Build the cached kernel's epilogue metadata from meta-device tensors. + + The EFC kernel is cached in ``_efc_epilogue_cache`` and reused across every + call; the real output/aux tensors are supplied per call via the runtime + ``GemmArguments.epilogue``, so the cached kernel needs only the epilogue's + shape/dtype/layout (its IR). Building it from the real ``EpilogueArguments`` + would make it retain those tensors forever -- ``EpilogueMetadata`` shares the + arguments' ``tensors`` (wrapping the output ``D`` and aux inputs) and traced + functor -- keeping the (often intermediate) output alive: a memory leak, and + it breaks CUDA graph capture (a live graph-pool allocation that is not a + tracked graph output). Re-trace the epilogue with meta tensors (carrying + dtype/layout but no device storage; the tracer reads only their metadata) so + the cached kernel holds nothing real. + """ + from cutlass.operators.arguments.epilogue import EpilogueArguments + from cutlass.operators.metadata import EpilogueMetadata + from cutlass.operators.utils.tensor import TensorWrapper + + from .nv_universal_gemm_utils import cutlass_dtype_to_torch + + def _meta_like(t: torch.Tensor) -> torch.Tensor: + return torch.empty_strided(t.shape, t.stride(), dtype=t.dtype, device="meta") + + fake_kwargs = {} + for name, val in epilogue_args.tensors.items(): + # Build a storage-free meta tensor with the same shape/stride/dtype. + # A compile-time-only TensorWrapper (the subprocess-precompile path) has + # no runtime tensor -- its `.runtime_tensor` property raises ValueError -- + # so read `_runtime_tensor` directly and fall back to the wrapper's own + # shape/stride and its CUTLASS dtype. + if isinstance(val, torch.Tensor): + fake_kwargs[name] = _meta_like(val) + elif isinstance(val, TensorWrapper) and isinstance( + val._runtime_tensor, torch.Tensor + ): + fake_kwargs[name] = _meta_like(val._runtime_tensor) + elif ( + isinstance(val, TensorWrapper) + and (dtype := cutlass_dtype_to_torch(val.dtype)) is not None + ): + fake_kwargs[name] = torch.empty_strided( + tuple(val.shape), tuple(val.stride), dtype=dtype, device="meta" + ) + else: + fake_kwargs[name] = val + fake_args = EpilogueArguments(epilogue_args.epilogue_fn, **fake_kwargs) + accum = epilogue_args.traced_epilogue.example_inputs["accum"] + fake_args.trace(accum.shape, accum.element) + return EpilogueMetadata.from_args(fake_args) + + +def get_efc_kernel_with_epilogue( + efc_kernel_name: str, + epilogue_args: Any, + epilogue_source: str = "", + base_kernel: Any | None = None, +) -> Any: + """Get (or create and cache) an EFC kernel bound to a specific epilogue. + + epilogue_source is preferred over inspect.getsource — generated functions + produce unstable source strings that can't be hashed reliably. + + base_kernel: pre-resolved base EFC kernel (e.g. from the args-filtered fast + lookup in a subprocess worker). When None, falls back to the full manifest. + """ + if not epilogue_source: + epilogue_source = str(epilogue_args) if epilogue_args is not None else "" + + cache_key = ( + efc_kernel_name, + epilogue_source, + _epilogue_args_signature(epilogue_args), + ) + + with _cache_lock: + if cache_key in _efc_epilogue_cache: + log.debug("EFC kernel with epilogue found in cache: %s", efc_kernel_name) + return _efc_epilogue_cache[cache_key] + + if base_kernel is None: + # Prefer the args-resolved operator cache (populated by choice + # generation); only build the full manifest if the name was never + # seen via args. + base_kernel = get_kernel_by_name(efc_kernel_name) + if base_kernel is None: + log.debug("Base EFC kernel not found: %s", efc_kernel_name) + return None + + from cutlass.operators.metadata import OperatorMetadata + + epilogue_metadata = _meta_epilogue_metadata(epilogue_args) + + base_metadata = base_kernel.metadata + new_metadata = OperatorMetadata( + operands=base_metadata.operands, + design=base_metadata.design, + operator_name=base_metadata.operator_name, + operator_class=base_metadata.operator_class, + supported_targets=base_metadata.supported_targets, + epilogue=epilogue_metadata, + ) + + kernel_class = base_metadata.operator_class + new_kernel = kernel_class(new_metadata) + + _efc_epilogue_cache[cache_key] = new_kernel + log.debug("Created and cached EFC kernel with epilogue: %s", efc_kernel_name) + + return new_kernel diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm.py new file mode 100644 index 0000000000000000000000000000000000000000..eb9de1cfcf8a3765d7db4e6d9e5704bc965cdcdc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm.py @@ -0,0 +1,1075 @@ +# mypy: allow-untyped-defs +""" +NVIDIA Universal GEMM (NVGEMM) backend for PyTorch Inductor. + +This module provides integration with the cutlass.operators library to enable +high-performance GEMM kernels for NVIDIA GPUs. +""" + +import itertools +import re +from enum import auto, Enum +from typing import Any, Literal + +import torch +from torch._inductor import config +from torch._inductor.autotune_process import ( + BenchmarkRequest, + GPUDeviceBenchmarkMixin, + TensorMeta, +) +from torch._inductor.codegen.cuda.cuda_env import get_cuda_arch +from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import ( + _compile_nvgemm, + _create_gemm_arguments, + _create_gemm_cache_key, + _current_target_sm, + _get_scaled_gemm_modes, + _make_disk_config_key, + _nvgemm_bias_add_epilogue, + _rewrap_efc_compiled_obj, + _unwrap_efc_compiled_obj, +) +from torch._inductor.heuristics.template.nv_universal_gemm import get_nvgemm_heuristics +from torch._inductor.ir import ( + Buffer, + ChoiceCaller, + FixedLayout, + Layout, + PermuteView, + TensorBox, +) +from torch._inductor.kernel_inputs import MMKernelInputs +from torch._inductor.utils import ensure_nv_universal_gemm_available +from torch._inductor.virtualized import V +from torch._logging import getArtifactLogger + + +log = getArtifactLogger(__name__, "output_code") + + +class GemmVariant(Enum): + """ + Enum for different GEMM operation types supported by NVIDIA Universal GEMM. + """ + + GEMM = auto() + + GROUPED_GEMM = auto() + + SCALED_GEMM = auto() + + @property + def op_name(self) -> str: + """Return the operation name for logging and naming.""" + if self == GemmVariant.GROUPED_GEMM: + return "nv_universal_grouped_gemm" + if self == GemmVariant.SCALED_GEMM: + return "nv_universal_scaled_gemm" + return "nv_universal_gemm" + + +class NVUniversalGemmBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest): + """Benchmark request for NVIDIA Universal GEMM kernels.""" + + def __init__( + self, + kernel_name: str, + input_tensor_meta: TensorMeta | list[TensorMeta], + output_tensor_meta: TensorMeta | list[TensorMeta], + kernel, # cutlass.operators.Operator object + accumulator_type: torch.dtype, + variant: GemmVariant, + 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, + swap_ab: bool = False, + has_bias_epilogue: bool = False, + ) -> None: + super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, ()) + self.kernel = kernel + self.accumulator_type = accumulator_type + self.has_bias_epilogue = has_bias_epilogue + self._workspace: torch.Tensor | None = None + self._disk_fn_cache: dict = {} + 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.swap_ab = swap_ab + + def benchmark( + self, + *input_tensors: torch.Tensor, + out: torch.Tensor | None = None, + ) -> float: + """Benchmark the NVIDIA Universal GEMM kernel. + + Override the base class to always create tensors from input_tensor_meta. + This is necessary because input_nodes may be ReinterpretViews that share + the same underlying buffer name. The autotuning framework deduplicates + inputs by name (in AlgorithmSelectorCache.get_inputs()), resulting in + fewer tensors than expected. By always creating from input_tensor_meta, + we ensure each input gets its own tensor with the correct size/stride/offset + from the view's layout. + + """ + from torch._inductor.runtime.benchmarking import benchmarker + + input_tensors = tuple(x.to_tensor() for x in self.input_tensor_meta) + if out is None: + out = self.output_tensor_meta.to_tensor() + + fn = self.make_run_fn(*input_tensors, out=out) + try: + if self.benchmark_with_cudagraphs: + res = benchmarker.benchmark_gpu_with_cuda_graph(fn) + else: + res = self.do_bench(fn, *input_tensors, out=out) + finally: + self.cleanup_run_fn() + return res + + def make_run_fn(self, *input_tensors: torch.Tensor, out: torch.Tensor): + """Create a function to run the NVIDIA Universal GEMM kernel.""" + from cutlass.operators.artifact import CompiledArtifact + + from torch._inductor.runtime.cutedsl_cache import disk_cache_get, disk_cache_set + from torch._inductor.utils import _ensure_fp4_dtype_registered + + _ensure_fp4_dtype_registered() + + if self.has_bias_epilogue: + # Benchmark the real fused kernel (GEMM + bias-add epilogue). The + # bias is the last input; the rest are the GEMM operands. + return self._make_bias_run_fn(input_tensors, out) + + # swap_ab: transpose operands and write into a transposed view of `out` + # (zero-copy). See _nvgemm_run for the full explanation. + if self.swap_ab and len(input_tensors) >= 2: + a, b = input_tensors[0], input_tensors[1] + if len(input_tensors) >= 4: + sa, sb = input_tensors[2], input_tensors[3] + input_tensors = (b.t(), a.t(), sb, sa) + input_tensors[4:] + else: + input_tensors = (b.t(), a.t()) + input_tensors[2:] + out = out.t() + + helper_kwargs: dict[str, Any] = {} + if self.variant == GemmVariant.SCALED_GEMM: + scale_mode_a, swizzle_mode_a, scale_mode_b, swizzle_mode_b = ( + _get_scaled_gemm_modes( + self.scale_type_a, + self.swizzle_type_a, + self.scale_type_b, + self.swizzle_type_b, + ) + ) + helper_kwargs = { + "scale_mode_a": scale_mode_a, + "swizzle_mode_a": swizzle_mode_a, + "scale_mode_b": scale_mode_b, + "swizzle_mode_b": swizzle_mode_b, + } + + cache_key = _create_gemm_cache_key(input_tensors, out) + dev_idx = input_tensors[0].device.index or 0 + kernel_name = self.kernel.metadata.operator_name + disk_config_key = _make_disk_config_key( + kernel_name, + self.variant.name, + self.accumulator_type, + self.scale_type_a, + self.scale_type_b, + self.swizzle_type_a, + self.swizzle_type_b, + ) + + def disk_fallback(kernel): + compiled_fn = disk_cache_get( + self._disk_fn_cache, + kernel_name, + disk_config_key, + cache_key, + dev_idx, + ) + if compiled_fn is not None: + compiled_fn = _rewrap_efc_compiled_obj(compiled_fn, kernel) + if compiled_fn is not None: + return CompiledArtifact( + compiled_fn, kernel, _current_target_sm(dev_idx) + ) + return None + + artifact, args, kernel, was_compiled = _compile_nvgemm( + self.variant.name, + input_tensors, + out, + self.accumulator_type, + kernel_obj=self.kernel, + args_kwargs=helper_kwargs, + fallback_fn=disk_fallback, + ) + + if was_compiled: + obj = _unwrap_efc_compiled_obj(artifact.compiled_obj) + disk_cache_set( + self._disk_fn_cache, + kernel_name, + disk_config_key, + cache_key, + obj, + dev_idx, + ) + + # Allocate workspace if needed + if self.workspace_size > 0: + self._workspace = torch.empty( + self.workspace_size, device=out.device, dtype=torch.int8 + ) + else: + self._workspace = None + + workspace = self._workspace + + def run_kernel(): + stream = torch.cuda.current_stream() + kernel.run( + args, + artifact, + stream=stream, + workspace=workspace, + assume_supported_args=True, + ) + + return run_kernel + + def _make_bias_run_fn(self, input_tensors, out): + """Build a run fn for the fused GEMM + bias-add epilogue (addmm). + + Mirrors make_run_fn's disk caching but with the bias epilogue: the + unwrap/rewrap machinery serializes the EFC artifact, so subprocess + precompile (which writes the same key) hands off to the benchmark + instead of recompiling serially. + """ + from cutlass.operators.arguments import EpilogueArguments + from cutlass.operators.artifact import CompiledArtifact + + from torch._inductor.runtime.cutedsl_cache import disk_cache_get, disk_cache_set + + *gemm_tensors, bias = input_tensors + gemm_tensors = tuple(gemm_tensors) + epilogue_args = EpilogueArguments(_nvgemm_bias_add_epilogue, bias=bias, D=out) + + kernel_name = self.kernel.metadata.operator_name + cache_key = _create_gemm_cache_key( + gemm_tensors, out, has_epilogue=True, aux_tensors=(bias,) + ) + dev_idx = gemm_tensors[0].device.index or 0 + disk_config_key = _make_disk_config_key( + kernel_name, + self.variant.name, + self.accumulator_type, + self.scale_type_a, + self.scale_type_b, + self.swizzle_type_a, + self.swizzle_type_b, + ) + + def disk_fallback(kernel): + compiled_fn = disk_cache_get( + self._disk_fn_cache, kernel_name, disk_config_key, cache_key, dev_idx + ) + if compiled_fn is not None: + compiled_fn = _rewrap_efc_compiled_obj( + compiled_fn, kernel, epilogue_args=epilogue_args + ) + if compiled_fn is not None: + return CompiledArtifact( + compiled_fn, kernel, _current_target_sm(dev_idx) + ) + return None + + artifact, args, kernel, was_compiled = _compile_nvgemm( + self.variant.name, + gemm_tensors, + out, + self.accumulator_type, + kernel_name=kernel_name, + epilogue_args=epilogue_args, + epilogue_source="nvgemm_addmm_bias_v1", + fallback_fn=disk_fallback, + base_kernel=self.kernel, + ) + + if was_compiled: + disk_cache_set( + self._disk_fn_cache, + kernel_name, + disk_config_key, + cache_key, + _unwrap_efc_compiled_obj(artifact.compiled_obj), + dev_idx, + ) + + if self.workspace_size > 0: + self._workspace = torch.empty( + self.workspace_size, device=out.device, dtype=torch.int8 + ) + else: + self._workspace = None + workspace = self._workspace + + def run_kernel(): + kernel.run( + args, + artifact, + stream=torch.cuda.current_stream(), + workspace=workspace, + assume_supported_args=True, + ) + + return run_kernel + + def precompile(self): + input_tensors = tuple(x.to_tensor() for x in self.input_tensor_meta) + out = self.output_tensor_meta.to_tensor() + self.make_run_fn(*input_tensors, out=out) + self.cleanup_run_fn() + + def cleanup_run_fn(self) -> None: + self._workspace = None + + +class NVUniversalGemmCaller(ChoiceCaller): + """ + ChoiceCaller for NVIDIA Universal GEMM kernels. + + Wraps a cutlass.operators kernel and integrates with Inductor's autotuning. + """ + + index_counter = itertools.count() + + def __init__( + self, + name: str, + input_nodes: list[Buffer], + layout: Layout, + kernel, # cutlass.operators.Operator object + accumulator_type: torch.dtype, + variant: GemmVariant, + 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, + kernel_layout: Layout | None = None, + bias_node: Buffer | None = None, + ) -> None: + super().__init__( + name=name, + input_nodes=input_nodes, + layout=layout, + description=f"{variant.op_name} {kernel.metadata.operator_name}" + + (" swap_ab" if swap_ab else "") + + (" bias" if bias_node is not None else ""), + ) + self.kernel = kernel + self.accumulator_type = accumulator_type + 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 + self.bias_node = bias_node + self._kernel_layout = kernel_layout or layout + self._cached_output_node: TensorBox | None = None + + output_buffer = Buffer(name=f"{variant.op_name}_out", layout=layout) + + self.bmreq = NVUniversalGemmBenchmarkRequest( + kernel_name=name, + input_tensor_meta=TensorMeta.from_irnodes(input_nodes), + output_tensor_meta=TensorMeta.from_irnodes(output_buffer), + kernel=kernel, + accumulator_type=accumulator_type, + workspace_size=workspace_size, + variant=variant, + scale_type_a=scale_type_a, + scale_type_b=scale_type_b, + swizzle_type_a=swizzle_type_a, + swizzle_type_b=swizzle_type_b, + swap_ab=swap_ab, + has_bias_epilogue=bias_node is not None, + ) + + def __str__(self) -> str: + return f"NVUniversalGemmCaller({self.kernel.metadata.operator_name})" + + def precompile(self): + self.bmreq.precompile() + + def benchmark(self, *args, out) -> float: + self.bmreq.benchmark_with_cudagraphs = self._benchmark_with_cudagraphs + return self.bmreq.benchmark(*args, out=out) + + def output_node(self) -> TensorBox: + from torch._inductor.ir import NVUniversalGemmBuffer + + # Without memoization, each call registers a new buffer (via + # TemplateBuffer.__init__ → V.graph.register_buffer), leaking orphan + # buffers into the graph's name tables during EFC benchmarking. + # + # But a buffer registered during a benchmark sub-context can have its + # name freed when that context rolls back `V.graph.buffers` (names are + # `buf{len(buffers)}`, so a freed slot is reused). A stale cached buffer + # then collides with a fresh buffer that reused its name, corrupting + # finalize_multi_template_buffers. Drop the cache entry in that case and + # rebuild a properly-registered buffer. + if self._cached_output_node is not None: + # pyrefly: ignore [missing-attribute] + cached_name = self._cached_output_node.data.data.get_name() + if cached_name in V.graph.name_to_buffer: + return self._cached_output_node + self._cached_output_node = None + + # For swap_ab, use the original (M, N) layout so the scheduler and + # downstream IR see the expected shape. The runtime handles the + # transpose internally via a temp buffer in _nvgemm_run. + buffer = NVUniversalGemmBuffer( + layout=self.layout, + inputs=self.input_nodes, + kernel=self.kernel, + 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, + supports_epilogue_fusion=self.supports_epilogue_fusion, + swap_ab=self.swap_ab, + bias_node=self.bias_node, + ) + if "ktc" in self.annotations: + buffer.annotations["ktc"] = self.annotations["ktc"] + + self._cached_output_node = TensorBox.create(buffer) + return self._cached_output_node + + def call_name(self) -> str: + return self.name + + def to_callable(self): + return self.bmreq.make_run_fn + + def hash_key(self) -> str: + # `select_algorithm` uses this as a precompile dedup key. Two callers + # wrapping the same physical kernel name but with different accumulator/ + # scale/swizzle types produce distinct compiled artifacts; collapsing + # them here would silently drop the second from autotuning. + return "_".join( + str(x) + for x in ( + self.variant.op_name, + self.kernel.metadata.operator_name, + self.accumulator_type, + self.scale_type_a, + self.scale_type_b, + self.swizzle_type_a, + self.swizzle_type_b, + "swap_ab" if self.swap_ab else "", + ) + ) + + def info_dict(self) -> dict[str, Any]: + info = { + "name": self.name, + "backend": self.variant.op_name, + "kernel_name": self.kernel.metadata.operator_name, + } + if self.swap_ab: + info["swap_ab"] = True + return info + + def get_make_kernel_render(self): + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import ( + NVUniversalGemmKernel, + ) + from torch._inductor.utils import Placeholder + + kernel_metadata = { + "kernel_name": self.kernel.metadata.operator_name, + "min_cc": self.kernel.designed_for_min_cc, + } + 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 + input_nodes = self.input_nodes + swap_ab = self.swap_ab + has_bias = self.bias_node is not None + + def make_kernel_render( + out_node, + hint_override=None, + epilogue_fn_code=None, + epilogue_reads=None, + epilogue_writes=None, + epilogue_var_renames=None, + local_reduce=None, + ): + from torch._inductor.ir import StorageBox, TensorBox + + processed_inputs = [] + for inp in input_nodes: + if isinstance(inp, TensorBox): + inp = inp.data + if isinstance(inp, StorageBox): + inp = inp.data + processed_inputs.append(inp) + + # A baked bias is the last input, consumed by the epilogue rather + # than as a GEMM operand. + bias_node = None + if has_bias: + bias_node = processed_inputs[-1] + processed_inputs = processed_inputs[:-1] + + kernel_name = str(Placeholder.KERNEL_NAME) + + render_kernel = NVUniversalGemmKernel( + kernel_name=kernel_name, + # pyrefly: ignore [bad-argument-type] + input_nodes=processed_inputs, + output_node=out_node, + kernel_metadata=kernel_metadata, + accumulator_type=accumulator_type, + workspace_size=workspace_size, + variant=variant, + scale_type_a=scale_type_a, + scale_type_b=scale_type_b, + swizzle_type_a=swizzle_type_a, + swizzle_type_b=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=swap_ab, + # pyrefly: ignore [bad-argument-type] + bias_node=bias_node, + ) + + def render(): + return render_kernel.render() + + return render_kernel, render + + return make_kernel_render + + +def _create_dummy_tensor_from_layout( + layout: Layout, dtype_override: torch.dtype | None = None +) -> torch.Tensor | None: + """ + Create a FakeTensor from a Layout for kernel filtering. + + Uses Layout.get_example() which creates FakeTensors within V.fake_mode, + avoiding real CUDA memory allocation. cutlass.operators only needs shape/stride/dtype + metadata for its supports() checks. + """ + try: + result = layout.get_example() + if dtype_override is not None and result.dtype != dtype_override: + result = result.view(dtype_override) + return result + except Exception: + # Broad: layout.get_example()/torch.empty_strided under fake mode can + # raise a variety of unexpected errors (TypeError, AssertionError, etc.) + # depending on stride/symint state. Failing to materialize a dummy + # should never abort autotune — just skip this candidate. + return None + + +_TILE_RE = re.compile(r"tile(\d+)x\d+x\d+") + + +def _include_efc_kernels_only(metadata) -> bool: + """Filter to include only EFC (Epilogue Fusion Compatible) kernels. + + Excludes tile_M=64 EFC kernels: cutlass.operators has a broadcast bug in the + epilogue thread operation for aux-tensor inputs with tile_M=64, and we + don't yet know at autotune time whether fusion will consume aux tensors. + Non-EFC kernels still cover tile_M=64, so plain GEMM autotune is unaffected. + + Strictly requires the kernel name to encode tile dims; if cutlass.operators ever + changes the naming scheme, this raises rather than silently letting the + broken tile_M=64 kernels through. + """ + if "EFC" not in metadata.operator_class.__name__: + return False + match = _TILE_RE.search(metadata.operator_name) + if match is None: + raise RuntimeError( + f"NVGEMM EFC kernel name does not match expected tile pattern " + f"'tileMxNxK': {metadata.operator_name}. The tile_M=64 broadcast " + f"workaround in _include_efc_kernels_only depends on this naming " + f"convention; update the regex or move to metadata-based filtering." + ) + return int(match.group(1)) >= 128 + + +def _exclude_efc_kernels(metadata) -> bool: + """Filter to exclude EFC kernels (for non-epilogue cases).""" + return "EFC" not in metadata.operator_class.__name__ + + +def _add_nv_gemm_choices_impl( + choices: list[ChoiceCaller], + layout: Layout, + input_nodes: list[Buffer], + variant: GemmVariant, + accumulator_type: torch.dtype, + mm_inputs: MMKernelInputs | None = None, + scale_type_a: Any | None = None, + scale_type_b: Any | None = None, + swizzle_type_a: Any | None = None, + swizzle_type_b: Any | None = None, + swap_ab: bool = False, + kernel_layout: Layout | None = None, + bias_node: Buffer | None = None, +) -> None: + """ + Unified implementation for adding NVIDIA Universal GEMM choices. + + Args: + choices: List to append ChoiceCaller objects to + layout: Output layout + input_nodes: GEMM operand nodes (A, B) + variant: The GEMM variant (determines behavior) + accumulator_type: Accumulator dtype + mm_inputs: Optional MMKernelInputs for heuristics + scale_type_a: ScalingType for A (required for SCALED_GEMM) + scale_type_b: ScalingType for B (required for SCALED_GEMM) + swizzle_type_a: SwizzleType for A (required for SCALED_GEMM) + swizzle_type_b: SwizzleType for B (required for SCALED_GEMM) + bias_node: Optional addmm bias, consumed as a fixed bias-add epilogue. + Requires EFC kernels; only these are considered when set. + """ + from torch._inductor.utils import _ensure_fp4_dtype_registered + + _ensure_fp4_dtype_registered() + + from torch._inductor.codegen.nv_universal_gemm.kernel_cache import ( + partition_compatible_kernels, + ) + + # Create dummy tensors for cutlass.operators's supports() checks. + # Pass node dtype to handle FP4 ReinterpretView (uint8 storage viewed as float4_e2m1fn_x2). + dummy_tensors = [ + _create_dummy_tensor_from_layout( + node.get_layout(), dtype_override=node.get_dtype() + ) + for node in input_nodes + ] + + if swap_ab and len(dummy_tensors) >= 2: + # swap_ab: transpose mat_a/mat_b dummies (and swap scales when scaled). + # Original: dummy[0]=mat_a(M,K) row, dummy[1]=mat_b(K,N) col + # Swap: new_A=mat_b.t()=(N,K) row, new_B=mat_a.t()=(K,M) col + d_a, d_b = dummy_tensors[0], dummy_tensors[1] + if d_a is not None and d_b is not None: + if len(dummy_tensors) >= 4: + # scaled: new_scale_a=scale_b, new_scale_b=scale_a + d_sa, d_sb = dummy_tensors[2], dummy_tensors[3] + dummy_tensors = [d_b.t(), d_a.t(), d_sb, d_sa] + dummy_tensors[4:] + else: + dummy_tensors = [d_b.t(), d_a.t()] + dummy_tensors[2:] + + effective_layout = kernel_layout if kernel_layout is not None else layout + out_tensor = _create_dummy_tensor_from_layout(effective_layout) + + if any(t is None for t in dummy_tensors) or out_tensor is None: + log.debug("Failed to create dummy tensors for %s", variant.op_name) + return + + helper_kwargs: dict[str, Any] = {} + if variant == GemmVariant.SCALED_GEMM: + try: + scale_mode_a, swizzle_mode_a, scale_mode_b, swizzle_mode_b = ( + _get_scaled_gemm_modes( + scale_type_a, + swizzle_type_a, + scale_type_b, + swizzle_type_b, + ) + ) + except NotImplementedError: + return + helper_kwargs = { + "scale_mode_a": scale_mode_a, + "swizzle_mode_a": swizzle_mode_a, + "scale_mode_b": scale_mode_b, + "swizzle_mode_b": swizzle_mode_b, + } + + args = _create_gemm_arguments( + variant.name, + tuple(dummy_tensors), + out_tensor, + accumulator_type, + **helper_kwargs, + ) + + cc = get_cuda_arch() + if cc is None: + log.debug("Failed to get CUDA arch") + return + cc_int = int(cc) + + # Single-pass partition over the ~390K-entry kernel cache. The two-pass + # form below called `kernel.supports(args)` once per bucket -- i.e. twice + # per non-EFC-class kernel -- across the full cache. + def _classify(metadata) -> int: + if _include_efc_kernels_only(metadata): + return 1 # efc bucket (with tile_M >= 128) + if _exclude_efc_kernels(metadata): + return 0 # non-efc bucket + # NOTE: tile_M < 128 EFC kernels are dropped due to a cutlass.operators + # broadcast bug. Tracking: https://github.com/pytorch/pytorch/issues/181901 + return -1 + + # A baked bias-add requires an epilogue-fusion-capable (EFC) kernel, so + # scan only EFC kernels -- skips supports() on the far larger non-EFC set. + # The args-filtered fast query is complete only for dense GEMM; scaled uses + # direct block-scaled sub-provider enumeration (get_operators under-generates + # operands from scaled args); anything else falls back to the full manifest. + candidate_source: Literal["args", "scaled", "manifest"] + if variant == GemmVariant.GEMM: + candidate_source = "args" + elif variant == GemmVariant.SCALED_GEMM: + candidate_source = "scaled" + else: + candidate_source = "manifest" + non_efc_kernels, efc_kernels = partition_compatible_kernels( + args, + cc_int, + _classify, + num_buckets=2, + efc_only=bias_node is not None, + candidate_source=candidate_source, + classifier_key="nvgemm_efc_partition_v1", + ) + if not config.epilogue_fusion or swap_ab: + efc_kernels = [] + if bias_node is not None: + non_efc_kernels = [] + if not non_efc_kernels and not efc_kernels: + log.debug("No compatible %s kernels found", variant.op_name) + return + + max_configs = config.nvgemm_max_profiling_configs or max( + len(non_efc_kernels), len(efc_kernels) + ) + if variant in (GemmVariant.GEMM, GemmVariant.SCALED_GEMM) and mm_inputs is not None: + heuristics = get_nvgemm_heuristics() + non_efc_kernels = heuristics.filter_kernels( + non_efc_kernels, mm_inputs, max_configs, accumulator_type + ) + efc_kernels = heuristics.filter_kernels( + efc_kernels, mm_inputs, max_configs, accumulator_type + ) + else: + # TODO(nikhilap): Enable heuristics for grouped GEMM + # when nvMatmulHeuristics adds support + non_efc_kernels = non_efc_kernels[:max_configs] + efc_kernels = efc_kernels[:max_configs] + + all_kernels = [(kernel, False) for kernel in non_efc_kernels] + [ + (kernel, True) for kernel in efc_kernels + ] + + # When a bias is baked in, it is appended as the last caller input so the + # scheduler tracks it as a read; the caller/kernel split it back off. + caller_input_nodes = ( + [*input_nodes, bias_node] if bias_node is not None else input_nodes + ) + + num_added = 0 + for kernel, supports_epilogue_fusion in all_kernels: + name = f"{variant.op_name}_{next(NVUniversalGemmCaller.index_counter)}" + workspace_size = kernel.get_workspace_size(args).size_bytes + try: + caller = NVUniversalGemmCaller( + name=name, + input_nodes=caller_input_nodes, + layout=layout, + kernel=kernel, + accumulator_type=accumulator_type, + workspace_size=workspace_size, + variant=variant, + scale_type_a=scale_type_a, + scale_type_b=scale_type_b, + swizzle_type_a=swizzle_type_a, + swizzle_type_b=swizzle_type_b, + supports_epilogue_fusion=supports_epilogue_fusion, + swap_ab=swap_ab, + kernel_layout=kernel_layout, + bias_node=bias_node, + ) + choices.append(caller) + num_added += 1 + except Exception: + # Broad: caller construction touches cutlass.operators / fake-mode tensors + # which can raise types other than RuntimeError/ValueError. A single + # bad choice should never abort the rest of autotune choice population. + log.debug("Failed to create %s choice", variant.op_name, exc_info=True) + + log.debug("Added %d %s choices", num_added, variant.op_name) + + +def add_nv_universal_gemm_choices( + choices: list[ChoiceCaller], + layout: Layout, + inputs: MMKernelInputs, + accumulator_type: torch.dtype | None = None, +) -> None: + """ + Add NVIDIA Universal GEMM kernels to the autotune choices. + + Thin wrapper around _add_nv_gemm_choices_impl for regular GEMM. + """ + if not ensure_nv_universal_gemm_available(): + log.debug( + "cutlass.operators not available, skipping NVIDIA Universal GEMM choices" + ) + return + + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=inputs.nodes(), + variant=GemmVariant.GEMM, + accumulator_type=accumulator_type or torch.float32, + mm_inputs=inputs, + ) + + # swap_ab: swap A/B so the large N goes on the M-axis, improving tile + # utilization for small-M / tall-skinny shapes (M << N). The kernel computes + # (N, M) and the runtime writes it into a transposed view of the (M, N) + # output. Mirrors the scaled path (see add_nv_universal_scaled_gemm_choices) + # but without scale operands. Only valid for 2D mm: this entry point also + # serves BMM (layout [B, M, N]), where the (M, N) / 2D-PermuteView swap logic + # would be wrong, so skip it there. + if not config.nvgemm_swap_ab or len(layout.size) != 2: + return + m, n = layout.size[0], layout.size[1] + swap_kernel_layout = FixedLayout(layout.device, layout.dtype, [n, m]) + # Rank swap configs with the heuristic on the SWAPPED (N, M, K) problem: + # new mat1 = mat_b.t() (N, K) row, new mat2 = mat_a.t() (K, M) col. Without + # this, the swap variant would fall back to an unranked prefix and miss the + # small-tile configs that make swap_ab win. + mat_a, mat_b = inputs.mat1mat2() + swap_inputs = MMKernelInputs( + [PermuteView.create(mat_b, [1, 0]), PermuteView.create(mat_a, [1, 0])] + ) + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=inputs.nodes(), + variant=GemmVariant.GEMM, + accumulator_type=accumulator_type or torch.float32, + mm_inputs=swap_inputs, + swap_ab=True, + kernel_layout=swap_kernel_layout, + ) + + +def add_nv_universal_addmm_choices( + choices: list[ChoiceCaller], + layout: Layout, + inputs: MMKernelInputs, + bias_node: Buffer, + alpha: float | int = 1, + beta: float | int = 1, + accumulator_type: torch.dtype | None = None, +) -> None: + """Add NVGEMM addmm choices: ``bias + mat1 @ mat2`` via an EFC bias-add + epilogue. + + Only the plain ``alpha == beta == 1`` case is handled; other scalings fall + back to the remaining backends. ``bias_node`` should be the original + (un-expanded) bias so a 1D row vector routes to the row-broadcast epilogue + impl -- passing the (M, N) broadcast *view* is rejected by cutlass.operators. + """ + if not ensure_nv_universal_gemm_available(): + return + # Bias-add requires an epilogue-fusion-capable (EFC) kernel. + if not config.epilogue_fusion: + return + if alpha != 1 or beta != 1: + return + + # Only broadcastable row-vector or full biases are supported. The bias last + # dim must match N; higher-rank or column-only biases are left to fallbacks. + n = layout.size[-1] + bias_size = bias_node.get_size() + # Only rank-1 (row vector) or rank-2 (full) biases are supported. The + # epilogue indexes bias_size[-1], so a rank-0 scalar bias would IndexError; + # reject it (and higher-rank biases) so they fall through to other backends. + if not 1 <= len(bias_size) <= 2: + return + if not V.graph.sizevars.statically_known_equals(bias_size[-1], n): + return + + mat1, mat2 = inputs.mat1mat2() + gemm_inputs = MMKernelInputs([mat1, mat2]) + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=[mat1, mat2], + variant=GemmVariant.GEMM, + accumulator_type=accumulator_type or torch.float32, + mm_inputs=gemm_inputs, + bias_node=bias_node, + ) + + +def add_nv_universal_grouped_gemm_choices( + choices: list[ChoiceCaller], + layout: Layout, + input_nodes: list[Buffer], + accumulator_type: torch.dtype | None = None, +) -> None: + """ + Add NVIDIA Universal Grouped GEMM kernels to the autotune choices. + + Thin wrapper around _add_nv_gemm_choices_impl for grouped GEMM. + + For grouped GEMM (contiguous offset variant): + - A is (TotalM, K) with problems stacked along M + - B is (G, K, N) where B[i] is the weight for problem i + - offsets is (G,) marking where each problem ends in A + - Output is (TotalM, N) + """ + if not ensure_nv_universal_gemm_available(): + log.debug( + "cutlass.operators not available, skipping NVIDIA Universal Grouped GEMM choices" + ) + return + + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=input_nodes, + variant=GemmVariant.GROUPED_GEMM, + accumulator_type=accumulator_type or torch.float32, + ) + + +def add_nv_universal_scaled_gemm_choices( + choices: list[ChoiceCaller], + layout: Layout, + input_nodes: list[Buffer], + accumulator_type: torch.dtype | None = None, + kernel_inputs: MMKernelInputs | None = None, +) -> None: + """ + Add NVIDIA Universal Scaled GEMM (FP8) kernels to the autotune choices. + + The scaling type is inferred from the input shapes/dtypes. + If the scaling mode is unsupported by NVGEMM, this function returns without + adding any choices. + """ + if not ensure_nv_universal_gemm_available(): + return + + from torch._inductor.utils import infer_scale_swizzle_ir + + if len(input_nodes) < 4: + return + + mat_a, mat_b, scale_a, scale_b = input_nodes[:4] + + scale_type_a, swizzle_type_a = infer_scale_swizzle_ir(mat_a, scale_a) + scale_type_b, swizzle_type_b = infer_scale_swizzle_ir( + mat_b, scale_b, transpose=True + ) + + if scale_type_a is None or scale_type_b is None: + return + + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=input_nodes, + variant=GemmVariant.SCALED_GEMM, + accumulator_type=accumulator_type or torch.float32, + mm_inputs=kernel_inputs, + scale_type_a=scale_type_a, + scale_type_b=scale_type_b, + swizzle_type_a=swizzle_type_a, + swizzle_type_b=swizzle_type_b, + ) + + # swap_ab: see add_nv_universal_gemm_choices for the rationale (swap A/B so + # the large N lands on the well-tiled M-axis for small-M shapes). + if not config.nvgemm_swap_ab: + return + + # In the IR, mat_a=(M, K/2) row-major, mat_b=(K/2, N) column-major (already .t()). + # swap_ab computes: un_transpose(mat_b) @ transpose(mat_a) = (N,K/2)@(K/2,M) = (N,M). + # Scales: new A uses scale_b (weight scale), new B uses scale_a (activation scale). + # The un-transposed mat_b is (N, K/2) row-major — same as the original weight. + # The transposed mat_a is (K/2, M) column-major. + # Both have the same layout pattern as the original (row-major A, column-major B). + + # Scale inference: new A is the original weight (N, K/2), no transpose. + # For infer_scale_swizzle_ir, we need to pass the un-transposed shape. + # mat_b.t() gives (N, K/2) — but we use transpose=True on mat_b itself + # since mat_b is (K/2, N), so transpose=True flips it to (N, K/2). + swap_scale_type_a, swap_swizzle_type_a = infer_scale_swizzle_ir( + mat_b, scale_b, transpose=True + ) + # New B is the original activation (M, K/2), used transposed as (K/2, M). + # infer_scale_swizzle_ir with transpose=True on mat_a flips (M, K/2) to (K/2, M). + swap_scale_type_b, swap_swizzle_type_b = infer_scale_swizzle_ir( + mat_a, scale_a, transpose=True + ) + + if swap_scale_type_a is None or swap_scale_type_b is None: + return + + # Kernel output shape is (N, M) — the transpose of the original (M, N) + m, n = layout.size[0], layout.size[1] + swap_kernel_layout = FixedLayout(layout.device, layout.dtype, [n, m]) + + # Skip heuristic filtering for swap_ab: mm_inputs has original (M, N, K) but + # the swapped kernel sees (N, M, K). Let the benchmark pick the best kernel. + _add_nv_gemm_choices_impl( + choices=choices, + layout=layout, + input_nodes=input_nodes, + variant=GemmVariant.SCALED_GEMM, + accumulator_type=accumulator_type or torch.float32, + mm_inputs=None, + scale_type_a=swap_scale_type_a, + scale_type_b=swap_scale_type_b, + swizzle_type_a=swap_swizzle_type_a, + swizzle_type_b=swap_swizzle_type_b, + swap_ab=True, + kernel_layout=swap_kernel_layout, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_kernel.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..345469e60e20704019774e6e730362eb34ca6fd9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_kernel.py @@ -0,0 +1,1475 @@ +# mypy: allow-untyped-defs +""" +NVIDIA Universal GEMM kernel code generation. + +This module generates Python code that calls cutlass.operators to execute GEMM operations. +The runtime helpers (_nvgemm_run, _nvgemm_precompile, etc.) are imported by the +generated wrapper at runtime, keeping the generated code thin. +""" + +from __future__ import annotations + +import hashlib +import importlib +import logging +import re +import threading +from typing import Any, TYPE_CHECKING + +from torch._inductor.codegen.common import ( + IndentedBuffer, + Kernel, + WorkspaceArg, + WorkspaceZeroMode, +) +from torch._inductor.codegen.cutedsl.cutedsl_op_overrides import CuteDSLOpOverrides +from torch._inductor.codegen.cutlass.python_evt import _ACCUMULATOR_ARG_NAME +from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_utils import ( + to_cutlass_scale_mode, +) +from torch._inductor.ir import ( + BaseView, + Buffer, + ExternKernel, + MutableBox, + ReinterpretView, +) +from torch._inductor.virtualized import V + + +if TYPE_CHECKING: + from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm import GemmVariant + from torch._inductor.kernel.gemm_epilogue import GemmReductionPlan + + +log = logging.getLogger(__name__) + + +def _current_target_sm(dev_idx: int): + """TargetSm for the current CUDA device, used to stamp disk-cached artifacts.""" + from cutlass.operators.arch import TargetSm + + import torch + + cc = torch.cuda.get_device_capability(dev_idx) + return TargetSm(cc=cc[0] * 10 + cc[1]) + + +def _make_disk_config_key( + kernel_name: str, + variant_name: str, + accumulator_type: Any, + scale_type_a: Any | None = None, + scale_type_b: Any | None = None, + swizzle_type_a: Any | None = None, + swizzle_type_b: Any | None = None, +) -> tuple: + return ( + kernel_name, + variant_name, + str(accumulator_type), + str(scale_type_a), + str(scale_type_b), + str(swizzle_type_a), + str(swizzle_type_b), + ) + + +def _compile_nvgemm( + variant_name, + input_tensors, + out, + accumulator_type, + *, + kernel_obj=None, + kernel_name: str | None = None, + args_kwargs=None, + epilogue_args=None, + epilogue_source="", + fallback_fn=None, + cc: int | None = None, + base_kernel=None, +): + """Compile an NVGEMM artifact, trying a fallback (disk cache) first. + + Thread safety is handled at the dispatch layer: autotuning precompile + runs in subprocess workers (process-isolated), runtime is + single-threaded per graph execution. + + kernel_obj: pre-resolved kernel (skips _lookup_gemm_kernel). + kernel_name: kernel name for _lookup_gemm_kernel. + base_kernel: pre-reconstructed operator (from metadata passed by the main + process); lets _lookup_gemm_kernel skip operator discovery entirely. + args_kwargs: extra kwargs forwarded to _create_gemm_arguments. + fallback_fn: callable(kernel) -> artifact | None, called before + compiling (for disk cache lookup). + + Returns (artifact, args, kernel, was_compiled). + """ + was_compiled = False + + args = _create_gemm_arguments( + variant_name, + input_tensors, + out, + accumulator_type, + epilogue=epilogue_args, + **(args_kwargs or {}), + ) + if kernel_obj is not None: + kernel = kernel_obj + else: + kernel = _lookup_gemm_kernel( + kernel_name, # pyrefly: ignore[bad-argument-type] + epilogue_args=epilogue_args, + epilogue_source=epilogue_source, + args=args if cc is not None else None, + cc=cc, + base_kernel=base_kernel, + ) + + artifact = None + if fallback_fn is not None: + artifact = fallback_fn(kernel) + if artifact is None: + artifact = kernel.compile(args) + was_compiled = True + + return artifact, args, kernel, was_compiled + + +class CUDAContextMetadata: + """CUDA device metadata that subprocess workers can't query on their own. + + Subprocess compile workers don't have CUDA initialized (and can't due to + fork restrictions). This bundles the values the main process must provide. + """ + + __slots__ = ("max_active_clusters", "device_capability") + + def __init__( + self, + max_active_clusters: int | None, + device_capability: tuple[int, int], + ): + self.max_active_clusters = max_active_clusters + self.device_capability = device_capability + + @staticmethod + def from_kernel(kernel, device) -> CUDAContextMetadata: + """Build from a cutlass.operators Kernel and torch device in the main process.""" + import torch + + mac = None + try: + cluster_shape = getattr( + getattr(kernel, "impl", None), "cluster_shape_mn", None + ) + if cluster_shape is not None: + from cutlass.operators.providers.cutedsl.integration_utils.mma import ( + get_max_active_clusters, + ) + + mac = get_max_active_clusters(cluster_shape) + except Exception: + log.warning("Failed to query max_active_clusters", exc_info=True) + cc = torch.cuda.get_device_capability(device) + return CUDAContextMetadata(mac, cc) + + +def _patch_max_active_clusters(max_active_clusters): + """Patch get_max_active_clusters in all CuTeDSL modules. + + Returns a list of (module, original_fn) pairs for restoration. + Subprocess workers don't have CUDA initialized, so they can't query + the driver; this patches in the pre-computed value from the main process. + """ + patched = [] + + def mac_fn(*a, **kw): + return max_active_clusters + + for mod_name in _MAX_ACTIVE_CLUSTERS_MODULES: + try: + m = importlib.import_module(mod_name) + except ImportError: + continue + if hasattr(m, "get_max_active_clusters"): + patched.append((m, m.get_max_active_clusters)) + m.get_max_active_clusters = mac_fn # pyrefly: ignore [missing-attribute] + return patched + + +def _restore_max_active_clusters(patched): + """Undo _patch_max_active_clusters.""" + for m, orig in patched: + m.get_max_active_clusters = orig # pyrefly: ignore [missing-attribute] + + +def _worker_nvgemm_autotuning_precompile( + kernel_name, + variant_name, + accumulator_type, + input_tensor_meta, + output_tensor_meta, + extra_env, + cuda_ctx, + scale_type_a=None, + scale_type_b=None, + swizzle_type_a=None, + swizzle_type_b=None, + has_bias_epilogue=False, + swap_ab=False, + metadata=None, +): + """Subprocess worker: compile one NVGEMM kernel and save to disk cache. + + Called from AsyncCompile.nvgemm_precompile() in a subprocess worker + so CuTeDSL compilation is process-isolated (no thread-safety issues). + Returns (None, elapsed_us) for compatibility with the precompile callback. + """ + import time + + # Share the persistent-worker env/cache handling used by PyCodeCache workers. + from torch._inductor.runtime.compile_tasks import ( + _apply_subprocess_env_and_clear_caches, + ) + + _apply_subprocess_env_and_clear_caches(extra_env) + + start_ns = time.time_ns() + + import torch + from torch._inductor.runtime.cutedsl_cache import disk_cache_set + from torch._inductor.utils import _ensure_fp4_dtype_registered + from torch._subclasses.fake_tensor import FakeTensorMode + + _ensure_fp4_dtype_registered() + + with FakeTensorMode(): + input_tensors = tuple( + torch.empty_strided(m.sizes, m.strides, device=m.device, dtype=m.dtype) + for m in input_tensor_meta + ) + out = torch.empty_strided( + output_tensor_meta.sizes, + output_tensor_meta.strides, + device=output_tensor_meta.device, + dtype=output_tensor_meta.dtype, + ) + + # swap_ab: the kernel was selected for the transposed (N, M) problem, so the + # worker must swap operands here too -- both to resolve the kernel via the + # args-filtered fast lookup and to key the disk cache the same way the + # benchmark's make_run_fn does (it swaps before compiling). Mirrors the + # runtime swap in _nvgemm_run. swap_ab and a bias epilogue never co-occur. + if swap_ab and len(input_tensors) >= 2: + a, b = input_tensors[0], input_tensors[1] + if len(input_tensors) >= 4: + sa, sb = input_tensors[2], input_tensors[3] + input_tensors = (b.t(), a.t(), sb, sa) + input_tensors[4:] + else: + input_tensors = (b.t(), a.t()) + input_tensors[2:] + out = out.t() + + helper_kwargs: dict[str, Any] = {} + if variant_name == "SCALED_GEMM": + scale_mode_a, swizzle_mode_a, scale_mode_b, swizzle_mode_b = ( + _get_scaled_gemm_modes( + scale_type_a, swizzle_type_a, scale_type_b, swizzle_type_b + ) + ) + helper_kwargs = { + "scale_mode_a": scale_mode_a, + "swizzle_mode_a": swizzle_mode_a, + "scale_mode_b": scale_mode_b, + "swizzle_mode_b": swizzle_mode_b, + } + + # For an addmm bias choice the last input is the bias, consumed by a + # bias-add epilogue; the rest are the GEMM operands. Building the epilogue + # (and keying the cache with it) here lets the parallel precompile hand off + # to the benchmark, which reads the same key. + epilogue_args = None + epilogue_source = "" + aux_tensors: tuple = () + if has_bias_epilogue: + from cutlass.operators.arguments import EpilogueArguments + + *gemm_list, bias = input_tensors + input_tensors = tuple(gemm_list) + epilogue_args = EpilogueArguments(_nvgemm_bias_add_epilogue, bias=bias, D=out) + epilogue_source = "nvgemm_addmm_bias_v1" + aux_tensors = (bias,) + + cache_key = _create_gemm_cache_key( + input_tensors, out, has_epilogue=has_bias_epilogue, aux_tensors=aux_tensors + ) + dev_idx = input_tensors[0].device.index or 0 + disk_config_key = _make_disk_config_key( + kernel_name, + variant_name, + accumulator_type, + scale_type_a, + scale_type_b, + swizzle_type_a, + swizzle_type_b, + ) + disk_fn_cache: dict = {} + + # cc for the args-filtered fast kernel lookup: workers can't query the CUDA + # driver, so use the bundled device capability instead of rebuilding the + # full ~294K-kernel manifest just to resolve one kernel by name. + major, minor = cuda_ctx.device_capability + worker_cc = major * 10 + minor + + patched = _patch_max_active_clusters(cuda_ctx.max_active_clusters) + try: + # Best path: the main process passed the chosen operator's metadata, so + # reconstruct exactly that one operator (~us) instead of enumerating the + # operator space. Done inside the patched region since construction may + # query max_active_clusters, which the worker can't get from the driver. + base_kernel = None + if metadata is not None: + try: + base_kernel = metadata.operator_class(metadata) + except Exception: + log.warning( + "Failed to reconstruct NVGEMM operator %s from metadata; " + "falling back to argument-based lookup", + kernel_name, + exc_info=True, + ) + + artifact, _, _, was_compiled = _compile_nvgemm( + variant_name, + input_tensors, + out, + accumulator_type, + kernel_name=kernel_name, + args_kwargs=helper_kwargs, + epilogue_args=epilogue_args, + epilogue_source=epilogue_source, + cc=worker_cc, + base_kernel=base_kernel, + ) + + if was_compiled: + obj = _unwrap_efc_compiled_obj(artifact.compiled_obj) + disk_cache_set( + disk_fn_cache, + kernel_name, + disk_config_key, + cache_key, + obj, + dev_idx, + device_capability=cuda_ctx.device_capability, + ) + finally: + _restore_max_active_clusters(patched) + + elapsed_us = (time.time_ns() - start_ns) // 1000 + return None, elapsed_us + + +# ── Runtime helpers (imported by generated wrapper code at runtime) ─────────── + + +def _get_scaled_gemm_modes( + scale_type_a: Any | None, + swizzle_type_a: Any | None, + scale_type_b: Any | None, + swizzle_type_b: Any | None, +) -> tuple[Any, Any, Any, Any]: + scale_mode_a, swizzle_mode_a = to_cutlass_scale_mode(scale_type_a, swizzle_type_a) + scale_mode_b, swizzle_mode_b = to_cutlass_scale_mode(scale_type_b, swizzle_type_b) + if any( + mode is None + for mode in (scale_mode_a, swizzle_mode_a, scale_mode_b, swizzle_mode_b) + ): + raise NotImplementedError("Unsupported scale/swizzle mode for scaled GEMM") + return scale_mode_a, swizzle_mode_a, scale_mode_b, swizzle_mode_b + + +def _create_gemm_arguments( + variant_name: str, + input_tensors, + out, + accumulator_type: Any, + *, + scale_mode_a: Any | None = None, + swizzle_mode_a: Any | None = None, + scale_mode_b: Any | None = None, + swizzle_mode_b: Any | None = None, + epilogue: Any | None = None, + local_reduce_out: Any | None = None, + local_reduce_group: int = 0, + local_reduce_axis: int = 1, + local_reduce_type: str = "sum", + local_reduce_source: str = "identity", + local_reduce_feeds_main: bool = False, +): + import cutlass.operators + + has_local_reduce = local_reduce_out is not None or local_reduce_feeds_main + if has_local_reduce and variant_name != "SCALED_GEMM": + raise NotImplementedError( + "NVGEMM local reductions currently require scaled GEMM" + ) + if has_local_reduce and ( + local_reduce_axis not in (0, 1) or local_reduce_group <= 1 + ): + raise NotImplementedError( + "NVGEMM local reductions require an M- or N-axis group greater than 1" + ) + + def with_local_reduce(args): + if not has_local_reduce: + return args + from cutlass.operators.utils.tensor import TensorWrapper + + args.local_reduce_out = ( + TensorWrapper(local_reduce_out) if local_reduce_out is not None else None + ) + args.local_reduce_group = local_reduce_group + args.local_reduce_axis = local_reduce_axis + args.local_reduce_type = local_reduce_type + args.local_reduce_source = local_reduce_source + args.local_reduce_feeds_main = local_reduce_feeds_main + return args + + if epilogue is not None and variant_name == "GROUPED_GEMM": + raise NotImplementedError( + "Epilogue fusion is not yet supported for grouped GEMM" + ) + + match variant_name: + case "GROUPED_GEMM": + a, b, offsets = input_tensors + return cutlass.operators.arguments.GroupedGemmArguments( + a, + b, + out, + accumulator_type=accumulator_type, + offsets=offsets, + ) + + case "SCALED_GEMM": + from cutlass.operators.arguments import ScaledOperand + + a, b, scale_a, scale_b = input_tensors + scaled_a = ScaledOperand(a, scale_a, scale_mode_a, swizzle_mode_a) + scaled_b = ScaledOperand(b, scale_b, scale_mode_b, swizzle_mode_b) + kwargs: dict[str, Any] = {"accumulator_type": accumulator_type} + if epilogue is not None: + kwargs["epilogue"] = epilogue + return with_local_reduce( + cutlass.operators.arguments.GemmArguments( + scaled_a, + scaled_b, + out, + **kwargs, + ) + ) + + case "GEMM": + a, b = input_tensors + kwargs: dict[str, Any] = {"accumulator_type": accumulator_type} + if epilogue is not None: + kwargs["epilogue"] = epilogue + return with_local_reduce( + cutlass.operators.arguments.GemmArguments(a, b, out, **kwargs) + ) + + case _: + raise NotImplementedError(f"Unsupported NVGEMM variant: {variant_name}") + + +def _lookup_gemm_kernel( + kernel_name: str, + *, + epilogue_args: Any | None = None, + epilogue_source: str = "", + args: Any | None = None, + cc: int | None = None, + base_kernel: Any | None = None, +): + from torch._inductor.codegen.nv_universal_gemm.kernel_cache import ( + get_efc_kernel_with_epilogue, + get_kernel_by_name, + get_kernel_by_name_via_args, + ) + + # Best path (subprocess precompile): the caller reconstructed the exact + # operator from metadata passed by the main process (operator_class(metadata), + # ~us), so we skip operator discovery entirely -- no args-filtered query and + # no full manifest. + # Fast path (base_kernel absent): resolve the single named kernel via an + # args-filtered query (~0.05s) instead of building the full manifest (~14s). + fast = args is not None and cc is not None + + if epilogue_args is None: + kernel = base_kernel + # Fast path can miss when the named kernel doesn't support these exact + # args (e.g. a swap_ab kernel selected for the transposed problem while + # the worker holds the original operands); fall back to the manifest. + if kernel is None and fast: + kernel = get_kernel_by_name_via_args(kernel_name, args, cc) + if kernel is None: + kernel = get_kernel_by_name(kernel_name) + if kernel is None: + raise RuntimeError(f"Could not find kernel: {kernel_name}") + return kernel + + if base_kernel is None and fast: + base_kernel = get_kernel_by_name_via_args(kernel_name, args, cc) + kernel = get_efc_kernel_with_epilogue( + kernel_name, + epilogue_args, + epilogue_source=epilogue_source, + base_kernel=base_kernel, + ) + if kernel is None: + raise RuntimeError(f"Could not find EFC kernel: {kernel_name}") + return kernel + + +def _tensor_sig(t): + return (t.shape, t.stride(), t.dtype) + + +def _create_gemm_cache_key( + input_tensors, + out, + *, + has_epilogue: bool = False, + aux_tensors: tuple = (), + epilogue_specialization: tuple = (), +): + cache_key = tuple(s for t in input_tensors for s in _tensor_sig(t)) + cache_key = (*cache_key, *_tensor_sig(out)) + + if has_epilogue: + aux_sig = tuple(_tensor_sig(t) for t in aux_tensors) + return (*cache_key, "epilogue", aux_sig, epilogue_specialization) + return cache_key + + +def _unwrap_efc_compiled_obj(compiled_obj): + """Extract the inner JIT function from an EFC closure for disk serialization.""" + if hasattr(compiled_obj, "__closure__") and compiled_obj.__closure__: + inner = compiled_obj.__closure__[0].cell_contents + if hasattr(inner, "export_to_c"): + return inner + return compiled_obj + + +def _init_efc_jit(kernel, epilogue_args): + """Lightweight EFC JIT init from epilogue args, without a full kernel.compile(). + + EFC.compile() calls analyze_epilogue_with_arguments() then creates the JIT + object. We replicate just those two steps so that disk-cached artifacts can + be rewrapped without recompiling the CuTe DSL kernel. + """ + from cutlass.operators.providers.cutedsl.evt.common_efc import EFC + from cutlass.operators.utils.tensor import TensorWrapper + + efc = kernel.impl.efc + params = [ + e.compile_time_tensor if isinstance(e, TensorWrapper) else e + for e in epilogue_args.parameters + ] + efc.analyze_epilogue_with_arguments(params) + efc.jit = EFC.JIT(efc, efc.epilogue_parameter_names) + + +def _rewrap_efc_compiled_obj(compiled_fn, kernel, epilogue_args=None): + """Reconstruct the EFC wrapped_launch closure from a loaded JIT function. + + When epilogue_args is provided and efc.jit is missing, performs a + lightweight initialization (analyze + JIT creation) so that + disk-cached EFC artifacts can be reused without a full recompile. + Falls back to returning None (triggering recompile) only when + epilogue_args is not available. + """ + if not hasattr(kernel, "impl") or not hasattr(kernel.impl, "efc"): + return compiled_fn + if not hasattr(kernel.impl.efc, "jit"): + if epilogue_args is not None: + _init_efc_jit(kernel, epilogue_args) + else: + return None + + from cutlass.operators.providers.cutedsl.gemm.sm100_static_persistent_efc import ( + Operand as KernelOperand, + TensorWrapper, + ) + + def wrapped_launch(a_tensor, b_tensor, stream, *supplemental_args): + runtime_args = [ + e.runtime_tensor + if isinstance(e, TensorWrapper) + else (e.tensor.runtime_tensor if isinstance(e, KernelOperand) else e) + for e in supplemental_args + ] + # A disk-reloaded artifact is the raw kernel module func: it takes the + # epilogue tensors unpacked (a, b, stream, aux..., out), unlike the + # freshly-JIT-compiled closure which expects pack_arguments(...). All + # callers of _rewrap_efc_compiled_obj load from disk, so pass unpacked. + return compiled_fn(a_tensor, b_tensor, stream, *runtime_args) + + return wrapped_launch + + +def _update_reuse_args_tensors( + variant_name, args, input_tensors, out, epilogue_args, args_kwargs=None +) -> bool: + """Redirect the cached args at this call's runtime tensors. + + A cache hit on ``mem_key`` guarantees identical shapes/strides/dtypes, so + only the data pointers change; mutating ``TensorWrapper._runtime_tensor`` in + place is sufficient and lets us skip the (expensive) _create_gemm_arguments + rebuild. Returns False for GROUPED_GEMM (unsupported), signalling the caller + to use the rebuild path. + """ + if variant_name == "GROUPED_GEMM": + return False + if variant_name == "SCALED_GEMM": + a, b, scale_a, scale_b = input_tensors + args.A.quantized.tensor._runtime_tensor = a + args.A.scale.tensor._runtime_tensor = scale_a + args.B.quantized.tensor._runtime_tensor = b + args.B.scale.tensor._runtime_tensor = scale_b + args.out.tensor._runtime_tensor = out + else: + # GEMM: dense mm and the EFC bias/epilogue addmm path. + a, b = input_tensors + args.A.tensor._runtime_tensor = a + args.B.tensor._runtime_tensor = b + args.out.tensor._runtime_tensor = out + epilogue = getattr(args, "epilogue", None) + if epilogue is not None: + for name, wrapper in epilogue.tensors.items(): + val = epilogue_args.tensors[name] + wrapper._runtime_tensor = getattr(val, "runtime_tensor", val) + local_reduce = getattr(args, "local_reduce_out", None) + if local_reduce is not None: + if args_kwargs is None: + raise AssertionError("expected args_kwargs to be not None") + local_reduce._runtime_tensor = args_kwargs["local_reduce_out"] + return True + + +def _clear_reuse_args_tensors(variant_name, args, epilogue_args): + """Drop the runtime tensors held by cached args after a launch. + + kernel.run enqueues the launch synchronously and reads the pointers during + the call, and the caller keeps the tensors alive, so clearing our cached + references is safe. Required for cudagraph capture, which fails if a cached + object retains a tensor from the graph pool between iterations. + """ + if variant_name == "SCALED_GEMM": + args.A.quantized.tensor._runtime_tensor = None + args.A.scale.tensor._runtime_tensor = None + args.B.quantized.tensor._runtime_tensor = None + args.B.scale.tensor._runtime_tensor = None + args.out.tensor._runtime_tensor = None + else: + args.A.tensor._runtime_tensor = None + args.B.tensor._runtime_tensor = None + args.out.tensor._runtime_tensor = None + epilogue = getattr(args, "epilogue", None) + if epilogue is not None: + for wrapper in epilogue.tensors.values(): + wrapper._runtime_tensor = None + # kernel.run traces the epilogue on first launch, and the trace retains + # the real output/aux tensors in example_inputs (used only for tracing, + # not the launch). Replace them with meta tensors so the cached args + # hold no real storage -- otherwise an intermediate output stays live + # and CUDA graph capture fails. Mirrors _meta_epilogue_metadata. + import torch + + te = getattr(epilogue, "traced_epilogue", None) + example_inputs = getattr(te, "example_inputs", None) if te else None + if example_inputs: + for name, val in example_inputs.items(): + if isinstance(val, torch.Tensor) and val.device.type != "meta": + example_inputs[name] = torch.empty_strided( + val.shape, val.stride(), dtype=val.dtype, device="meta" + ) + local_reduce = getattr(args, "local_reduce_out", None) + if local_reduce is not None: + local_reduce._runtime_tensor = None + + +def _nvgemm_run( + variant_name: str, + kernel_name: str, + input_tensors: tuple, + out, + accumulator_type, + compiled_cache: dict, + disk_fn_cache: dict, + module_path: str, + disk_config_key: tuple, + *, + stream=None, + workspace=None, + variant_kwargs: dict | None = None, + epilogue_args=None, + epilogue_source: str = "", + has_epilogue: bool = False, + aux_tensors: tuple = (), + swap_ab: bool = False, +): + if swap_ab and len(input_tensors) >= 2: + a, b = input_tensors[0], input_tensors[1] + if len(input_tensors) >= 4: + sa, sb = input_tensors[2], input_tensors[3] + input_tensors = (b.t(), a.t(), sb, sa) + input_tensors[4:] + else: + input_tensors = (b.t(), a.t()) + input_tensors[2:] + # Swapped GEMM computes (N, M) = out.t(); write it zero-copy into a + # transposed (column-major) view of the real (M, N) output -- no temp + # buffer / copy (the kernel handles column-major C). + out = out.t() + from cutlass.operators.artifact import CompiledArtifact + + from torch._inductor.runtime.cutedsl_cache import disk_cache_get, disk_cache_set + + epilogue_specialization = tuple( + (key, variant_kwargs[key]) + for key in ("local_reduce_type", "local_reduce_source") + if variant_kwargs is not None and key in variant_kwargs + ) + cache_key = _create_gemm_cache_key( + input_tensors, + out, + has_epilogue=has_epilogue, + aux_tensors=aux_tensors, + epilogue_specialization=epilogue_specialization, + ) + dev_idx = input_tensors[0].device.index or 0 + mem_key = (cache_key, dev_idx) + + if mem_key in compiled_cache: + artifact = compiled_cache[mem_key] + # Fast path: reuse the previously-built args, redirecting only the + # runtime tensor pointers. Skips _create_gemm_arguments, whose cost + # (get_type_hints + deepcopy + full epilogue/layout reprocessing) + # depends solely on shapes/layout -- fixed for a given mem_key. + reuse = getattr(artifact, "_nvgemm_reuse", None) + if reuse is not None: + args, kernel, reuse_lock = reuse + # The cached args are shared mutable state. Serialize the + # redirect->launch->clear so concurrent launches on the same cached + # artifact (e.g. two graph executions sharing this kernel) don't + # stomp each other's runtime tensor pointers. + with reuse_lock: + if _update_reuse_args_tensors( + variant_name, + args, + input_tensors, + out, + epilogue_args, + variant_kwargs, + ): + try: + kernel.run( + args, + artifact, + stream=stream, + workspace=workspace, + assume_supported_args=True, + ) + finally: + _clear_reuse_args_tensors(variant_name, args, epilogue_args) + return + # No reusable args (e.g. artifact loaded from disk by a subprocess + # precompile): build them once, then attach below for future calls. + args = _create_gemm_arguments( + variant_name, + input_tensors, + out, + accumulator_type, + epilogue=epilogue_args, + **(variant_kwargs or {}), + ) + kernel = artifact.operator_obj + else: + + def disk_fallback(kernel): + compiled_fn = disk_cache_get( + disk_fn_cache, + module_path, + disk_config_key, + cache_key, + dev_idx, + ) + if compiled_fn is not None: + compiled_fn = _rewrap_efc_compiled_obj( + compiled_fn, + kernel, + epilogue_args=epilogue_args, + ) + if compiled_fn is not None: + return CompiledArtifact( + compiled_fn, kernel, _current_target_sm(dev_idx) + ) + return None + + artifact, args, kernel, was_compiled = _compile_nvgemm( + variant_name, + input_tensors, + out, + accumulator_type, + kernel_name=kernel_name, + args_kwargs=variant_kwargs, + epilogue_args=epilogue_args, + epilogue_source=epilogue_source, + fallback_fn=disk_fallback, + cc=_current_target_sm(dev_idx).cc, + ) + + if was_compiled: + disk_cache_set( + disk_fn_cache, + module_path, + disk_config_key, + cache_key, + _unwrap_efc_compiled_obj(artifact.compiled_obj), + dev_idx, + ) + + compiled_cache[mem_key] = artifact + + # Attach the built args for reuse on subsequent calls (skipped for + # GROUPED_GEMM, where _update_reuse_args_tensors returns False). This runs + # for both the disk-loaded rebuild branch and the fresh-compile branch. + reuse_supported = _update_reuse_args_tensors( + variant_name, + args, + input_tensors, + out, + epilogue_args, + variant_kwargs, + ) + if reuse_supported: + # Publish and launch under the lock so a concurrent reuse-path caller + # that picks up these args blocks until this launch has cleared them. + reuse_lock = threading.Lock() + with reuse_lock: + artifact._nvgemm_reuse = (args, kernel, reuse_lock) + try: + kernel.run( + args, + artifact, + stream=stream, + workspace=workspace, + assume_supported_args=True, + ) + finally: + _clear_reuse_args_tensors(variant_name, args, epilogue_args) + else: + kernel.run( + args, + artifact, + stream=stream, + workspace=workspace, + assume_supported_args=True, + ) + + +# Patch both the canonical definition (integration_utils.mma) for callers that +# reference it module-qualified, and each gemm module's namespace for callers +# that imported the bare name. _patch_max_active_clusters skips any without it. +_MAX_ACTIVE_CLUSTERS_MODULES = [ + "cutlass.operators.providers.cutedsl.integration_utils.mma", + "cutlass.operators.providers.cutedsl.gemm.sm100_persistent", + "cutlass.operators.providers.cutedsl.gemm.sm100_persistent_preferred_cluster", + "cutlass.operators.providers.cutedsl.gemm.sm100_static_persistent_efc", + "cutlass.operators.providers.cutedsl.gemm.sm100_dense_blockscaled_static_persistent", + "cutlass.operators.providers.cutedsl.gemm.sm100_contiguous_offset_2d3d_dense_gemm", + "cutlass.operators.providers.cutedsl.gemm.sm100_mixed_input", + "cutlass.operators.providers.cutedsl.gemm.sm90_static_persistent", +] + + +def _nvgemm_precompile( + precompile_shapes: dict, + precompile_strides: dict, + precompile_dtypes: dict, + device_index: int = 0, + device_capability: tuple | None = None, + *, + variant_name: str, + kernel_name: str, + accumulator_type, + compiled_cache: dict, + disk_fn_cache: dict, + module_path: str, + disk_config_key: tuple, + input_param_names: list[str], + variant_kwargs: dict | None = None, + max_active_clusters: int | None = None, +): + """Precompile an NVGEMM kernel in a subprocess for parallel compilation. + + Precompiles only the base (non-EFC) kernel. EFC kernels produce + closure-wrapped artifacts that can't be serialized to disk cache. + """ + import torch + from torch._inductor.runtime.cutedsl_cache import disk_cache_set + from torch._subclasses.fake_tensor import FakeTensorMode + + if max_active_clusters is None: + return + + # cutlass.operators queries device occupancy while compiling. In async-compile + # workers forked from a CUDA-initialized parent, skip precompile. + if torch.cuda._is_in_bad_fork(): + return + + device = f"cuda:{device_index}" + with FakeTensorMode(): + tensors = {} + for name in [*input_param_names, "output"]: + tensors[name] = torch.empty_strided( + tuple(precompile_shapes[name]), + tuple(precompile_strides[name]), + device=device, + dtype=getattr(torch, precompile_dtypes[name]), + ) + + input_tensors = tuple(tensors[n] for n in input_param_names) + out = tensors["output"] + + patched = _patch_max_active_clusters(max_active_clusters) + try: + cache_key = _create_gemm_cache_key(input_tensors, out) + mem_key = (cache_key, device_index) + if mem_key not in compiled_cache: + artifact, _, _, _ = _compile_nvgemm( + variant_name, + input_tensors, + out, + accumulator_type, + kernel_name=kernel_name, + args_kwargs=variant_kwargs, + ) + disk_cache_set( + disk_fn_cache, + module_path, + disk_config_key, + cache_key, + artifact.compiled_obj, + device_index, + device_capability=device_capability, + ) + compiled_cache[mem_key] = artifact + finally: + _restore_max_active_clusters(patched) + + +# ── Kernel wrapper (returned by async_compile.nv_universal_gemm) ───────────── + + +class NVUniversalGemmKernelWrapper: + """Wrapper to provide .run() interface for NVIDIA Universal GEMM kernels.""" + + def __init__(self, kernel_fn, kernel_path: str | None = None): + self.kernel_fn = kernel_fn + self.kernel_path = kernel_path + + def run(self, *args, stream=None, **kwargs): + """Execute the NVIDIA Universal GEMM kernel.""" + return self.kernel_fn(*args, stream=stream, **kwargs) + + +# ── Kernel codegen class ───────────────────────────────────────────────────── + + +# Module-level bias-add epilogue for benchmark tracing. Must be a real +# (introspectable) function -- EpilogueArguments parses its source via +# inspect.getsource -- and must contain NO string literals (the AST tracer +# treats any constant as an immediate). The param name is deliberately not +# ``C`` (see _build_bias_epilogue) so a 1D bias routes to the row-broadcast impl. +def _nvgemm_bias_add_epilogue(accum, bias): + D = accum + bias + return D + + +def _build_bias_epilogue( + bias_name: str, out_name: str +) -> tuple[str, list[str], list[str], dict[str, str]]: + """Build the epilogue fields for an addmm bias-add (``accum + bias``). + + Uses the bias buffer name as the epilogue-fn parameter, matching + CutlassEVTCodegen's convention. This deliberately avoids the name ``C``: + cutlass.operators' LoadSrcImpl claims any epilogue param named ``C`` whose + shape equals the output (ignoring stride), which shadows the row/column + broadcast impls and silently mis-reads a broadcast (1D) bias. + """ + epilogue_fn_code = ( + f"def _epilogue_fn(accum, {bias_name}):\n" + f" D = accum + {bias_name}\n" + f" return D" + ) + epilogue_reads = [bias_name] + epilogue_writes: list[str] = [] + epilogue_var_renames = {bias_name: bias_name, "D": out_name} + return epilogue_fn_code, epilogue_reads, epilogue_writes, epilogue_var_renames + + +def _compose_bias_into_epilogue( + epilogue_fn_code: str, + epilogue_reads: list[str], + epilogue_var_renames: dict[str, Any], + bias_name: str, +) -> tuple[str, list[str], dict[str, Any]]: + """Inject an addmm bias-add into a scheduler-fused epilogue. + + The EFC kernel's ``accum`` is the raw ``A @ B``; a fused pointwise epilogue + written by CutlassEVTCodegen assumes its ``accum`` is the addmm output + (``A @ B + bias``). We keep ``accum`` as the raw accumulator (required by + the cutlass epilogue tracer) and rewrite the fused body to read a new + ``biased = accum + bias`` value instead, adding ``bias`` as an aux input. + """ + lines = epilogue_fn_code.splitlines() + def_line = lines[0] + body = lines[1:] + # Add bias as the 2nd parameter (after the required `accum`), unless the + # fused epilogue already reads the same buffer -- then it is already a + # parameter and re-adding it would emit `def fn(accum, b, b)` (SyntaxError). + if bias_name not in epilogue_reads: + def_line = def_line.replace("(accum", f"(accum, {bias_name}", 1) + # Rewrite fused-body references to the accumulator to the biased value. + rewritten = [re.sub(r"\baccum\b", "biased", bl) for bl in body] + composed = "\n".join([def_line, f" biased = accum + {bias_name}", *rewritten]) + reads = list(epilogue_reads) + if bias_name not in reads: + reads.append(bias_name) + renames = dict(epilogue_var_renames) + renames[bias_name] = bias_name + return composed, reads, renames + + +class NVUniversalGemmKernel(Kernel): + """ + Kernel implementation for NVIDIA Universal GEMM. + + Generates a thin Python wrapper that delegates to runtime helpers + (_nvgemm_run, _nvgemm_precompile) for the actual GEMM execution and + compilation logic. + """ + + def __init__( + self, + kernel_name: str, + input_nodes: list[Buffer], + output_node: Buffer, + kernel_metadata: dict[str, Any], + accumulator_type: Any, + variant: GemmVariant, + 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, + 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, + swap_ab: bool = False, + bias_node: Buffer | None = None, + ) -> None: + super().__init__() + self.kernel_name = kernel_name + self.input_nodes = input_nodes + self.output_node = output_node + self.kernel_metadata = kernel_metadata + self.accumulator_type = accumulator_type + 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.epilogue_fn_code = epilogue_fn_code + self.epilogue_reads = epilogue_reads or [] + self.epilogue_writes = epilogue_writes or [] + self.epilogue_var_renames = epilogue_var_renames or {} + self.local_reduce = local_reduce + self.swap_ab = swap_ab + + # An addmm bias baked into the choice becomes a bias-add epilogue. With + # no scheduler-fused epilogue it's a standalone bias-add; when the + # scheduler also fuses pointwise ops, compose the bias-add into them so + # the fused epilogue sees A@B + bias (matches Triton's epilogue fusion). + if bias_node is not None: + if not self.epilogue_fn_code: + ( + self.epilogue_fn_code, + self.epilogue_reads, + self.epilogue_writes, + self.epilogue_var_renames, + ) = _build_bias_epilogue(bias_node.get_name(), output_node.get_name()) + else: + ( + self.epilogue_fn_code, + self.epilogue_reads, + self.epilogue_var_renames, + ) = _compose_bias_into_epilogue( + self.epilogue_fn_code, + self.epilogue_reads, + self.epilogue_var_renames, + bias_node.get_name(), + ) + + self._template_input_args: list[tuple[str, Buffer]] = [] + + for i, input_node in enumerate(input_nodes): + param_name = f"in_ptr{i}" + self._template_input_args.append((param_name, input_node)) + + def render(self) -> str: + """Render the Python source for the NVGEMM kernel wrapper.""" + kernel_name_str = self.kernel_metadata["kernel_name"] + acc_dtype_str = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get( + self.accumulator_type, "cutlass.Float32" + ) + + input_tensor_names = [f"in_ptr{i}" for i, _ in enumerate(self.input_nodes)] + output_buffers = self._ordered_output_buffers() + input_params = list(input_tensor_names) + input_params.extend(f"out_ptr{i}" for i in range(len(output_buffers))) + input_params.extend(self.epilogue_reads) + if self.workspace_size > 0: + input_params.append("workspace") + input_params.append("stream=None") + params_str = ", ".join(input_params) + + if len(input_tensor_names) == 1: + input_tensors_expr = f"({input_tensor_names[0]},)" + else: + input_tensors_expr = f"({', '.join(input_tensor_names)})" + + workspace_arg = "workspace" if self.workspace_size > 0 else "None" + has_epilogue = bool(self.epilogue_fn_code) or self.local_reduce is not None + + # Build variant_kwargs dict expression for SCALED_GEMM + variant_kwargs_expr = "None" + variant_extra_imports = "" + if self.variant.name == "SCALED_GEMM": + sma, swza, smb, swzb = _get_scaled_gemm_modes( + self.scale_type_a, + self.swizzle_type_a, + self.scale_type_b, + self.swizzle_type_b, + ) + variant_extra_imports = ( + "from cutlass.operators import ScaleMode, ScaleSwizzleMode" + ) + variant_kwargs_expr = ( + "{" + f'"scale_mode_a": ScaleMode.{sma.name}, ' + f'"swizzle_mode_a": ScaleSwizzleMode.{swza.name}, ' + f'"scale_mode_b": ScaleMode.{smb.name}, ' + f'"swizzle_mode_b": ScaleSwizzleMode.{swzb.name}' + "}" + ) + + code = IndentedBuffer() + + # -- Module-level imports and constants -- + code.writeline("import cutlass") + code.writeline( + "from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import (" + ) + with code.indent(): + code.writeline("_make_disk_config_key,") + code.writeline("_nvgemm_run,") + code.writeline("_nvgemm_precompile,") + code.writeline(")") + code.writeline("from torch._inductor.utils import _ensure_fp4_dtype_registered") + code.writeline("_ensure_fp4_dtype_registered()") + if variant_extra_imports: + code.writeline(variant_extra_imports) + if has_epilogue: + code.writeline("from cutlass.operators.arguments import EpilogueArguments") + code.writeline("") + + # -- Epilogue function definition (must be module-level for cutlass.operators) -- + epilogue_fn_code = self.epilogue_fn_code + if has_epilogue and epilogue_fn_code is not None: + epilogue_source_hash = hashlib.sha256(epilogue_fn_code.encode()).hexdigest() + code.writeline(f'_EPILOGUE_FN_SOURCE = "{epilogue_source_hash}"') + # Pass the epilogue to cutlass.operators as a SOURCE STRING, not a + # callable: EpilogueArguments traces a string directly, whereas a + # callable triggers inspect.getsource() at every kernel launch -- + # which fails ("could not get source code") for generated modules + # loaded from the subprocess PyCodeCache. + code.writeline(f"_EPILOGUE_FN_SRC = {epilogue_fn_code!r}") + code.writeline("") + + # -- Module-level state -- + code.writeline(f"_KERNEL_NAME = {kernel_name_str!r}") + disk_key_args = ", ".join( + repr(str(v)) + for v in ( + kernel_name_str, + self.variant.name, + self.accumulator_type, + self.scale_type_a, + self.scale_type_b, + self.swizzle_type_a, + self.swizzle_type_b, + ) + ) + code.writeline( + f"_DISK_CACHE_CONFIG_KEY = _make_disk_config_key({disk_key_args})" + ) + code.writeline("_compiled_cache = {}") + code.writeline("_disk_fn_cache = {}") + code.writeline(f"_VARIANT_KWARGS = {variant_kwargs_expr}") + code.writeline(f"_ACC_TYPE = {acc_dtype_str}") + input_param_names_repr = repr(input_tensor_names) + code.writeline(f"_INPUT_PARAM_NAMES = {input_param_names_repr}") + code.writeline("") + + # -- Main function -- + code.writeline(f"def {self.kernel_name}_main({params_str}):") + with code.indent(): + # Build epilogue args if needed (user-specific variable names) + epi_args_expr = "None" + epi_source_expr = '""' + aux_tensors: list[str] = [] + if self.epilogue_fn_code: + epilogue_kwargs = self._render_epilogue_kwargs() + epi_kwargs_str = "epilogue_fn=_EPILOGUE_FN_SRC" + if epilogue_kwargs: + epi_kwargs_str += f", {epilogue_kwargs}" + code.writeline(f"epi_args = EpilogueArguments({epi_kwargs_str})") + epi_args_expr = "epi_args" + epi_source_expr = "_EPILOGUE_FN_SOURCE" + aux_tensors.extend(self.epilogue_reads) + + run_variant_kwargs = "_VARIANT_KWARGS" + if self.local_reduce is not None: + reduction = self.local_reduce + feed_main = reduction.feeds_main + reduce_ptr = ( + "None" + if reduction.reduction_output is None + else f"out_ptr{output_buffers.index(reduction.reduction_output)}" + ) + run_variant_kwargs = ( + "_VARIANT_KWARGS | {" + f"'local_reduce_out': {reduce_ptr}, " + f"'local_reduce_group': {reduction.group}, " + f"'local_reduce_axis': {reduction.axis}, " + f"'local_reduce_type': {reduction.reduction_type!r}, " + f"'local_reduce_source': {reduction.source_type!r}" + f", 'local_reduce_feeds_main': {feed_main!r}" + "}" + ) + if not feed_main: + aux_tensors.append(reduce_ptr) + + aux_tensors_expr = f"({', '.join(aux_tensors)},)" if aux_tensors else "()" + + code.writeline("_nvgemm_run(") + with code.indent(): + code.writeline(f'"{self.variant.name}", _KERNEL_NAME,') + code.writeline(f"{input_tensors_expr}, out_ptr0, _ACC_TYPE,") + code.writeline( + "_compiled_cache, _disk_fn_cache, __file__, _DISK_CACHE_CONFIG_KEY," + ) + code.writeline(f"stream=stream, workspace={workspace_arg},") + code.writeline(f"variant_kwargs={run_variant_kwargs},") + code.writeline(f"epilogue_args={epi_args_expr},") + code.writeline(f"epilogue_source={epi_source_expr},") + code.writeline(f"has_epilogue={has_epilogue},") + code.writeline(f"aux_tensors={aux_tensors_expr},") + if self.swap_ab: + code.writeline("swap_ab=True,") + code.writeline(")") + + # -- Precompile hook -- + code.writeline("") + code.writeline( + f"def {self.kernel_name}_precompile(" + "precompile_shapes, precompile_strides, precompile_dtypes, " + "device_index=0, device_capability=None, **kwargs):" + ) + with code.indent(): + code.writeline("_nvgemm_precompile(") + with code.indent(): + code.writeline( + "precompile_shapes, precompile_strides, precompile_dtypes," + ) + code.writeline("device_index, device_capability,") + code.writeline(f'variant_name="{self.variant.name}",') + code.writeline("kernel_name=_KERNEL_NAME,") + code.writeline("accumulator_type=_ACC_TYPE,") + code.writeline( + "compiled_cache=_compiled_cache, disk_fn_cache=_disk_fn_cache," + ) + code.writeline( + "module_path=__file__, disk_config_key=_DISK_CACHE_CONFIG_KEY," + ) + code.writeline("input_param_names=_INPUT_PARAM_NAMES,") + code.writeline("variant_kwargs=_VARIANT_KWARGS,") + code.writeline("max_active_clusters=kwargs.get('max_active_clusters'),") + code.writeline(")") + + return code.getvalue() + + def _ordered_output_buffers(self) -> list[str]: + """Graph-output buffer names in out_ptr order. + + out_ptr0 is the primary GEMM output (the epilogue's `D` store, passed as + the kernel's `out`). Additional stores -- a multi-store epilogue where the + GEMM output feeds more than one graph output -- follow in epilogue_writes + order as out_ptr1, out_ptr2, ... + """ + if not self.epilogue_writes: + primary_output = ( + self.local_reduce.primary_output + if self.local_reduce is not None + else self.output_node.get_name() + ) + ordered = [primary_output] + if self.local_reduce is not None: + ordered.extend(self.local_reduce.auxiliary_outputs) + return ordered + d_buf = (self.epilogue_var_renames or {}).get("D") + ordered: list[str] = [] + if d_buf is not None: + ordered.append(d_buf) + for w in self.epilogue_writes: + if w != d_buf and w not in ordered: + ordered.append(w) + if self.local_reduce is not None: + ordered.extend( + output + for output in self.local_reduce.auxiliary_outputs + if output not in ordered + ) + return ordered + + def _render_epilogue_kwargs(self) -> str: + """Render kwargs for the EpilogueArguments constructor. + + Each epilogue variable maps to either an output pointer -- the `D` store + and any additional multi-store outputs become out_ptr0, out_ptr1, ... in + _ordered_output_buffers order -- or, for a read, the aux input buffer. + `accum` is the kernel-supplied accumulator and is not a kwarg. + """ + out_ptr_of = { + buf: f"out_ptr{i}" for i, buf in enumerate(self._ordered_output_buffers()) + } + kwargs_parts = [] + for var_name, buffer_name in self.epilogue_var_renames.items(): + if var_name == _ACCUMULATOR_ARG_NAME: + continue + if buffer_name in out_ptr_of: + kwargs_parts.append(f"{var_name}={out_ptr_of[buffer_name]}") + else: + kwargs_parts.append(f"{var_name}={buffer_name}") + return ", ".join(kwargs_parts) + + def _get_reinterpret_view(self, node) -> ReinterpretView | None: + """Extract or convert to ReinterpretView from a node, handling all views.""" + while isinstance(node, MutableBox): + node = node.data + if isinstance(node, BaseView): + return ExternKernel.convert_to_reinterpret_view(node) + return None + + def call_kernel(self, name: str, node=None): + """ + Generate the kernel call in the wrapper code. + + Similar to CuteDSLTemplateKernel.call_kernel but simplified for NVIDIA Universal GEMM. + Includes epilogue input tensors when epilogue fusion is enabled. + """ + wrapper = V.graph.wrapper_code + + if self.local_reduce is not None: + primary_name = self.local_reduce.primary_output + V.graph.removed_buffers.discard(primary_name) + primary_output = V.graph.get_buffer(primary_name) + wrapper.codegen_allocation( + primary_output + if isinstance(primary_output, Buffer) + else self.output_node + ) + + call_args: list[str] = [] + arg_types: list[Any] = [] + raw_args: list[Buffer | ReinterpretView | None] = [] + raw_keys: list[str | None] = [] + + for param_name, input_node in self._template_input_args: + reinterpret_view = self._get_reinterpret_view(input_node) + if reinterpret_view is not None: + call_args.append(reinterpret_view.codegen_reference()) + # Pass the ReinterpretView as raw_arg so autotune_at_compile_time + # can use it to generate example tensors + raw_args.append(reinterpret_view) + else: + call_args.append(input_node.get_name()) + raw_args.append(input_node) + arg_types.append(V.graph.get_dtype(input_node.get_name())) + raw_keys.append(param_name) + + # The kernel writes the epilogue's output store(s), not the GEMM buffer + # (which is removed via removed_buffers aliasing). out_ptr0 is the primary + # (`D`) output; a multi-store epilogue adds out_ptr1, ... in order. + for i, output_name in enumerate(self._ordered_output_buffers()): + call_args.append(output_name) + arg_types.append(V.graph.get_dtype(output_name)) + raw_args.append(None) # Output buffer is findable by name + raw_keys.append(f"out_ptr{i}") + + for read_name in self.epilogue_reads: + call_args.append(read_name) + arg_types.append(V.graph.get_dtype(read_name)) + buf = V.graph.get_buffer(read_name) + if buf is None: + # Epilogue may read model parameters/inputs (e.g. bias) that are + # graph inputs rather than computed buffers. + buf = V.graph.graph_inputs.get(read_name) + # pyrefly: ignore [bad-argument-type] + raw_args.append(buf) + raw_keys.append(read_name) + + # Allocate workspace if needed + ws: WorkspaceArg | None = None + if self.workspace_size > 0: + ws = WorkspaceArg( + count=self.workspace_size, + device=V.graph.get_current_device_or_throw(), + zero_mode=WorkspaceZeroMode.UNINITIALIZED, + outer_name=WorkspaceArg.unique_name(), + ) + wrapper.generate_workspace_allocation(ws) + call_args.append(ws.outer_name) + arg_types.append(ws.dtype) + raw_args.append(None) + raw_keys.append(None) + + wrapper.generate_kernel_call( + name, + call_args, + triton=True, + arg_types=arg_types, + raw_args=raw_args, + raw_keys=raw_keys, + ) + + # Deallocate workspace after kernel call + if ws is not None: + wrapper.generate_workspace_deallocation(ws) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_scheduling.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_scheduling.py new file mode 100644 index 0000000000000000000000000000000000000000..16f2094cd8d6d362e95064c12b6b57b61c81c45d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_scheduling.py @@ -0,0 +1,1137 @@ +# mypy: allow-untyped-defs +""" +NVIDIA Universal GEMM scheduling for PyTorch Inductor. +""" + +import dataclasses +import hashlib +import logging +from collections.abc import Sequence +from typing import Any, cast + +from torch._inductor.utils import ( + get_fused_kernel_name, + get_kernel_metadata, + Placeholder, +) +from torch.utils._ordered_set import OrderedSet + +from ... import config +from ...codecache import code_hash, get_path +from ...ir import ( + Buffer, + ComputedBuffer, + Layout, + MultiTemplateBuffer, + NVUniversalGemmBuffer, + Pointwise, + Reduction, +) +from ...kernel.gemm_epilogue import GemmReductionConfig, GemmReductionPlan +from ...kernel.loop_ir_cutedsl_codegen import LoopIRCuteDSLCodegen +from ...kernel.loop_ir_epilogue_lowering import ( + centered_mean_consumer_type_unrolled_ir, + GemmEpilogueIRAnalysis, + grouped_reduction_ir, + single_source_affine_ir, +) +from ...scheduler import ( + BaseSchedulerNode, + BaseScheduling, + FusedSchedulerNode, + SchedulerNode, +) +from ...virtualized import V +from ..common import BackendFeature, IndentedBuffer +from ..cutlass.python_evt import _ACCUMULATOR_ARG_NAME, CutlassEVTCodegen +from .nv_universal_gemm import NVUniversalGemmCaller + + +log = logging.getLogger(__name__) + +MAIN_SUFFIX = "main" +_BENCHMARK_KERNEL_PREFIX = "nv_gemm_" +EPILOGUE_FN_NAME = "_epilogue_fn" + + +@dataclasses.dataclass(frozen=True) +class NVGemmEpiloguePlan: + nodes: tuple[BaseSchedulerNode, ...] + reductions: tuple[GemmReductionConfig, ...] + reduction_nodes: tuple[BaseSchedulerNode, ...] + candidate_reduction: GemmReductionConfig | None = None + feed_main: GemmReductionConfig | None = None + + @property + def evt_nodes(self) -> list[BaseSchedulerNode]: + owned = OrderedSet(self.reduction_nodes) + return [node for node in self.nodes if node not in owned] + + +class NVUniversalGemmScheduling(BaseScheduling): + """ + Scheduling implementation for NVIDIA Universal GEMM kernels. + + This class is intended to be used in combination with other schedulers, + and delegated to by CUDACombinedScheduling. + """ + + @classmethod + def get_backend_features(cls, device) -> OrderedSet[BackendFeature]: + return OrderedSet() + + @staticmethod + def _is_nvgemm_ir_buffer(ir_node: Any) -> bool: + """Return True if `ir_node` is an NVGEMM buffer or an MTB resolving to one. + + Honors finalize_as_*_caller's swap (a MultiTemplateBuffer whose render + kind is "triton" is no longer NVGEMM, even if the autotune winner was). + Falls back to the autotune winner only when no swap has happened. + """ + if isinstance(ir_node, NVUniversalGemmBuffer): + return True + if not isinstance(ir_node, MultiTemplateBuffer): + return False + if ir_node._render_kind == "triton": + return False + if ir_node._render_kind == "nvgemm": + return True + # Fast path: avoid forcing autotune just to answer this query. + if not any(isinstance(c, NVUniversalGemmCaller) for c in ir_node._choices): + return False + try: + min_choice, _ = ir_node.get_min_choice() + return isinstance(min_choice, NVUniversalGemmCaller) + except (RuntimeError, ValueError): + return False + + @staticmethod + def is_nv_universal_gemm_template(node: BaseSchedulerNode) -> bool: + """Check if a node is an NVGEMM template SchedulerNode.""" + if not isinstance(node, SchedulerNode): + return False + return NVUniversalGemmScheduling._is_nvgemm_ir_buffer(node.node) + + @staticmethod + def _best_nvgemm_choice( + ir_node: MultiTemplateBuffer, + require_epilogue_fusion: bool = False, + ) -> NVUniversalGemmCaller: + """Find the best NVUniversalGemmCaller from an MTB's choice timings.""" + choice_timings = ir_node.choice_timings() + best: NVUniversalGemmCaller | None = None + best_time = float("inf") + for choice, timing in choice_timings.items(): + if not isinstance(choice, NVUniversalGemmCaller): + continue + if require_epilogue_fusion and not choice.supports_epilogue_fusion: + continue + if best is None or timing < best_time: + best_time = timing + best = choice + if best is None: + kind = "EFC kernel" if require_epilogue_fusion else "NVUniversalGemmCaller" + raise RuntimeError(f"No {kind} found in choices") + return best + + @staticmethod + def get_nv_gemm_buffer_from_node( + node: BaseSchedulerNode, require_epilogue_fusion: bool = False + ) -> NVUniversalGemmBuffer: + """Extract NVUniversalGemmBuffer from node (direct or via MultiTemplateBuffer).""" + if not isinstance(node, SchedulerNode): + raise AssertionError(f"expected SchedulerNode, got {type(node)}") + ir_node = node.node + + if isinstance(ir_node, NVUniversalGemmBuffer): + return ir_node + elif isinstance(ir_node, MultiTemplateBuffer): + # Honor an explicit swap/finalize -- the fusion benchmark loop swaps + # in each EFC choice one at a time and must not re-select from timings. + if isinstance(ir_node._render_caller, NVUniversalGemmCaller) and ( + not require_epilogue_fusion + or ir_node._render_caller.supports_epilogue_fusion + ): + selected_choice = ir_node._render_caller + elif require_epilogue_fusion: + selected_choice = NVUniversalGemmScheduling._best_nvgemm_choice( + ir_node, require_epilogue_fusion=True + ) + else: + min_choice, _ = ir_node.get_min_choice() + if isinstance(min_choice, NVUniversalGemmCaller): + selected_choice = min_choice + else: + selected_choice = NVUniversalGemmScheduling._best_nvgemm_choice( + ir_node + ) + tensor_box = selected_choice.output_node() + # pyrefly: ignore [missing-attribute] + return cast(NVUniversalGemmBuffer, tensor_box.data.data) + + raise TypeError( + f"Expected NVUniversalGemmBuffer or MultiTemplateBuffer, got {type(ir_node).__name__}" + ) + + @staticmethod + def is_nv_universal_gemm_fused_template(node: BaseSchedulerNode) -> bool: + """Check if a node is a fused NVIDIA Universal GEMM template.""" + if not isinstance(node, FusedSchedulerNode): + return False + return NVUniversalGemmScheduling._is_nvgemm_ir_buffer(node.get_template_node()) + + def can_fuse_vertical( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + if self.is_nv_universal_gemm_template(node1): + return self._can_fuse_epilogue_impl( + cast(SchedulerNode, node1), + [], + node2, + ) + elif self.is_nv_universal_gemm_fused_template(node1): + fnode1 = cast(FusedSchedulerNode, node1) + template_snode = next( + (n for n in fnode1.snodes if self.is_nv_universal_gemm_template(n)), + None, + ) + if template_snode is None: + return False + return self._can_fuse_epilogue_impl( + cast(SchedulerNode, template_snode), + self._unwrap_epilogue_nodes(fnode1), + node2, + ) + return False + + def _unwrap_epilogue_nodes( + self, fused_node: FusedSchedulerNode + ) -> list[BaseSchedulerNode]: + """Extract epilogue nodes from a fused node.""" + epilogue_nodes = [] + for node in fused_node.snodes: + if not self.is_nv_universal_gemm_template(node): + epilogue_nodes.append(node) + return epilogue_nodes + + @classmethod + def _grouped_reduce_config( + cls, gemm_node: Buffer, scheduler_node: BaseSchedulerNode + ) -> GemmReductionConfig | None: + nodes = scheduler_node.get_nodes() + if len(nodes) not in (1, 2): + return None + buffers = [snode.node for snode in nodes] + if not all(isinstance(buffer, ComputedBuffer) for buffer in buffers): + return None + buffers = [cast(ComputedBuffer, buffer) for buffer in buffers] + node = buffers[0] + access_node = scheduler_node + output_name = node.get_name() + if len(node.data.ranges) != 2 or len(gemm_node.get_size()) != 2: + return None + try: + m, n = (V.graph.sizevars.optimization_hint(v) for v in gemm_node.get_size()) + out_m, out_n = ( + V.graph.sizevars.optimization_hint(v) for v in node.data.ranges + ) + except Exception: + return None + + if isinstance(node.data, Reduction): + reduction = node.data + if len(reduction.reduction_ranges) != 1: + return None + group = V.graph.sizevars.optimization_hint(reduction.reduction_ranges[0]) + if m == out_m and n % group == 0 and out_n == n // group: + axis = 1 + expected_strides = [n, group, 1] + max_group = n + elif n == out_n and m % group == 0 and out_m == m // group: + axis = 0 + expected_strides = [group * n, 1, n] + max_group = 16 + else: + return None + elif isinstance(node.data, Pointwise): + if n != out_n or out_m <= 0 or m % out_m != 0: + return None + group = m // out_m + axis = 0 + max_group = 16 + expected_strides = [group * n, 1] + else: + return None + if group <= 1 or group > max_group: + return None + + store = GemmEpilogueIRAnalysis.store_from_buffer(node) + classified = ( + grouped_reduction_ir( + store, + gemm_node.get_name(), + group, + gemm_node.get_dtype(), + ) + if store is not None + else None + ) + if classified is None: + return None + reduction_type, source_type = classified + if reduction_type not in ( + "sum", + "mean", + "prod", + "max", + "min", + ) or source_type not in ("identity", "square"): + return None + if ( + isinstance(node.data, Reduction) + and node.data.reduction_type != reduction_type + ): + return None + if len(buffers) == 2: + finalizer = buffers[1] + finalizer_store = GemmEpilogueIRAnalysis.store_from_buffer(finalizer) + finalizer_reads = list(nodes[1].read_writes.reads) + if ( + reduction_type != "sum" + or not isinstance(node.data, Reduction) + or not isinstance(finalizer.data, Pointwise) + or not finalizer_reads + or any(read.name != node.get_name() for read in finalizer_reads) + or not V.graph.sizevars.statically_known_list_equals( + node.get_size(), finalizer.get_size() + ) + or finalizer_store is None + or single_source_affine_ir(finalizer_store, node.get_name()) + != (1.0 / group, 0.0) + ): + return None + reduction_type = "mean" + access_node = nodes[0] + output_name = finalizer.get_name() + + reads = list(access_node.read_writes.reads) + if not reads or any(read.name != gemm_node.get_name() for read in reads): + return None + range_vars = access_node.read_writes.range_vars + if range_vars is None: + return None + if not range_vars: + return GemmReductionConfig( + output_name, group, axis, reduction_type, source_type + ) + if isinstance(node.data, Reduction): + if len(reads) != 1: + return None + strides = V.graph.sizevars.stride_vars(reads[0].index, range_vars) + if list(strides) != expected_strides: + return None + else: + if len(reads) != group: + return None + expected_base = group * n * range_vars[0] + range_vars[1] + offsets = [] + for read in reads: + strides = V.graph.sizevars.stride_vars(read.index, range_vars) + if list(strides) != expected_strides: + return None + offsets.append(V.graph.sizevars.simplify(read.index - expected_base)) + expected_offsets = OrderedSet(offset * n for offset in range(group)) + if OrderedSet(offsets) != expected_offsets: + return None + return GemmReductionConfig( + output_name, group, axis, reduction_type, source_type + ) + + @classmethod + def _grouped_reduce_feeds_main_config( + cls, gemm_node: Buffer, scheduler_node: BaseSchedulerNode + ) -> GemmReductionConfig | None: + nodes = scheduler_node.get_nodes() + if len(nodes) != 1 or not isinstance(nodes[0].node, ComputedBuffer): + return None + node = cast(ComputedBuffer, nodes[0].node) + if not isinstance(node.data, Pointwise): + return None + reads = list(scheduler_node.read_writes.reads) + range_vars = scheduler_node.read_writes.range_vars + if range_vars is None or len(reads) <= 2: + return None + try: + _, n = map(V.graph.sizevars.optimization_hint, gemm_node.get_size()) + except Exception: + return None + group = len(reads) - 1 + if group <= 1 or group > 4: + return None + store = GemmEpilogueIRAnalysis.store_from_buffer(node) + if ( + store is None + or centered_mean_consumer_type_unrolled_ir( + store, gemm_node.get_name(), group + ) + != "mean_linear:1:-1:0" + ): + return None + if any(read.name != gemm_node.get_name() for read in reads): + return None + grouped_base = reads[1].index + if any( + V.graph.sizevars.simplify(read.index - grouped_base) != i * n + for i, read in enumerate(reads[1:]) + ): + return None + return GemmReductionConfig(node.get_name(), group, 0, "mean", "identity") + + @classmethod + def _epilogue_plan( + cls, + gemm_node: Buffer, + epilogue_nodes: Sequence[BaseSchedulerNode], + candidate: BaseSchedulerNode | None = None, + ) -> NVGemmEpiloguePlan: + reductions: list[GemmReductionConfig] = [] + reduction_nodes: list[BaseSchedulerNode] = [] + candidate_reduction = None + for node in epilogue_nodes: + config = cls._grouped_reduce_config(gemm_node, node) + if config is None: + continue + reductions.append(config) + reduction_nodes.extend(node.get_nodes()) + if node is candidate: + candidate_reduction = config + nodes = tuple( + scheduler_node + for node in epilogue_nodes + for scheduler_node in node.get_nodes() + ) + feed_main = ( + cls._grouped_reduce_feeds_main_config(gemm_node, epilogue_nodes[0]) + if len(epilogue_nodes) == 1 + else None + ) + return NVGemmEpiloguePlan( + nodes, + tuple(reductions), + tuple(reduction_nodes), + candidate_reduction, + feed_main, + ) + + def _can_fuse_epilogue_impl( + self, + gemm_template_node: SchedulerNode, + existing_epilogue_nodes: list[BaseSchedulerNode], + node_to_fuse: BaseSchedulerNode, + ) -> bool: + from .nv_universal_gemm import GemmVariant + + if not config.epilogue_fusion: + return False + + ir_node = gemm_template_node.node + if not isinstance(ir_node, (NVUniversalGemmBuffer, MultiTemplateBuffer)): + return False + + if isinstance(ir_node, NVUniversalGemmBuffer): + if ir_node.variant not in (GemmVariant.GEMM, GemmVariant.SCALED_GEMM): + log.debug( + "NVGEMM epilogue fusion: not supported for %s variant", + ir_node.variant.op_name, + ) + return False + if not ir_node.supports_epilogue_fusion: + log.debug( + "NVGEMM epilogue fusion: kernel %s does not support epilogue fusion", + ir_node.kernel_metadata.get("kernel_name", "unknown"), + ) + return False + elif isinstance(ir_node, MultiTemplateBuffer): + # Use _choices, not choice_timings() — the latter forces autotune sync. + has_efc_choice = False + for choice in ir_node._choices: + if not ( + isinstance(choice, NVUniversalGemmCaller) + and choice.supports_epilogue_fusion + ): + continue + has_efc_choice = True + if choice.variant not in ( + GemmVariant.GEMM, + GemmVariant.SCALED_GEMM, + ): + log.debug( + "NVGEMM epilogue fusion: MultiTemplateBuffer has unsupported EFC choices" + ) + return False + if not has_efc_choice: + log.debug("NVGEMM epilogue fusion: no EFC kernel available in choices") + return False + + plan = self._epilogue_plan( + ir_node, (*existing_epilogue_nodes, node_to_fuse), node_to_fuse + ) + reduction_nodes = OrderedSet(plan.reduction_nodes) + local_reduce = plan.candidate_reduction + feed_main = plan.feed_main + variants = ( + (ir_node.variant,) + if isinstance(ir_node, NVUniversalGemmBuffer) + else tuple( + choice.variant + for choice in ir_node._choices + if isinstance(choice, NVUniversalGemmCaller) + and choice.supports_epilogue_fusion + ) + ) + scaled_epilogue = bool(variants) and all( + variant == GemmVariant.SCALED_GEMM for variant in variants + ) + if local_reduce is not None: + if not scaled_epilogue: + return False + + for s_node in plan.nodes: + node = s_node.node + if not isinstance(node, ComputedBuffer): + log.debug("NVGEMM epilogue fusion: %s is not a ComputedBuffer", node) + return False + if ( + feed_main is None + and not isinstance(node.data, Pointwise) + and s_node not in reduction_nodes + ): + log.debug("NVGEMM epilogue fusion: %s is not a Pointwise op", node) + return False + + if ( + feed_main is None + and s_node not in reduction_nodes + and not V.graph.sizevars.statically_known_list_equals( + node.get_size(), ir_node.get_size() + ) + ): + log.debug( + "NVGEMM epilogue fusion: size mismatch %s vs %s", + node.get_size(), + ir_node.get_size(), + ) + return False + # cutlass.operators' EVT supports matrix, row, and column loads here. + # Reject unresolved inputs and shapes outside those broadcast patterns; + # the trial EVT trace below remains the final capability check. + gemm_size = ir_node.get_size() + name_to_buf = V.graph.name_to_buffer | V.graph.graph_inputs + internal_names = OrderedSet([ir_node.get_name()]) | OrderedSet( + [s_node.get_name() for s_node in plan.nodes] + ) + epilogue_inputs: OrderedSet[str] = OrderedSet() + for s_node in plan.nodes: + for rd in s_node.read_writes.reads: + if rd.name in internal_names: + continue + epilogue_inputs.add(rd.name) + read_buf = name_to_buf.get(rd.name) + if read_buf is None: + log.debug( + "NVGEMM epilogue fusion: read %s not in name_to_buffer/graph_inputs, refusing to fuse", + rd.name, + ) + return False + read_size = read_buf.get_size() + if not read_size or len(read_size) > len(gemm_size): + log.debug( + "NVGEMM epilogue fusion: read buffer %s has unsupported rank", + rd.name, + ) + return False + padded_size = [1] * (len(gemm_size) - len(read_size)) + list(read_size) + supported_shapes = ( + gemm_size, + [1, gemm_size[1]], + [gemm_size[0], 1], + ) + if not any( + V.graph.sizevars.statically_known_list_equals(padded_size, shape) + for shape in supported_shapes + ): + log.debug( + "NVGEMM epilogue fusion: read buffer %s size %s is not broadcastable to GEMM size %s", + rd.name, + read_size, + gemm_size, + ) + return False + if scaled_epilogue and len(epilogue_inputs) > 4: + log.debug( + "NVGEMM scaled epilogue has %d captured tensors; at most four are supported", + len(epilogue_inputs), + ) + return False + + if not existing_epilogue_nodes: + reads = OrderedSet(rd.name for rd in node_to_fuse.read_writes.reads) + if ir_node.get_name() not in reads: + log.debug( + "NVGEMM epilogue fusion: first epilogue node doesn't read from GEMM output" + ) + return False + + if node_to_fuse.has_aliasing_or_mutation(): + log.debug("NVGEMM epilogue fusion: node has aliasing or mutation") + return False + elif node_to_fuse.is_reduction() and local_reduce is None: + log.debug("NVGEMM epilogue fusion: reductions not supported") + return False + + all_epilogue_nodes = list(plan.nodes) + fused_buffer_names = OrderedSet( + n.get_name() for n in [gemm_template_node, *all_epilogue_nodes] + ) + preserve_gemm_output = ( + not V.graph.scheduler.can_buffer_be_removed_through_fusion( + ir_node.get_name(), fused_buffer_names + ) + ) + # Multi-store epilogues wire each output to its own destination tensor. + trial_removed_buffers = V.graph.removed_buffers.copy() + if not preserve_gemm_output: + trial_removed_buffers.add(ir_node.get_name()) + try: + evt_nodes = plan.evt_nodes + trial_reads: list[str] = [] + trial_writes: list[str] = [] + if feed_main is not None: + evt_nodes = [] + if evt_nodes: + trial_reads, trial_writes, _, _ = ( + CutlassEVTCodegen.ir_to_evt_python_code( + ir_node.get_name(), + evt_nodes, + trial_removed_buffers, + ) + ) + if scaled_epilogue: + if len(trial_reads) > 4 or len(trial_writes) > 4: + return False + for read_name in trial_reads: + read_buf = name_to_buf.get(read_name) + if read_buf is None: + log.debug( + "NVGEMM scaled EVT input %s cannot be resolved", + read_name, + ) + return False + except (NotImplementedError, AssertionError) as e: + log.debug("NVGEMM epilogue fusion: trial EVT codegen failed: %s", e) + return False + + return True + + def can_fuse_horizontal( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + # NVIDIA Universal GEMM templates don't support horizontal fusion yet + return False + + def can_fuse_reduction_epilogue( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ) -> bool: + template = node1.get_template_node() + return isinstance(template, Buffer) and ( + self._grouped_reduce_config(template, node2) is not None + or self._grouped_reduce_feeds_main_config(template, node2) is not None + ) + + def define_kernel( + self, src_code: str, node_schedule, precompile_metadata=None + ) -> str: + """ + Define a NVIDIA Universal GEMM kernel by writing source code and generating wrapper. + + Based on CuteDSLScheduling.define_kernel. + """ + wrapper = V.graph.wrapper_code + + # Use the string as the key for caching + if src_code in wrapper.src_to_kernel: + return wrapper.src_to_kernel[src_code] + + fused_name = ( + get_fused_kernel_name(node_schedule, config.triton.descriptive_names) + if config.triton.descriptive_names + else "" + ) + + kernel_hash = hashlib.sha256(src_code.encode("utf-8")).hexdigest()[:8] + if fused_name == "fused": + kernel_name = f"nv_universal_gemm_{kernel_hash}" + else: + kernel_name = f"nv_universal_gemm_{fused_name}_{kernel_hash}" + + wrapper.src_to_kernel[src_code] = kernel_name + + src_code = src_code.replace(str(Placeholder.KERNEL_NAME), kernel_name) + + _, _, kernel_path = get_path(code_hash(src_code), "py") + + compile_wrapper = IndentedBuffer() + compile_wrapper.writeline( + f"async_compile.nv_universal_gemm({kernel_name!r}, r'''" + ) + compile_wrapper.splice(src_code, strip=True) + if precompile_metadata is not None: + compile_wrapper.writeline( + f"''', precompile_metadata={precompile_metadata!r})" + ) + else: + compile_wrapper.writeline("''')") + + 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) + + return kernel_name + + def codegen_template( + self, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + prologue_nodes: Sequence[BaseSchedulerNode], + *, + only_gen_src_code: bool = False, + ) -> str | None: + """ + Codegen a NVIDIA Universal GEMM template with optional epilogue fusion. + + If `only_gen_src_code=True` the src code will be returned instead of being + codegenned into the wrapper (used for benchmarking). + """ + log.debug( + "NVGEMM codegen_template: template_node=%s, epilogue_nodes=%s, prologue_nodes=%s", + template_node, + [n.get_name() for n in epilogue_nodes] if epilogue_nodes else [], + [n.get_name() for n in prologue_nodes] if prologue_nodes else [], + ) + if not self.is_nv_universal_gemm_template(template_node): + raise AssertionError( + "Template node passed to NVUniversalGemmScheduling.codegen_template must be a " + "SchedulerNode that wraps a NVUniversalGemmBuffer or MultiTemplateBuffer with NVGEMM choice" + ) + if prologue_nodes: + raise AssertionError( + "NVIDIA Universal GEMM doesn't support prologue fusion yet" + ) + + template_node = cast(SchedulerNode, template_node) + + original_ir_node = template_node.node + if not isinstance(original_ir_node, Buffer): + raise AssertionError(f"expected Buffer, got {type(original_ir_node)}") + original_buffer_name = original_ir_node.get_name() + + ctb: NVUniversalGemmBuffer = self.get_nv_gemm_buffer_from_node( + template_node, require_epilogue_fusion=bool(epilogue_nodes) + ) + + epilogue_fn_code: str | None = None + epilogue_reads: list[str] = [] + epilogue_writes: list[str] = [] + epilogue_var_renames: dict[str, Any] = {} + local_reduce: GemmReductionPlan | None = None + + if epilogue_nodes: + scheduler = V.graph.scheduler + try: + plan = self._epilogue_plan(original_ir_node, epilogue_nodes) + if len(plan.reductions) > 1: + raise NotImplementedError( + "NVGEMM supports one grouped local reduction" + ) + if plan.reductions: + reduction = plan.reductions[0] + local_reduce = GemmReductionPlan( + reduction_output=reduction.output_name, + group=reduction.group, + axis=reduction.axis, + reduction_type=reduction.reduction_type, + source_type=reduction.source_type, + primary_output=original_buffer_name, + ) + feed_main = plan.feed_main + if feed_main is not None: + local_reduce = GemmReductionPlan( + reduction_output=None, + group=feed_main.group, + axis=feed_main.axis, + reduction_type=feed_main.reduction_type, + source_type=feed_main.source_type, + primary_output=feed_main.output_name, + feeds_main=True, + ) + epilogue_fn_code = ( + f"def {EPILOGUE_FN_NAME}(accum):\n D = accum\n return D" + ) + epilogue_writes = [feed_main.output_name] + epilogue_var_renames = { + _ACCUMULATOR_ARG_NAME: original_buffer_name, + "D": feed_main.output_name, + } + evt_nodes = [] if feed_main is not None else plan.evt_nodes + fused_buffer_names: OrderedSet[str] = OrderedSet( + n.get_name() for n in epilogue_nodes + ) + fused_buffer_names.add(original_buffer_name) + removed_buffers_with_gemm = V.graph.removed_buffers.copy() + if scheduler.can_buffer_be_removed_through_fusion( + original_buffer_name, fused_buffer_names + ): + removed_buffers_with_gemm.add(original_buffer_name) + + if evt_nodes: + evt_buffers = [ + node.node + for node in evt_nodes + if isinstance(node.node, ComputedBuffer) + ] + try: + reads, writes, var_renames, evt_code = ( + LoopIRCuteDSLCodegen.from_buffers( + original_buffer_name, + evt_buffers, + removed_buffers_with_gemm, + EPILOGUE_FN_NAME, + ) + ) + except NotImplementedError: + reads, writes, var_renames, evt_code = ( + CutlassEVTCodegen.ir_to_evt_python_code( + original_buffer_name, + list(evt_nodes), + removed_buffers_with_gemm, + fn_name=EPILOGUE_FN_NAME, + as_standalone_function=True, + ) + ) + epilogue_fn_code = evt_code + epilogue_reads = reads + epilogue_writes = writes + epilogue_var_renames = var_renames + + if not only_gen_src_code: + write_bufs = OrderedSet(epilogue_writes) + if local_reduce is not None: + write_bufs.update(local_reduce.auxiliary_outputs) + for node in epilogue_nodes: + node_name = node.get_name() + if node_name in write_bufs: + continue + if scheduler.can_buffer_be_removed_through_fusion( + node_name, fused_buffer_names + ): + V.graph.removed_buffers.add(node_name) + if ( + original_buffer_name not in write_bufs + and scheduler.can_buffer_be_removed_through_fusion( + original_buffer_name, fused_buffer_names + ) + ): + V.graph.removed_buffers.add(original_buffer_name) + for node in epilogue_nodes: + node.mark_run() + + log.debug( + "NVGEMM epilogue fusion: %d nodes, reads=%s, writes=%s, local_reduce=%s", + len(epilogue_nodes), + epilogue_reads, + epilogue_writes, + local_reduce, + ) + except (NotImplementedError, AssertionError) as e: + log.warning("NVGEMM epilogue codegen failed unexpectedly: %s", e) + raise + + if ctb.make_kernel_render is None: + raise AssertionError("expected ctb.make_kernel_render to be not None") + kernel, render = ctb.make_kernel_render( + ctb, + epilogue_fn_code=epilogue_fn_code, + epilogue_reads=epilogue_reads, + epilogue_writes=epilogue_writes, + epilogue_var_renames=epilogue_var_renames, + local_reduce=local_reduce, + ) + + if not only_gen_src_code: + template_node.mark_run() + + src_code = render() + + if only_gen_src_code: + return src_code + + # Precompile only base (non-EFC) kernels. EFC kernels produce + # closure-wrapped artifacts that can't be serialized to disk cache. + if epilogue_nodes: + precompile_metadata = None + else: + precompile_metadata = self._build_precompile_metadata(kernel, ctb) + + with V.set_kernel_handler(kernel): + node_schedule: list[BaseSchedulerNode] = [template_node] + if epilogue_nodes: + node_schedule.extend(epilogue_nodes) + kernel_name = self.define_kernel( + src_code, node_schedule, precompile_metadata + ) + + self.codegen_comment(node_schedule, kernel_name) + kernel.call_kernel(kernel_name, ctb) + V.graph.removed_buffers |= kernel.removed_buffers + V.graph.inplaced_to_remove |= kernel.inplaced_to_remove + self.free_buffers_in_scheduler() + return None + + def _build_precompile_metadata(self, kernel, ctb): + """Extract shapes and dtypes from kernel inputs/output for subprocess precompilation. + + Only called for base (non-epilogue) kernels. Returns None if shapes are + symbolic (dynamic shapes), in which case the subprocess will skip + precompilation and the kernel compiles lazily on first call. + """ + if not hasattr(kernel, "_template_input_args"): + return None + + precompile_shapes = {} + precompile_strides = {} + precompile_dtypes = {} + + try: + for param_name, input_node in kernel._template_input_args: + size = input_node.get_size() + precompile_shapes[param_name] = [int(s) for s in size] + stride = input_node.get_stride() + precompile_strides[param_name] = [int(s) for s in stride] + precompile_dtypes[param_name] = str( + input_node.get_dtype() + ).removeprefix("torch.") + + out_layout = cast(Layout, ctb.layout) + precompile_shapes["output"] = [int(s) for s in out_layout.size] + precompile_strides["output"] = [int(s) for s in out_layout.stride] + precompile_dtypes["output"] = str(out_layout.dtype).removeprefix("torch.") + except (TypeError, RuntimeError, ValueError): + log.debug( + "Skipping NV Universal GEMM precompile metadata: symbolic sizes " + "cannot be resolved to concrete values" + ) + return None + + device = ctb.layout.device + device_index = device.index if device.index is not None else 0 + + import torch + + device_capability = None + if torch.cuda.is_available(): + device_capability = torch.cuda.get_device_capability(device_index) + + max_active_clusters = None + kernel_name = ctb.kernel_metadata.get("kernel_name") + try: + if kernel_name and torch.cuda.is_available(): + from torch._inductor.codegen.nv_universal_gemm.kernel_cache import ( + get_kernel_by_name, + ) + + k = get_kernel_by_name(kernel_name) + if k is not None and hasattr(k, "impl"): + from cutlass.operators.providers.cutedsl.integration_utils.mma import ( + get_max_active_clusters, + ) + + max_active_clusters = get_max_active_clusters( + k.impl.cluster_shape_mn + ) + except Exception: + log.debug( + "Failed to resolve max_active_clusters for precompile", exc_info=True + ) + + return { + "precompile_shapes": precompile_shapes, + "precompile_strides": precompile_strides, + "precompile_dtypes": precompile_dtypes, + "device_index": device_index, + "device_capability": device_capability, + "max_active_clusters": max_active_clusters, + } + + def generate_kernel_code_from_nodes( + self, + nodes: Sequence[BaseSchedulerNode], + benchmark_kernel: bool = False, + hint_override: int | None = None, + ) -> str: + prologue, template, epilogue = nodes[0].get_prologue_template_epilogue( + list(nodes) + ) + + epilogue_reads: list[str] = [] + output_bufs: list[str] = [] + if epilogue: + template_sn = cast(SchedulerNode, template) + if not isinstance(template_sn.node, Buffer): + raise AssertionError(f"expected Buffer, got {type(template_sn.node)}") + original_buffer_name = template_sn.node.get_name() + plan = self._epilogue_plan(template_sn.node, epilogue) + evt_nodes = [] if plan.feed_main is not None else plan.evt_nodes + removed_buffers_with_gemm = V.graph.removed_buffers.copy() + if not plan.reductions: + removed_buffers_with_gemm.add(original_buffer_name) + try: + if evt_nodes: + reads, writes, var_renames, _ = ( + CutlassEVTCodegen.ir_to_evt_python_code( + original_buffer_name, + evt_nodes, + removed_buffers_with_gemm, + ) + ) + epilogue_reads = reads + d_buf = var_renames.get("D") + output_bufs = ([d_buf] if d_buf else []) + [ + w for w in writes if w != d_buf + ] + if plan.reductions: + output_bufs = [ + original_buffer_name, + *output_bufs, + plan.reductions[0].output_name, + ] + elif plan.feed_main is not None: + output_bufs = [plan.feed_main.output_name] + except (NotImplementedError, AssertionError) as e: + log.warning("NVGEMM benchmark epilogue codegen failed: %s", e) + + with config.patch("benchmark_kernel", benchmark_kernel): + src_code = self.codegen_template( + template, + epilogue, + prologue, + only_gen_src_code=True, + ) + + if src_code is None: + raise AssertionError("expected src_code to be not None") + src_code = src_code.replace( + str(Placeholder.KERNEL_NAME), _BENCHMARK_KERNEL_PREFIX + ) + + if benchmark_kernel: + src_code = self._add_benchmark_helpers( + src_code, template, epilogue, epilogue_reads, output_bufs + ) + + return src_code + + def _add_benchmark_helpers( + self, + src_code: str, + template_node: BaseSchedulerNode, + epilogue_nodes: Sequence[BaseSchedulerNode], + epilogue_reads: list[str], + output_bufs: list[str] | None = None, + ) -> str: + template_node = cast(SchedulerNode, template_node) + ctb: NVUniversalGemmBuffer = self.get_nv_gemm_buffer_from_node( + template_node, require_epilogue_fusion=bool(epilogue_nodes) + ) + + input_nodes = cast(list[Buffer], ctb.inputs) + # Output store layouts in out_ptr order. A multi-store epilogue has one + # per graph output; otherwise a single output (the fused final node, or + # the plain GEMM layout). + output_layouts: list[Layout] = [] + if output_bufs: + for b in output_bufs: + buf = V.graph.get_buffer(b) + # pyrefly: ignore [missing-attribute] + output_layouts.append(cast(Layout, buf.get_layout())) + elif epilogue_nodes: + final_node = cast(SchedulerNode, epilogue_nodes[-1]) + # pyrefly: ignore [missing-attribute] + output_layouts.append(cast(Layout, final_node.node.get_layout())) + else: + output_layouts.append(cast(Layout, ctb.layout)) + + args_code = IndentedBuffer() + args_code.writeline("") + args_code.writeline("is_nvgemm = True") + args_code.writeline("") + args_code.writeline("def get_args():") + with args_code.indent(): + args_code.writeline("import torch") + args_code.writeline("from torch._dynamo.testing import rand_strided") + args_code.writeline("args = []") + + for inp in input_nodes: + size = V.graph.sizevars.optimization_hints(inp.get_size()) + stride = V.graph.sizevars.optimization_hints(inp.get_stride()) + dtype = inp.get_dtype() + device = inp.get_device() + args_code.writeline( + f"args.append(rand_strided({size}, {stride}, device='{device}', dtype={dtype}))" + ) + + for ol in output_layouts: + out_size = V.graph.sizevars.optimization_hints(ol.size) + out_stride = V.graph.sizevars.optimization_hints(ol.stride) + args_code.writeline( + f"args.append(rand_strided({out_size}, {out_stride}, device='{ol.device}', dtype={ol.dtype}))" + ) + + for read_name in epilogue_reads: + buf = V.graph.get_buffer(read_name) + size = V.graph.sizevars.optimization_hints(buf.get_size()) + stride = V.graph.sizevars.optimization_hints(buf.get_stride()) + dtype = buf.get_dtype() + device = buf.get_device() + args_code.writeline( + f"args.append(rand_strided({size}, {stride}, device='{device}', dtype={dtype}))" + ) + + if ctb.workspace_size > 0: + args_code.writeline( + f"args.append(torch.empty({ctb.workspace_size}, " + f"device='{output_layouts[0].device}', dtype=torch.int8))" + ) + + args_code.writeline("return args") + + args_code.writeline("") + args_code.writeline("def call(args):") + with args_code.indent(): + args_code.writeline("import torch") + num_inputs = len(input_nodes) + n_fixed = num_inputs + len(output_layouts) + param_list = [f"args[{i}]" for i in range(n_fixed)] + + for j in range(len(epilogue_reads)): + param_list.append(f"args[{n_fixed + j}]") + + if ctb.workspace_size > 0: + param_list.append(f"args[{n_fixed + len(epilogue_reads)}]") + + params_str = ", ".join(param_list) + args_code.writeline("stream = torch.cuda.current_stream().cuda_stream") + bench_fn_name = f"{_BENCHMARK_KERNEL_PREFIX}_{MAIN_SUFFIX}" + args_code.writeline(f"{bench_fn_name}({params_str}, stream=stream)") + + return src_code + args_code.getvalue() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_utils.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b7a0ca95a72414ffbbc75fdef400d94aed6786cb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_utils.py @@ -0,0 +1,126 @@ +# mypy: allow-untyped-defs +""" +Utility functions for NVIDIA Universal GEMM. +""" + +import copyreg +from typing import Any + +from torch.nn.functional import ScalingType, SwizzleType + + +def _rebuild_scaling_type(name: str) -> Any: + return getattr(ScalingType, name) + + +def _rebuild_swizzle_type(name: str) -> Any: + return getattr(SwizzleType, name) + + +def _register_enum_pickling() -> None: + """Make torch.nn.functional ScalingType/SwizzleType picklable. + + They are pybind11 C++ enums whose class __qualname__ is `_ScalingType` / + `_SwizzleType`, but torch.nn.functional only binds the public names + `ScalingType` / `SwizzleType`. Pickle's default reduction reconstructs by + the private qualname and fails, which blocks shipping a scaled-GEMM + benchmark request to the autotuning subprocess pool. Reduce by `.name` + string via the public alias instead (no class object in the pickle). + """ + copyreg.pickle( + type(ScalingType.BlockWise1x16), + lambda v: (_rebuild_scaling_type, (v.name,)), + ) + copyreg.pickle( + type(SwizzleType.NO_SWIZZLE), + lambda v: (_rebuild_swizzle_type, (v.name,)), + ) + + +_register_enum_pickling() + + +def _rebuild_scaled_operand_constraints( + quantized: Any, scale: Any, mode: Any, swizzle: Any +) -> Any: + from cutlass.operators.metadata import ScaledOperandConstraints + + return ScaledOperandConstraints(quantized, scale, mode, swizzle) + + +def _register_scaled_operand_constraints_pickling() -> None: + """Avoid CUTLASS's recursive ``__getattr__`` during unpickling.""" + try: + from cutlass.operators.metadata import ScaledOperandConstraints + except ImportError: + return + + copyreg.pickle( + ScaledOperandConstraints, + lambda value: ( + _rebuild_scaled_operand_constraints, + (value.quantized, value.scale, value.mode, value.swizzle), + ), + ) + + +_register_scaled_operand_constraints_pickling() + + +def to_cutlass_scale_mode( + scale_type: Any, swizzle_type: Any +) -> tuple[Any | None, Any | None]: + """ + Map PyTorch ScalingType/SwizzleType to cutlass.operators ScaleMode/ScaleSwizzleMode. + + Args: + scale_type: ScalingType from torch.nn.functional + swizzle_type: SwizzleType from torch.nn.functional + + Returns: + Tuple of (ScaleMode, ScaleSwizzleMode) from cutlass.operators, + or (None, None) if the types are not supported. + + The returned enum objects can be used directly with cutlass.operators, or their + .name attribute can be used for codegen (e.g., scale_mode.name -> "Blockwise1x32"). + + NOTE: + Currently on Blackwell (SM100), NVGEMM only supports MXFP8 scaling modes. + Update this mapping when additional scaling modes are added. + """ + from cutlass.operators import ScaleMode, ScaleSwizzleMode + + scale_mode_map = { + ScalingType.BlockWise1x32: ScaleMode.Blockwise1x32, + ScalingType.BlockWise1x16: ScaleMode.Blockwise1x16, + } + swizzle_mode_map = { + SwizzleType.SWIZZLE_32_4_4: ScaleSwizzleMode.Swizzle32x4x4, + SwizzleType.NO_SWIZZLE: ScaleSwizzleMode.SwizzleNone, + } + return scale_mode_map.get(scale_type), swizzle_mode_map.get(swizzle_type) + + +# NOTE: cutlass.torch.dtype() doesn't support Float4E2M1FN (raises TypeError), +# so we maintain our own mapping that includes FP4. +_CUTLASS_TO_TORCH_DTYPE: dict | None = None + + +def cutlass_dtype_to_torch(cutlass_dtype: Any) -> "Any | None": + """Map a cutlass dtype to the corresponding torch dtype.""" + import torch + + global _CUTLASS_TO_TORCH_DTYPE + if _CUTLASS_TO_TORCH_DTYPE is None: + import cutlass + + _CUTLASS_TO_TORCH_DTYPE = { + cutlass.Float4E2M1FN: torch.float4_e2m1fn_x2, + cutlass.Float8E4M3FN: torch.float8_e4m3fn, + cutlass.Float8E5M2: torch.float8_e5m2, + cutlass.Float8E8M0FNU: torch.float8_e8m0fnu, + cutlass.BFloat16: torch.bfloat16, + cutlass.Float16: torch.float16, + cutlass.Float32: torch.float32, + } + return _CUTLASS_TO_TORCH_DTYPE.get(cutlass_dtype) diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/pallas.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/pallas.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab5b394caf5027f861363406b71e7ea668670c4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/pallas.py @@ -0,0 +1,4986 @@ +from __future__ import annotations + +import dataclasses +import hashlib +import math +import re +import typing_extensions +from typing import Any, cast, TYPE_CHECKING + +import sympy + +import torch +from torch.utils._ordered_set import OrderedSet +from torch.utils._sympy.functions import ( + Max as TorchMax, + Min as TorchMin, + ModularIndexing, +) + +from .. import config +from ..runtime.runtime_utils import torch_dtype_to_jax +from ..utils import get_fused_kernel_name, get_kernel_metadata +from ..virtualized import V +from .block_analysis import BlockPatternMatcher +from .common import ( + BackendFeature, + CSEVariable, + IndentedBuffer, + OpOverrides, + PythonPrinter, +) +from .simd import IterationRangesEntry, SIMDKernel, SIMDScheduling + + +class PallasPrinter(PythonPrinter): + """ + Custom sympy printer for Pallas that handles JAX-specific constructs. + """ + + def _print_Where(self, expr: sympy.Expr) -> str: + """Convert sympy Where to jnp.where.""" + c = self.doprint(expr.args[0]) + p = self.doprint(expr.args[1]) + q = self.doprint(expr.args[2]) + return f"jnp.where({c}, {p}, {q})" + + def _print_Min(self, expr: sympy.Expr) -> str: + """Convert sympy Min to jnp.minimum for JAX compatibility.""" + args = [self.doprint(arg) for arg in expr.args] + result = args[0] + for arg in args[1:]: + result = f"jnp.minimum({result}, {arg})" + return result + + def _print_Max(self, expr: sympy.Expr) -> str: + """Convert sympy Max to jnp.maximum for JAX compatibility.""" + args = [self.doprint(arg) for arg in expr.args] + result = args[0] + for arg in args[1:]: + result = f"jnp.maximum({result}, {arg})" + return result + + +# Use Pallas-specific printer for expression generation +pallas_pexpr = PallasPrinter().doprint + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + from ..ir import IRNode + from ..ops_handler import ReductionType + from ..scheduler import BaseSchedulerNode + + +# Main function suffix used in generated Pallas code +MAIN_SUFFIX = "main" + +# Logger for Pallas kernel code +kernel_code_log = torch._logging.getArtifactLogger(__name__, "kernel_code") + + +class PallasKernelWrapper: + """Wrapper to provide .run() interface for Pallas kernels""" + + def __init__(self, kernel_fn: Callable[..., Any], kernel_path: str | None = None): + self.kernel_fn = kernel_fn + self.kernel_path = kernel_path + kernel_code_log.info("Pallas kernel path: %s", kernel_path) + + def run(self, *args, stream=None, **kwargs): + """ + Execute the Pallas kernel. + + Args: + *args: Arguments to pass to the kernel function + stream: CUDA stream to pass to the kernel function + **kwargs: Additional keyword arguments for the kernel + + Returns: + Result of the kernel execution + """ + return self.kernel_fn(*args, stream=stream, **kwargs) + + +class Unsupported(RuntimeError): + """Exception raised when an operation is not supported by the Pallas backend.""" + + +class PallasKernelOverrides(OpOverrides): + """ + Map element-wise ops to JAX/Pallas operations. + + For now, we use the default Python operators which are compatible + with JAX numpy broadcasting semantics. + """ + + @staticmethod + # pyrefly: ignore [bad-override] + def sin(x: str) -> str: + return f"jnp.sin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cos(x: str) -> str: + return f"jnp.cos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tan(x: str) -> str: + return f"jnp.tan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sinh(x: str) -> str: + return f"jnp.sinh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def cosh(x: str) -> str: + return f"jnp.cosh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def tanh(x: str) -> str: + return f"jnp.tanh({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def asin(x: str) -> str: + return f"jnp.arcsin({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def acos(x: str) -> str: + return f"jnp.arccos({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def atan(x: str) -> str: + return f"jnp.arctan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def exp(x: str) -> str: + return f"jnp.exp({x})" + + @staticmethod + def exp2(x: str) -> str: + return f"jnp.exp2({x})" + + @staticmethod + def expm1(x: str) -> str: + return f"jnp.expm1({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def log(x: str) -> str: + return f"jnp.log({x})" + + @staticmethod + def log10(x: str) -> str: + return f"jnp.log10({x})" + + @staticmethod + def log2(x: str) -> str: + return f"jnp.log2({x})" + + @staticmethod + def log1p(x: str) -> str: + return f"jnp.log1p({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def sqrt(x: str) -> str: + return f"jnp.sqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def rsqrt(x: str) -> str: + return f"jax.lax.rsqrt({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def abs(x: str) -> str: + return f"jnp.abs({x})" + + @staticmethod + def neg(x: str) -> str: + return f"(-{x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def floor(x: str) -> str: + return f"jnp.floor({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def ceil(x: str) -> str: + return f"jnp.ceil({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def trunc(x: str) -> str: + return f"jnp.trunc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def round(x: str) -> str: + return f"jnp.round({x})" + + @staticmethod + def sigmoid(x: str) -> str: + return f"jax.nn.sigmoid({x})" + + @staticmethod + def relu(x: str) -> str: + return f"jnp.maximum({x}, 0)" + + @staticmethod + def pow(a: str, b: str) -> str: + return f"jnp.power({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def maximum(a: str, b: str) -> str: + return f"jnp.maximum({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def minimum(a: str, b: str) -> str: + return f"jnp.minimum({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def where(cond: str, a: str, b: str) -> str: + return f"jnp.where({cond}, {a}, {b})" + + @staticmethod + def masked(mask: str, body: Callable[[], str], other: float) -> str: + """ + Computes body, but only uses the result where mask is true. + Where mask is false, uses the 'other' value instead. + """ + result = body() + # Format the 'other' value properly for JAX + if isinstance(other, float): + if math.isnan(other): + other_str = "jnp.nan" + elif math.isinf(other): + other_str = "jnp.inf" if other > 0 else "-jnp.inf" + else: + other_str = repr(other) + else: + other_str = repr(other) + # Use jnp.where to select between result and other based on mask + return f"jnp.where({mask}, {result}, {other_str})" + + @staticmethod + def to_dtype( + x: str, + dtype: torch.dtype, + src_dtype: torch.dtype | None = None, + use_compute_types: bool = True, + ) -> str: + # TPU doesn't support 64-bit types + if dtype == torch.int64 and V.graph.get_current_device_or_throw().type == "tpu": + dtype = torch.int32 + jax_dtype = torch_dtype_to_jax(dtype) + # Wrap in jnp.asarray to handle scalars from integer indexing + return f"jnp.asarray({x}).astype({jax_dtype})" + + @staticmethod + def to_dtype_bitcast(x: str, dtype: torch.dtype, src_dtype: torch.dtype) -> str: + """Bitcast a value from one dtype to another with the same size.""" + jax_dtype = torch_dtype_to_jax(dtype) + jax_src_dtype = torch_dtype_to_jax(src_dtype) + # First ensure the value is the correct source dtype, then bitcast + return f"jax.lax.bitcast_convert_type(jnp.asarray({x}).astype({jax_src_dtype}), {jax_dtype})" + + @staticmethod + def index_expr(expr: sympy.Expr, dtype: torch.dtype) -> str: + """Convert a sympy expression to a JAX array indexing expression.""" + from ..utils import get_bounds_index_expr + + # Track which iteration variables are used + V.kernel.used_iter_vars.update(V.kernel._get_used_iter_vars(expr)) + + # Prepare and rename indexing to register size symbols as kernel args + prepared = V.kernel.prepare_indexing(expr) + renamed = V.kernel.rename_indexing(prepared) + idx_str = V.kernel.kexpr(renamed) + var = V.kernel.cse.generate( + V.kernel.compute, idx_str, bounds=get_bounds_index_expr(expr) + ) + return PallasKernelOverrides.to_dtype(var, dtype) + + @staticmethod + def value_expr(expr: sympy.Expr, dtype: torch.dtype) -> str: + # Pallas index_expr already emits the requested dtype, so value_expr has + # the same lowering here. + return PallasKernelOverrides.index_expr(expr, dtype) + + @staticmethod + def constant(val, dtype: torch.dtype) -> str: + """Convert a constant value to JAX representation.""" + jax_dtype = torch_dtype_to_jax(dtype) + if dtype == torch.bool: + return "True" if val else "False" + # Handle special float values + if isinstance(val, float): + if math.isnan(val): + return "jnp.nan" + if math.isinf(val): + return "jnp.inf" if val > 0 else "-jnp.inf" + return f"jnp.array({val}, dtype={jax_dtype})" + + @staticmethod + def real(x: str) -> str: + return f"jnp.real({x})" + + @staticmethod + def imag(x: str) -> str: + return f"jnp.imag({x})" + + @staticmethod + def conj(x: str) -> str: + return f"jnp.conj({x})" + + @staticmethod + def angle(x: str) -> str: + return f"jnp.angle({x})" + + @staticmethod + def view_as_real(x: str) -> str: + """View complex tensor as real tensor with extra dimension.""" + return f"jnp.stack([jnp.real({x}), jnp.imag({x})], axis=-1)" + + @staticmethod + def view_as_complex(x: str) -> str: + """View real tensor as complex tensor.""" + return f"({x}[..., 0] + 1j * {x}[..., 1])" + + # Comparison operations + @staticmethod + def eq(a: str, b: str) -> str: + return f"({a} == {b})" + + @staticmethod + def ne(a: str, b: str) -> str: + return f"({a} != {b})" + + @staticmethod + def lt(a: str, b: str) -> str: + return f"({a} < {b})" + + @staticmethod + def le(a: str, b: str) -> str: + return f"({a} <= {b})" + + @staticmethod + def gt(a: str, b: str) -> str: + return f"({a} > {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def isnan(x: str) -> str: + return f"jnp.isnan({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def isinf(x: str) -> str: + return f"jnp.isinf({x})" + + @staticmethod + def isfinite(x: str) -> str: + return f"jnp.isfinite({x})" + + @staticmethod + def ge(a: str, b: str) -> str: + return f"({a} >= {b})" + + # Logical operations + @staticmethod + # pyrefly: ignore [bad-override] + def logical_and(a: str, b: str) -> str: + return f"jnp.logical_and({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_or(a: str, b: str) -> str: + return f"jnp.logical_or({a}, {b})" + + @staticmethod + def logical_not(x: str) -> str: + return f"jnp.logical_not({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def logical_xor(a: str, b: str) -> str: + return f"jnp.logical_xor({a}, {b})" + + # Math operations + @staticmethod + # pyrefly: ignore [bad-override] + def atan2(a: str, b: str) -> str: + return f"jnp.arctan2({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def hypot(a: str, b: str) -> str: + return f"jnp.hypot({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def fmod(a: str, b: str) -> str: + return f"jnp.fmod({a}, {b})" + + @staticmethod + def remainder(a: str, b: str) -> str: + return f"jnp.remainder({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def truncdiv(a: str, b: str) -> str: + # Truncated division (rounds toward zero) + # For integers: sign(a)*sign(b) * (abs(a) // abs(b)) + return f"(jnp.sign({a}) * jnp.sign({b}) * (jnp.abs({a}) // jnp.abs({b}))).astype({a}.dtype)" + + @staticmethod + def floordiv(a: str, b: str) -> str: + return f"({a} // {b})" + + @staticmethod + def clamp(x: str, min_val: str, max_val: str) -> str: + return f"jnp.clip({x}, {min_val}, {max_val})" + + clip = clamp + + # Sign operations + @staticmethod + # pyrefly: ignore [bad-override] + def sign(x: str) -> str: + # PyTorch returns 0 for NaN, JAX returns NaN + return f"jnp.where(jnp.isnan({x}), 0.0, jnp.sign({x}))" + + @staticmethod + # pyrefly: ignore [bad-override] + def signbit(x: str) -> str: + return f"jnp.signbit({x})" + + # Special math functions + @staticmethod + # pyrefly: ignore [bad-override] + def erf(x: str) -> str: + return f"jax.scipy.special.erf({x})" + + @staticmethod + def erfc(x: str) -> str: + return f"jax.scipy.special.erfc({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def erfinv(x: str) -> str: + return f"jax.scipy.special.erfinv({x})" + + @staticmethod + # pyrefly: ignore [bad-override] + def lgamma(x: str) -> str: + return f"jax.scipy.special.gammaln({x})" + + @staticmethod + def digamma(x: str) -> str: + return f"jax.scipy.special.digamma({x})" + + @staticmethod + def bessel_j0(x: str) -> str: + # bessel_jn requires float64 and has numerical issues at x=0 (returns NaN) + # bessel_jn(x, v=n) returns array of shape (n+1, ...) with J_0 to J_n + # Handle by: convert to float64, compute, handle x=0, convert back + # J0(0) = 1.0 + return ( + f"jnp.where({x}.astype(jnp.float64) == 0.0, 1.0, " + f"jax.scipy.special.bessel_jn({x}.astype(jnp.float64), v=0)[0])" + f".astype({x}.dtype)" + ) + + @staticmethod + def bessel_j1(x: str) -> str: + # bessel_jn requires float64 and has numerical issues at x=0 (returns NaN) + # bessel_jn(x, v=n) returns array of shape (n+1, ...) with J_0 to J_n + # Handle by: convert to float64, compute, handle x=0, convert back + # J1(0) = 0.0 + return ( + f"jnp.where({x}.astype(jnp.float64) == 0.0, 0.0, " + f"jax.scipy.special.bessel_jn({x}.astype(jnp.float64), v=1)[1])" + f".astype({x}.dtype)" + ) + + @staticmethod + def modified_bessel_i0(x: str) -> str: + # Modified Bessel function of the first kind I_0(x) + # I_0(x) = bessel_i0e(x) * exp(|x|) where bessel_i0e is the scaled version + return f"jax.lax.bessel_i0e({x}) * jnp.exp(jnp.abs({x}))" + + @staticmethod + def modified_bessel_i1(x: str) -> str: + # Modified Bessel function of the first kind I_1(x) + # I_1(x) = bessel_i1e(x) * exp(|x|) where bessel_i1e is the scaled version + return f"jax.lax.bessel_i1e({x}) * jnp.exp(jnp.abs({x}))" + + @staticmethod + def spherical_bessel_j0(x: str) -> str: + # Spherical Bessel function of the first kind j_0(x) = sin(x) / x + # Handle x=0: j_0(0) = 1 + return f"jnp.where({x} == 0.0, 1.0, jnp.sin({x}) / {x})" + + i0 = modified_bessel_i0 + + @staticmethod + def i0e(x: str) -> str: + # Exponentially scaled modified Bessel function I_0 + return f"jax.lax.bessel_i0e({x})" + + i1 = modified_bessel_i1 + + @staticmethod + def i1e(x: str) -> str: + # Exponentially scaled modified Bessel function I_1 + return f"jax.lax.bessel_i1e({x})" + + @staticmethod + def gammainc(x: str, y: str) -> str: + # Regularized lower incomplete gamma function P(a, x) + # Note: PyTorch uses gammainc(input, other) where input is a (shape param) + return f"jax.scipy.special.gammainc({x}, {y})" + + @staticmethod + def gammaincc(x: str, y: str) -> str: + # Regularized upper incomplete gamma function Q(a, x) + return f"jax.scipy.special.gammaincc({x}, {y})" + + igamma = gammainc + + igammac = gammaincc + + @staticmethod + def polygamma(x: str, y: str) -> str: + # Polygamma function psi^(n)(x), x is order n, y is the value + # Note: JAX uses polygamma(n, x) where n is integer order + return f"jax.scipy.special.polygamma({x}.astype(jnp.int32), {y})" + + @staticmethod + def ndtri(x: str) -> str: + # Inverse of the standard normal CDF + return f"jax.scipy.special.ndtri({x})" + + @staticmethod + def zeta(x: str, y: str) -> str: + # Hurwitz zeta function zeta(x, q) = sum_{k=0}^inf 1/(k+q)^x + return f"jax.scipy.special.zeta({x}, {y})" + + @staticmethod + def xlogy(x: str, y: str) -> str: + # x * log(y), with proper handling of x=0 + return f"jax.scipy.special.xlogy({x}, {y})" + + @staticmethod + def xlog1py(x: str, y: str) -> str: + # x * log1p(y), with proper handling of x=0 + return f"jax.scipy.special.xlog1py({x}, {y})" + + @staticmethod + # pyrefly: ignore [bad-override] + def chebyshev_polynomial_t(x: str, n: str) -> str: + # Chebyshev polynomial of the first kind T_n(x) + # For |x| <= 1: T_n(x) = cos(n * arccos(x)) + # For x > 1: T_n(x) = cosh(n * arccosh(x)) + # For x < -1: T_n(x) = (-1)^n * cosh(n * arccosh(-x)) + return ( + f"jnp.where(jnp.abs({x}) <= 1, " + f"jnp.cos({n} * jnp.arccos(jnp.clip({x}, -1, 1))), " + f"jnp.where({x} > 1, " + f"jnp.cosh({n} * jnp.arccosh(jnp.maximum({x}, 1.0))), " + f"((-1.0) ** {n}) * jnp.cosh({n} * jnp.arccosh(jnp.maximum(-{x}, 1.0)))))" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def chebyshev_polynomial_u(x: str, n: str) -> str: + # Chebyshev polynomial of the second kind U_n(x) + # For |x| < 1: U_n(x) = sin((n+1) * arccos(x)) / sqrt(1 - x^2) + # For x = 1: U_n(1) = n+1 + # For x = -1: U_n(-1) = (-1)^n * (n+1) + # For x > 1: U_n(x) = sinh((n+1) * arccosh(x)) / sqrt(x^2 - 1) + # For x < -1: U_n(x) = (-1)^n * U_n(-x) (symmetry) + return ( + f"jnp.where(jnp.abs({x}) < 1, " + f"jnp.sin(({n} + 1) * jnp.arccos(jnp.clip({x}, -1, 1))) / " + f"jnp.sqrt(jnp.maximum(1 - {x}**2, 1e-10)), " + f"jnp.where({x} >= 1, " + f"jnp.where({x} == 1, {n} + 1.0, " + f"jnp.sinh(({n} + 1) * jnp.arccosh(jnp.maximum({x}, 1.0))) / " + f"jnp.sqrt(jnp.maximum({x}**2 - 1, 1e-10))), " + f"jnp.where({x} == -1, ((-1.0) ** {n}) * ({n} + 1.0), " + f"((-1.0) ** {n}) * jnp.sinh(({n} + 1) * jnp.arccosh(jnp.maximum(-{x}, 1.0))) / " + f"jnp.sqrt(jnp.maximum({x}**2 - 1, 1e-10)))))" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def chebyshev_polynomial_v(x: str, n: str) -> str: + # Chebyshev polynomial of the third kind V_n(x) + # V_n(x) = (T_n(x) - T_{n+1}(x)) / (1 - x) for x != 1 + # V_n(1) = 1, recurrence: V_0 = 1, V_1 = 2x - 1, V_n = 2x*V_{n-1} - V_{n-2} + # Explicit: V_0 = 1, V_1 = 2x-1, V_2 = 4x^2-2x-1, V_3 = 8x^3-4x^2-4x+1 + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, 2*{x} - 1, " + f"jnp.where({n} == 2, 4*{x}**2 - 2*{x} - 1, " + f"jnp.where({n} == 3, 8*{x}**3 - 4*{x}**2 - 4*{x} + 1, " + f"jnp.where({n} == 4, 16*{x}**4 - 8*{x}**3 - 12*{x}**2 + 4*{x} + 1, " + f"jnp.where({n} == 5, 32*{x}**5 - 16*{x}**4 - 32*{x}**3 + 12*{x}**2 + 6*{x} - 1, " + f"jnp.zeros_like({x})))))))" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def chebyshev_polynomial_w(x: str, n: str) -> str: + # Chebyshev polynomial of the fourth kind W_n(x) + # W_n(x) = (T_n(x) + T_{n+1}(x)) / (1 + x) for x != -1 + # W_n(-1) = (-1)^n, recurrence: W_0 = 1, W_1 = 2x + 1, W_n = 2x*W_{n-1} - W_{n-2} + # Explicit: W_0 = 1, W_1 = 2x+1, W_2 = 4x^2+2x-1, W_3 = 8x^3+4x^2-4x-1 + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, 2*{x} + 1, " + f"jnp.where({n} == 2, 4*{x}**2 + 2*{x} - 1, " + f"jnp.where({n} == 3, 8*{x}**3 + 4*{x}**2 - 4*{x} - 1, " + f"jnp.where({n} == 4, 16*{x}**4 + 8*{x}**3 - 12*{x}**2 - 4*{x} + 1, " + f"jnp.where({n} == 5, 32*{x}**5 + 16*{x}**4 - 32*{x}**3 - 12*{x}**2 + 6*{x} + 1, " + f"jnp.zeros_like({x})))))))" + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def shifted_chebyshev_polynomial_t(x: str, n: str) -> str: + return PallasKernelOverrides.chebyshev_polynomial_t(f"(2 * {x} - 1)", n) + + @staticmethod + # pyrefly: ignore [bad-override] + def shifted_chebyshev_polynomial_u(x: str, n: str) -> str: + return PallasKernelOverrides.chebyshev_polynomial_u(f"(2 * {x} - 1)", n) + + @staticmethod + # pyrefly: ignore [bad-override] + def shifted_chebyshev_polynomial_v(x: str, n: str) -> str: + return PallasKernelOverrides.chebyshev_polynomial_v(f"(2 * {x} - 1)", n) + + @staticmethod + # pyrefly: ignore [bad-override] + def shifted_chebyshev_polynomial_w(x: str, n: str) -> str: + return PallasKernelOverrides.chebyshev_polynomial_w(f"(2 * {x} - 1)", n) + + @staticmethod + # pyrefly: ignore [bad-override] + def hermite_polynomial_h(x: str, n: str) -> str: + # Physicist's Hermite polynomial H_n(x) + # H_n(x) = 2^n * x^n - n*(n-1)/2 * 2^(n-2) * x^(n-2) + ... + # Use explicit formula: H_n(x) = n! * sum_{m=0}^{n//2} (-1)^m / (m! * (n-2m)!) * (2x)^(n-2m) + # For simplicity, use the relation: H_n(x) = 2^(n/2) * He_n(x * sqrt(2)) where He is probabilist's + # Actually simpler: use recurrence or closed form + # H_0 = 1, H_1 = 2x, H_2 = 4x^2 - 2, H_3 = 8x^3 - 12x + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, 2 * {x}, " + f"jnp.where({n} == 2, 4 * {x}**2 - 2, " + f"jnp.where({n} == 3, 8 * {x}**3 - 12 * {x}, " + f"jnp.where({n} == 4, 16 * {x}**4 - 48 * {x}**2 + 12, " + f"jnp.where({n} == 5, 32 * {x}**5 - 160 * {x}**3 + 120 * {x}, " + f"jnp.zeros_like({x})))))))" # Fallback for higher n + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def hermite_polynomial_he(x: str, n: str) -> str: + # Probabilist's Hermite polynomial He_n(x) + # He_0 = 1, He_1 = x, He_2 = x^2 - 1, He_3 = x^3 - 3x + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, {x}, " + f"jnp.where({n} == 2, {x}**2 - 1, " + f"jnp.where({n} == 3, {x}**3 - 3 * {x}, " + f"jnp.where({n} == 4, {x}**4 - 6 * {x}**2 + 3, " + f"jnp.where({n} == 5, {x}**5 - 10 * {x}**3 + 15 * {x}, " + f"jnp.zeros_like({x})))))))" # Fallback for higher n + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def laguerre_polynomial_l(x: str, n: str) -> str: + # Laguerre polynomial L_n(x) + # L_0 = 1, L_1 = 1 - x, L_2 = (x^2 - 4x + 2)/2, L_3 = (-x^3 + 9x^2 - 18x + 6)/6 + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, 1 - {x}, " + f"jnp.where({n} == 2, ({x}**2 - 4*{x} + 2) / 2, " + f"jnp.where({n} == 3, (-{x}**3 + 9*{x}**2 - 18*{x} + 6) / 6, " + f"jnp.where({n} == 4, ({x}**4 - 16*{x}**3 + 72*{x}**2 - 96*{x} + 24) / 24, " + f"jnp.where({n} == 5, (-{x}**5 + 25*{x}**4 - 200*{x}**3 + 600*{x}**2 - 600*{x} + 120) / 120, " + f"jnp.zeros_like({x})))))))" # Fallback for higher n + ) + + @staticmethod + # pyrefly: ignore [bad-override] + def legendre_polynomial_p(x: str, n: str) -> str: + # Legendre polynomial P_n(x) + # P_0 = 1, P_1 = x, P_2 = (3x^2 - 1)/2, P_3 = (5x^3 - 3x)/2 + return ( + f"jnp.where({n} == 0, jnp.ones_like({x}), " + f"jnp.where({n} == 1, {x}, " + f"jnp.where({n} == 2, (3 * {x}**2 - 1) / 2, " + f"jnp.where({n} == 3, (5 * {x}**3 - 3 * {x}) / 2, " + f"jnp.where({n} == 4, (35 * {x}**4 - 30 * {x}**2 + 3) / 8, " + f"jnp.where({n} == 5, (63 * {x}**5 - 70 * {x}**3 + 15 * {x}) / 8, " + f"jnp.zeros_like({x})))))))" # Fallback for higher n + ) + + # Reciprocal and square + @staticmethod + def reciprocal(x: str) -> str: + return f"jnp.reciprocal({x})" + + @staticmethod + def square(x: str) -> str: + return f"jnp.square({x})" + + # Additional operations + @staticmethod + def fma(a: str, b: str, c: str) -> str: + """Fused multiply-add: a * b + c + + JAX doesn't have jnp.fma, so we use the unfused version. + The compiler may still fuse this on supported hardware. + """ + return f"(({a}) * ({b}) + ({c}))" + + @staticmethod + # pyrefly: ignore [bad-override] + def copysign(a: str, b: str) -> str: + return f"jnp.copysign({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def nextafter(a: str, b: str) -> str: + return f"jnp.nextafter({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def ldexp(a: str, b: str) -> str: + return f"jnp.ldexp({a}, {b})" + + @staticmethod + # pyrefly: ignore [bad-override] + def frexp(x: str) -> str: + return f"jnp.frexp({x})" + + @staticmethod + def modf(x: str) -> str: + return f"jnp.modf({x})" + + # Bitwise operations + @staticmethod + def bitwise_and(a: str, b: str) -> str: + return f"jnp.bitwise_and({a}, {b})" + + @staticmethod + def bitwise_or(a: str, b: str) -> str: + return f"jnp.bitwise_or({a}, {b})" + + @staticmethod + def bitwise_xor(a: str, b: str) -> str: + return f"jnp.bitwise_xor({a}, {b})" + + @staticmethod + def bitwise_not(x: str) -> str: + return f"jnp.bitwise_not({x})" + + @staticmethod + def left_shift(a: str, b: str) -> str: + return f"jnp.left_shift({a}, {b})" + + @staticmethod + def right_shift(a: str, b: str) -> str: + return f"jnp.right_shift({a}, {b})" + + # Random number generation operations + @staticmethod + def load_seed(name: str, offset: str) -> str: + """Load the random seed value from a buffer.""" + # Load the seed from the buffer and add offset for uniqueness + # pyrefly: ignore[bad-argument-type] + seed_offset = V.kernel.args.seed_offset("load_seed_offset", offset) + return f"({V.kernel.args.input(name)}[0] + {seed_offset})" + + @staticmethod + def rand(seed: str, offset: str) -> str: + """Generate uniform random numbers in [0, 1). + + Uses JAX's threefry2x32 PRNG directly for vectorized random generation. + The seed provides the base key, offset provides per-element uniqueness. + """ + # For vectorized random, we use jax.random.uniform with shape from offset + # Create a base key from seed, then use fold_in with vmap for per-element keys + # Use float32 dtype to match PyTorch's default + return ( + f"jax.vmap(lambda o: jax.random.uniform(" + f"jax.random.fold_in(jax.random.PRNGKey(jnp.uint32({seed})), jnp.uint32(o)), (), dtype=jnp.float32))" + f"(jnp.asarray({offset}).flatten()).reshape(jnp.asarray({offset}).shape)" + ) + + @staticmethod + def randn(seed: str, offset: str) -> str: + """Generate standard normal random numbers. + + Uses JAX's threefry2x32 PRNG directly for vectorized random generation. + The seed provides the base key, offset provides per-element uniqueness. + """ + # For vectorized random, use vmap to fold in each offset value + # Use float32 dtype to match PyTorch's default + return ( + f"jax.vmap(lambda o: jax.random.normal(" + f"jax.random.fold_in(jax.random.PRNGKey(jnp.uint32({seed})), jnp.uint32(o)), (), dtype=jnp.float32))" + f"(jnp.asarray({offset}).flatten()).reshape(jnp.asarray({offset}).shape)" + ) + + @staticmethod + def randint64(seed: str, offset: str, low: str, high: str) -> str: + """Generate random int64 values in [low, high).""" + # For vectorized random, use vmap to fold in each offset value + return ( + f"jax.vmap(lambda o: jax.random.randint(" + f"jax.random.fold_in(jax.random.PRNGKey(jnp.uint32({seed})), jnp.uint32(o)), (), {low}, {high}, dtype=jnp.int64))" + f"(jnp.asarray({offset}).flatten()).reshape(jnp.asarray({offset}).shape)" + ) + + +@dataclasses.dataclass +class _IndirectAccessInfo: + """Describes a detected indirect (data-dependent) buffer access.""" + + table_param: str + table_buf_name: str + table_shape: tuple + indirect_dim: int + indirect_var: str + indices_param: str + + +@dataclasses.dataclass +class _BufferIndexing: + """Encapsulates index string and flattening requirements for buffer access.""" + + index_str: str + needs_flatten: bool + + +@dataclasses.dataclass +class _BroadcastedIterVar: + """Encapsulates information needed to codegen a broadcasted iteration var""" + + # index of this var in `self.range_tree_nodes.items()`` + idx: int + var_sym: sympy.Symbol + entry: IterationRangesEntry + length_val: int | None + + +@dataclasses.dataclass +class _CodegenContext: + """Bundles local state shared across codegen_kernel helper methods.""" + + code: IndentedBuffer + kernel_name: str + is_tpu: bool + interpret_is_cpu: bool + interpret_literal: str + kernel_params: list[str] + pure_out_params: list[str] + output_params: list[str] + size_var_params: list[str] + output_buffer_lookup: dict[str, str] + aliasable_flags: dict[str, bool] + alias_params: list[str] + pointer_tail: list[str] + kernel_input_params: list[str] + full_kernel_params: list[str] + non_alias_out_set: OrderedSet[str] + copy_output_indices: list[int] + alias_pairs: list[tuple[int, int]] + + +class PallasKernel(SIMDKernel): + """Pallas kernel codegen for TPU and GPU (Mosaic backend). + + Generates Python code that defines a Pallas kernel and a host entrypoint, + compiled and loaded via async_compile.pallas. + """ + + overrides = PallasKernelOverrides # type: ignore[assignment] + kexpr: Callable[[sympy.Expr], str] = pallas_pexpr # Use Pallas expression printer + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Determine device type once at initialization + device = V.graph.get_current_device_or_throw() + self.is_gpu = device.type == "cuda" + self.is_tpu = device.type == "tpu" + # Use TMA (Tensor Memory Accelerator) for GPU to handle non-aligned tensor sizes + # TMA automatically masks OOB accesses, eliminating the need for explicit + # padding to multiples of 128. Uses lax.fori_loop with direct TMA primitives. + self.use_emit_pipeline = self.is_gpu # Enable TMA approach for GPU + # Track which output param each store uses: list of (out_ptr_name, store_line) + self.store_with_output: list[tuple[str, str]] = [] + # Track load index expressions for reduction axis detection + self.load_index_exprs: dict[str, sympy.Expr] = {} + # Track outputs that need to be readable (for scatter operations) + self.outputs_need_read: OrderedSet[str] = OrderedSet() + # Map input buffer names to their detected permutation tuples. + self.permuted_input_buffers: dict[str, tuple[int, ...]] = {} + self.collapsed_reshape_inputs: dict[str, tuple[int, ...]] = {} + self.collapsed_output_shape: tuple[int, ...] | None = None + self._cpu_max_grid_product: int | None = None + # Precompute output buffer names from scheduler nodes so that the + # load path can check output shapes before stores are processed. + self._output_buffer_names: list[str] = [] + for snode in self.features.scheduler_nodes(): + for dep in snode.read_writes.writes: + self._output_buffer_names.append(dep.name) + # Track which iteration variables are actually used in the kernel + self.used_iter_vars: OrderedSet[sympy.Symbol] = OrderedSet() + # Iteration vars that have been emitted in tile-relative form + # (safe for tiling even when they appear in the compute body) + self.tile_relative_iter_vars: OrderedSet[sympy.Symbol] = OrderedSet() + # Track if any load/store uses flatten-based indexing (buf[...].flatten()[idx]) + self.has_flatten_indexing = False + # Strided input buffers: map graph buffer name -> per-dim + # (stride, offset, skip) triples. Used to reshape inputs outside + # the kernel and generate static indexing inside + # (e.g. in_ref[:, :, offset] instead of in_ref[...].flatten()[idx]). + self.strided_input_buffers: dict[str, list[tuple[int, int, int]]] = {} + # Buffers that already use flatten+gather indexing; strided + # decomposition must not reshape these (it would break flat offsets). + self.flatten_indexed_buffers: OrderedSet[str] = OrderedSet() + # Indirect (data-dependent) access info for scalar prefetch + self.indirect_access: _IndirectAccessInfo | None = None + self._cse_to_param: dict[str, str] = {} + self._param_to_graph_name: dict[str, str] = {} + self.is_tpu = device.type == "tpu" + + def check_bounds( + self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool + ) -> None: + """Check array bounds for indirect indexing.""" + # For now, skip explicit bounds checking as JAX/Pallas handles this internally + # TODO: Implement explicit bounds checking with assertions if needed + + def _get_index_str(self, index: sympy.Expr) -> str: + """ + Convert an index expression to a string suitable for Pallas indexing. + + Pallas operates on full arrays, so we need to convert index expressions + to JAX array slicing. For example: + - x0 -> "..." (contiguous access, full array) + - 2*x0 -> "::2" (strided access with stride 2) + - 2*x0 + 1 -> "1::2" (strided access with offset 1, stride 2) + + Args: + index: The indexing expression to convert + + Returns: + The indexing string to use in generated code + """ + # Prepare and simplify the index + prepared_index = self.prepare_indexing(index) + + # Note: Block variable detection (im2col patterns) is handled in load()/store() + # where we have access to buffer dimensions. We check the buffer size + # against iteration variables there to detect gather patterns. + + # For simple single-symbol access (contiguous case), we can use [...] + # which is more efficient as it operates on the entire array at once + if isinstance(prepared_index, sympy.Symbol): + return "..." + elif prepared_index.is_Integer: + # Scalar index + return str(prepared_index) + else: + # Complex expression (strided/scatter access) + # Try to extract stride and offset for common patterns + return self._convert_to_jax_slice(prepared_index) + + def _convert_to_jax_slice(self, index: sympy.Expr) -> str: + """ + Convert a sympy index expression to JAX slice notation. + + Handles common patterns like: + - stride*var -> ::stride + - stride*var + offset -> offset::stride + + For more complex patterns, falls back to explicit indexing. + Uses BlockPatternMatcher for robust pattern matching. + """ + # Get the iteration variables for this kernel + if not self.range_trees: + return "..." + + # Rename symbolic sizes to kernel parameter names upfront + index = self.rename_indexing(index) + + # Check for ModularIndexing - this is NOT contiguous access + # ModularIndexing is used for roll/wrap-around operations + if index.has(ModularIndexing): + # Track which iteration variables are used before returning + self.used_iter_vars.update(self._get_used_iter_vars(index)) + # Generate actual index expression - iteration variables are already + # defined as jnp.arange arrays, so we just convert to JAX code + return self.kexpr(index) + + # Simplify the index + index = V.graph.sizevars.simplify(index) + # Find which iteration variable(s) are used + used_vars = self._get_used_iter_vars(index) + + # Track which iteration variables are used + self.used_iter_vars.update(used_vars) + + if len(used_vars) == 0: + # No iteration variables, this is a constant index + return str(index) + elif len(used_vars) == 1: + # Single iteration variable - try to extract stride and offset using BlockPatternMatcher + var = next(iter(used_vars)) + + # Get the subexpression involving this variable + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(index, var) + + # Try to match affine pattern: stride * var + stride = BlockPatternMatcher.match_affine_block_expr(var_expr, var) + + if stride is not None: + offset = index - var_expr + offset = V.graph.sizevars.simplify(offset) + + if stride < 0: + return self.kexpr(index) + + if offset == 0: + return "..." + + # Non-zero offset: check if we can use slice notation + if stride != 1: + return self.kexpr(index) + + try: + offset_val = int(offset) + if offset_val < 0: + return self.kexpr(index) + except (TypeError, ValueError): + return self.kexpr(index) + + return f"{self.kexpr(offset)}::1" + else: + # Couldn't match affine pattern, fall back to original logic + offset = index - var_expr + offset = V.graph.sizevars.simplify(offset) + if offset == 0 and var_expr == var: + # Just the variable itself, unit stride + return "..." + elif len(used_vars) > 1: + # Multi-dimensional indexing + # For contiguous multi-dim access, all terms should have unit stride + all_unit_stride = True + for var in used_vars: + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(index, var) + stride = BlockPatternMatcher.match_affine_block_expr(var_expr, var) + if stride != 1: + all_unit_stride = False + break + if all_unit_stride: + # Contiguous multi-dimensional access + return "..." + else: + # Strided multi-dimensional access + # For most cases, inputs are made contiguous before passing to JAX, + # so strided tensors become contiguous and we can use [...] + # The buffer size check in load() handles im2col-like patterns + return "..." + + # For complex cases, use [...] since inputs are made contiguous + return "..." + + def _generate_strided_index(self, index: sympy.Expr) -> str: + """ + Generate JAX code to compute an index array for strided/complex indexing patterns. + + For expressions like `2 * x3 + 32 * x2 + 256 * x1 + 1024 * x0`, we generate + code that computes the flattened index array using broadcasting. + + The iteration variables (x0, x1, x2, x3) are already defined as jnp.arange arrays + in the kernel. We just need to convert the sympy expression to JAX code. + """ + free_symbols = index.free_symbols + iter_vars = self._get_iter_vars() + + # Check that all free symbols are iteration variables (no indirect vars) + used_vars = free_symbols & iter_vars + if used_vars != free_symbols: + raise Unsupported( + f"Pallas backend does not yet support mixed index pattern: {index}" + ) + + # Track which iteration variables are used + self.used_iter_vars.update(used_vars) + + # Convert sympy expression to Python/JAX code string + # The iteration variables are already defined as jnp.arange arrays + index_str = self.kexpr(index) + + # Mark this as requiring flatten access + return index_str + + def _get_iter_vars(self) -> OrderedSet: + """Get the set of iteration variable symbols.""" + return OrderedSet(self.range_tree_nodes.keys()) + + def _get_used_iter_vars(self, index: sympy.Expr) -> OrderedSet: + """Get iteration variables used in an index expression.""" + return index.free_symbols & self._get_iter_vars() + + def _has_iteration_vars(self, index: sympy.Expr) -> bool: + """Check if index expression contains iteration variables.""" + return bool(self._get_used_iter_vars(index)) + + def _get_indirect_vars(self, index: sympy.Expr) -> list[sympy.Symbol]: + """Get list of indirect variable symbols (tmp*) in an index expression.""" + return [s for s in index.free_symbols if str(s).startswith("tmp")] + + def _has_indirect_vars(self, index: sympy.Expr) -> bool: + """Check if index expression contains indirect variables.""" + return len(self._get_indirect_vars(index)) > 0 + + def _decompose_strided_access( + self, index: sympy.Expr, name: str + ) -> list[tuple[int, int, int]] | None: + """Decompose a flat index into per-dimension (stride, offset, skip) triples. + + Given flat index like ``64*x0 + 2*x1 + 5`` and buffer shape ``(32, 64)`` + with C-contiguous strides ``[64, 1]``: + - x0 coefficient 64 / buffer_stride[0]=64 -> dim 0: stride=1 + - x1 coefficient 2 / buffer_stride[1]=1 -> dim 1: stride=2 + - constant 5: dim 0 gets 5//64=0, dim 1 gets 5//1=5 + - dim 1 offset 5 with stride 2: skip=5//2=2, offset=5%2=1 + + Returns per-dim ``[(stride, offset, skip), ...]`` where: + - stride: access stride on this dim (1 = contiguous) + - offset: static index into the stride dim (0 <= offset < stride) + - skip: number of stride-blocks to skip at the start of this dim + Returns None if decomposition fails. + """ + if self._has_indirect_vars(index) or index.has(ModularIndexing): + return None + + # Don't reshape a buffer that already has flatten+gather loads; + # the reshape would change the flat layout and break those loads. + if name in self.flatten_indexed_buffers: + return None + + info = self._get_buffer_info(name) + if info is None: + return None + _, buf_size, _, _, _ = info + + buf_shape_or_none = [self._safe_int(s) for s in buf_size] + if any(s is None or s <= 0 for s in buf_shape_or_none): + return None + buf_shape: list[int] = cast(list[int], buf_shape_or_none) + ndim = len(buf_shape) + if ndim == 0: + return None + + c_strides = self._c_contiguous_strides(buf_shape) + + # Extract per-variable coefficients + used_vars = self._get_used_iter_vars(index) + if not used_vars: + return None + + # [stride, raw_offset] per dim — raw_offset may be >= stride + result: list[list[int]] = [[1, 0] for _ in range(ndim)] + # Track which variable maps to which dimension + var_to_dim: dict[sympy.Symbol, int] = {} + + remaining = V.graph.sizevars.simplify(index) + for var in used_vars: + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(remaining, var) + coeff = BlockPatternMatcher.match_affine_block_expr(var_expr, var) + if coeff is None: + return None + coeff_int = self._safe_int(coeff) + if coeff_int is None or coeff_int <= 0: + return None + + # Find which buffer dim this variable maps to + dim = None + for d in range(ndim): + if c_strides[d] == 0: + continue + if coeff_int % c_strides[d] == 0: + per_dim_stride = coeff_int // c_strides[d] + if per_dim_stride >= 1: + dim = d + break + if dim is None: + return None + + per_dim_stride = coeff_int // c_strides[dim] + if per_dim_stride < 1 or buf_shape[dim] % per_dim_stride != 0: + return None + + result[dim][0] = per_dim_stride + var_to_dim[var] = dim + remaining = V.graph.sizevars.simplify(remaining - var_expr) + + # Remaining is the constant offset; distribute across dims using + # divmod with C-contiguous strides (largest stride first). + offset_val = self._safe_int(remaining) + if offset_val is None: + return None + if offset_val < 0: + return None + for d in range(ndim): + if c_strides[d] > 0: + result[d][1] = offset_val // c_strides[d] + offset_val = offset_val % c_strides[d] + if offset_val != 0: + return None + + # Only return if there's at least one dim with stride > 1. + # Contiguous accesses with just an offset (stride=1 everywhere) + # are handled by the normal tiling path. + if all(s == 1 for s, _ in result): + return None + + # Decompose each dim's raw offset into (skip, offset) where + # offset < stride: raw = skip * stride + offset. + # Then validate the output numel matches. + decomposed: list[tuple[int, int, int]] = [] + output_numel_expected = 1 + for d in range(ndim): + stride, raw_offset = result[d] + offset = raw_offset % stride + skip = raw_offset // stride + n_blocks = buf_shape[d] // stride + if skip >= n_blocks: + return None + output_numel_expected *= n_blocks - skip + decomposed.append((stride, offset, skip)) + + output_numel, _ = self._compute_output_numel_from_index(index) + if output_numel != output_numel_expected: + return None + + # Verify each variable's range matches its assigned dimension's + # effective size. When the kernel collapses multiple buffer dims + # into one iteration variable (e.g. batch*channels), the variable + # range won't match any single buffer dimension and we must bail + # out to avoid shape mismatches in the generated code. + for var, dim in var_to_dim.items(): + if var not in self.range_tree_nodes: + return None + var_range = self._safe_int(self.range_tree_nodes[var].length) + if var_range is None: + return None + stride_d, _offset_d, skip_d = decomposed[dim] + effective_size = buf_shape[dim] // stride_d - skip_d + if var_range != effective_size: + return None + + return decomposed + + @staticmethod + def _strided_load_expr(buf: str, decomp: list[tuple[int, int, int]]) -> str: + """Build ``buf[:, :, offset]`` for strided dims, ``:`` for others.""" + parts: list[str] = [] + for stride, offset, _skip in decomp: + if stride == 1: + parts.append(":") + else: + parts.append(":") # the halved dim + parts.append(str(offset)) # static index into stride dim + return f"{buf}[{', '.join(parts)}]" + + def _codegen_strided_reshapes( + self, code: IndentedBuffer, params: list[str] + ) -> None: + """Emit reshape + optional slice for strided input parameters. + + For each strided param, reshapes ``(M, N)`` to ``(M, N/stride, stride)`` + and, when ``skip > 0``, slices off leading blocks so the remaining + elements align with the output. + """ + for param in params: + buf_name = self._param_to_buf_name(param) + if buf_name is None or buf_name not in self.strided_input_buffers: + continue + strides = self.strided_input_buffers[buf_name] + info = self._get_buffer_info(buf_name) + if info is None: + continue + _, buf_size, _, _, _ = info + new_shape_parts: list[str] = [] + for d, (stride, _offset, _skip) in enumerate(strides): + dim = self._safe_int(buf_size[d]) + if dim is None: + break + if stride > 1: + new_shape_parts.append(str(dim // stride)) + new_shape_parts.append(str(stride)) + else: + new_shape_parts.append(str(dim)) + else: + code.writeline( + f"{param} = {param}.reshape({', '.join(new_shape_parts)})" + ) + if any(skip > 0 for _, _, skip in strides): + slice_parts: list[str] = [] + for stride, _offset, skip in strides: + if stride == 1: + slice_parts.append(":") + else: + slice_parts.append(f"{skip}:" if skip > 0 else ":") + slice_parts.append(":") + code.writeline(f"{param} = {param}[{', '.join(slice_parts)}]") + + @staticmethod + def _get_actual_out_strides(out_buf, n: int) -> list[int] | None: + """Extract actual output buffer strides from its layout.""" + layout = getattr(out_buf, "get_layout", lambda: None)() + if layout is None: + return None + stride_raw = getattr(layout, "stride", None) + if stride_raw is None or len(stride_raw) != n: + return None + strides: list[int] = [] + for s in stride_raw: + v = int(s) if isinstance(s, (int, sympy.Integer)) else None + if v is None: + return None + strides.append(v) + return strides + + def _compute_store_coeffs(self, ordered: list) -> dict | None: + """Compute store-side linearization coefficients from range tree nesting. + + The tree structure encodes the output iteration order: later + trees (prefix ``x``) are innermost, earlier trees (``y``, ``z``) + are outer. Within a tree, dict order goes inner-to-outer. + The innermost variable gets coefficient 1; each successive + variable (moving outward) multiplies by the previous range. + + Returns ``{sympy.Symbol: int}`` mapping each RT var to its store + coefficient, or ``None`` on failure. + """ + prefix_groups: dict[str, list] = {} + prefix_order: list[str] = [] + for v in ordered: + node = self.range_tree_nodes[v] + p = node.prefix + if p not in prefix_groups: + prefix_groups[p] = [] + prefix_order.append(p) + prefix_groups[p].append(v) + inner_to_outer: list = [] + for p in reversed(prefix_order): + inner_to_outer.extend(prefix_groups[p]) + coeffs: dict = {} + coeff = 1 + for v in inner_to_outer: + sz = self._safe_int(self.range_tree_nodes[v].length) + if sz is None: + return None + coeffs[v] = coeff + coeff *= sz + return coeffs + + def _get_full_load_permutation( + self, name: str, index: sympy.Expr + ) -> tuple[int, ...] | None: + """Return permutation for a full-array load, or None. + + Computes the permutation by mapping each range-tree variable to + both an output dimension (via store coefficients + actual output + strides) and an input dimension (via load coefficients + input + C-contiguous strides). The permutation is then: + + perm[out_dim] = in_dim for each RT variable + + Using actual output strides (not C-contiguous) is critical: the + scheduler may choose a non-standard output layout (e.g. column- + major) to optimise for transposed inputs. + + When all dimensions collapse to a single flat RT variable (e.g. + (2,2,2,2,2) with all dims size 2), infers the permutation + directly from output strides vs input C-contiguous strides. + """ + info = self._get_buffer_info(name) + if not info: + return None + _, buf_size, _, _, is_contiguous = info + in_shape_raw = [self._safe_int(s) for s in buf_size] + if len(in_shape_raw) < 2 or None in in_shape_raw: + return None + in_shape: list[int] = cast(list[int], in_shape_raw) + if not is_contiguous: + return None # .contiguous() at JAX boundary handles this + + # Extract index coefficients for each non-reduction RT variable. + iter_used = self._get_used_iter_vars(index) + ordered = [ + s + for s, e in self.range_tree_nodes.items() + if s in iter_used and not e.is_reduction + ] + if len(ordered) != len(in_shape): + # All dims may have collapsed to a single flat RT variable + # (e.g. (2,2,2,2,2) → single x0 of length 32). In this + # case, infer the permutation directly from output strides + # vs input C-contiguous strides. + n = len(in_shape) + if len(ordered) == 1 and self._safe_int( + self.range_tree_nodes[ordered[0]].length + ) == math.prod(in_shape): + in_strides = self._c_contiguous_strides(in_shape) + for out_name in self._output_buffer_names: + out_buf = V.graph.get_buffer(out_name) + if out_buf is None: + continue + out_shape = [self._safe_int(s) for s in out_buf.get_size()] + if any(s is None for s in out_shape) or len(out_shape) != n: + continue + actual = self._get_actual_out_strides(out_buf, n) + if actual is None: + break + # Map each output dim to the input dim with the + # same stride. + perm = self._map_coeffs_to_dims(actual, in_strides) + if perm is None: + break + if list(perm) == list(range(n)): + return None + return tuple(perm) + return None + coeffs_raw = [ + self._get_index_coefficient(V.graph.sizevars.simplify(index), v) + for v in ordered + ] + if not all(isinstance(c, int) and c > 0 for c in coeffs_raw): + return None + coeffs: list[int] = cast(list[int], coeffs_raw) + + n = len(ordered) + in_strides = self._c_contiguous_strides(in_shape) + store_coeffs = self._compute_store_coeffs(ordered) + + # --- Primary path: dimension-mapping with actual output strides --- + if store_coeffs is not None: + for out_name in self._output_buffer_names: + out_buf = V.graph.get_buffer(out_name) + if out_buf is None: + continue + out_shape = [self._safe_int(s) for s in out_buf.get_size()] + if any(s is None for s in out_shape) or len(out_shape) != n: + continue + + actual = self._get_actual_out_strides(out_buf, n) + if actual is not None: + rt_to_out = self._map_coeffs_to_dims( + [store_coeffs[v] for v in ordered], actual + ) + rt_to_in = self._map_coeffs_to_dims(list(coeffs), in_strides) + if rt_to_out is not None and rt_to_in is not None: + perm = [0] * n + for k in range(n): + perm[rt_to_out[k]] = rt_to_in[k] + if list(perm) == list(range(n)): + return None + return tuple(perm) + break + + return None + + def _get_collapsed_load_permutation( + self, name: str, index: sympy.Expr + ) -> tuple[tuple[int, ...], tuple[int, ...]] | None: + """Handle permutation when range tree has collapsed dimensions. + + When simplify_and_reorder merges contiguous dims, the range tree + has fewer variables than the buffer's rank. This method detects + the permutation in the collapsed space and returns + (collapsed_input_shape, perm) so the caller can generate: + jnp.permute_dims(load.reshape(collapsed_shape), perm) + + Uses index coefficients on both sides: load-index coefficients + map vars to collapsed input dims, and store-side coefficients + (derived from the range tree nesting) map vars to collapsed + output dims. Both sets of strides are always unique, so + matching is unambiguous even with duplicate group sizes. + """ + info = self._get_buffer_info(name) + if not info: + return None + _, buf_size, _, _, is_contiguous = info + in_shape_raw = [self._safe_int(s) for s in buf_size] + if len(in_shape_raw) < 2 or None in in_shape_raw: + return None + in_shape: list[int] = cast(list[int], in_shape_raw) + if not is_contiguous: + return None + + iter_used = self._get_used_iter_vars(index) + ordered = [ + s + for s, e in self.range_tree_nodes.items() + if s in iter_used and not e.is_reduction + ] + n = len(ordered) + if n < 2 or n >= len(in_shape): + return None + ranges_raw = [self._safe_int(self.range_tree_nodes[v].length) for v in ordered] + if None in ranges_raw: + return None + ranges: list[int] = cast(list[int], ranges_raw) + if math.prod(ranges) != math.prod(in_shape): + return None + + # Group consecutive input dims (right-to-left) to match ranges + in_groups = self._group_dims_to_ranges(in_shape, ranges) + if in_groups is None: + return None + + # Compute collapsed input strides (row-major) and use load-index + # coefficients to map each range tree var to a collapsed input dim. + # Strides are always unique, so this is unambiguous even when + # group sizes are duplicated. + collapsed_in_strides = [0] * n + stride = 1 + for i in range(n - 1, -1, -1): + collapsed_in_strides[i] = stride + stride *= in_groups[i] + + simplified = V.graph.sizevars.simplify(index) + in_coeffs_raw = [self._get_index_coefficient(simplified, v) for v in ordered] + if not all(isinstance(c, int) and c > 0 for c in in_coeffs_raw): + return None + in_coeffs: list[int] = cast(list[int], in_coeffs_raw) + + in_stride_to_dim = {s: i for i, s in enumerate(collapsed_in_strides)} + var_to_in_dim = [] + for coeff in in_coeffs: + dim = in_stride_to_dim.get(coeff) + if dim is None: + return None + var_to_in_dim.append(dim) + + store_coeffs = self._compute_store_coeffs(ordered) + if store_coeffs is None: + return None + + # Find the output-side mapping using store coefficients. + for out_name in self._output_buffer_names: + out_buf = V.graph.get_buffer(out_name) + if out_buf is None: + continue + out_shape_raw = [self._safe_int(s) for s in out_buf.get_size()] + if any(s is None for s in out_shape_raw) or len(out_shape_raw) < 2: + continue + out_shape: list[int] = cast(list[int], out_shape_raw) + if math.prod(out_shape) != math.prod(in_shape): + continue + out_groups = self._group_dims_to_ranges(out_shape, list(in_groups)) + if out_groups is None: + continue + + # Compute collapsed output strides and match store coefficients. + collapsed_out_strides = [0] * n + stride = 1 + for i in range(n - 1, -1, -1): + collapsed_out_strides[i] = stride + stride *= out_groups[i] + + out_stride_to_dim = {s: j for j, s in enumerate(collapsed_out_strides)} + var_to_out_dim = [] + for v in ordered: + j = out_stride_to_dim.get(store_coeffs[v]) + if j is None: + return None + var_to_out_dim.append(j) + + # Build perm: perm[out_dim] = in_dim + perm = [0] * n + for k in range(n): + perm[var_to_out_dim[k]] = var_to_in_dim[k] + if perm == list(range(n)): + return None + return (tuple(in_groups), tuple(perm)) + return None + + @staticmethod + def _group_dims_to_ranges(dims: list[int], ranges: list[int]) -> list[int] | None: + """Group consecutive dims (right-to-left) to match range values. + + Returns collapsed shape (left-to-right) or None if no valid grouping. + """ + available = list(ranges) + groups: list[int] = [] + product = 1 + for i in range(len(dims) - 1, -1, -1): + product *= dims[i] + try: + idx = available.index(product) + except ValueError: + continue + groups.append(product) + available.pop(idx) + product = 1 + if product != 1 or available: + return None + groups.reverse() + return groups + + def _get_index_expr(self, index: sympy.Expr) -> _BufferIndexing: + """Get the index expression string and whether it needs flattening.""" + has_indirect = self._has_indirect_vars(index) + has_iter_vars = self._has_iteration_vars(index) + + if has_indirect and has_iter_vars: + return _BufferIndexing( + index_str=self._handle_mixed_indexing(index), needs_flatten=True + ) + elif has_indirect: + return _BufferIndexing(index_str=self.kexpr(index), needs_flatten=False) + else: + index_str = self._get_index_str(index) + # Check if index contains ModularIndexing - this requires flattened access + # ModularIndexing is used for roll/wrap-around operations + needs_flatten = index.has(ModularIndexing) and index_str != "..." + # If index_str is an actual expression (not "..." or a slice pattern), + # we need flattened access because it uses block variables + if not needs_flatten and index_str != "...": + # Check if it's a simple slice pattern (::N or M::N) + if not ("::" in index_str or index_str.lstrip("-").isdigit()): + needs_flatten = True + return _BufferIndexing(index_str=index_str, needs_flatten=needs_flatten) + + @staticmethod + def _safe_int(val: Any) -> int | None: + """Convert value to int, returning None on failure.""" + try: + return int(val) + except (TypeError, ValueError): + return None + + @staticmethod + def _c_contiguous_strides(shape: list[int]) -> list[int]: + """Return C-contiguous strides for the given shape.""" + n = len(shape) + strides = [1] * n + for i in range(n - 2, -1, -1): + strides[i] = strides[i + 1] * shape[i + 1] + return strides + + @staticmethod + def _map_coeffs_to_dims(coeffs: list[int], strides: list[int]) -> list[int] | None: + """Map coefficient values to dimension indices via stride matching. + + Returns a list where entry k is the dimension whose stride equals + coeffs[k], or None if the mapping is ambiguous or incomplete. + """ + stride_to_dim: dict[int, int] = {} + for d, s in enumerate(strides): + if s in stride_to_dim: + return None # duplicate strides + stride_to_dim[s] = d + mapping: list[int] = [] + for c in coeffs: + d = stride_to_dim.get(c) + if d is None: + return None + mapping.append(d) + if len(OrderedSet(mapping)) != len(coeffs): + return None + return mapping + + def _zero_dim_output_flags(self, ctx: _CodegenContext) -> tuple[bool, bool]: + """Return whether an output has a zero or unknown dimension.""" + has_unknown_dim = False + for buf_name in ctx.output_buffer_lookup.values(): + buf = V.graph.try_get_buffer(buf_name) + if buf is None: + has_unknown_dim = True + continue + for dim in buf.get_size(): + dim_int = self._safe_int(dim) + if dim_int == 0: + return True, has_unknown_dim + if dim_int is None: + has_unknown_dim = True + return False, has_unknown_dim + + def _get_reduction_axes(self) -> tuple[int, ...]: + """Determine which axes of the loaded array are reduction axes. + + Finds the innermost reduction stride from the load index + expression, then walks outward through the buffer's dims + using stride ratios until the accumulated product reaches + red_numel. Falls back to stride-direction analysis for + gather/flatten loads. + """ + if not self.load_index_exprs: + return (-1,) + + r_vars = [v for v, e in self.range_tree_nodes.items() if e.is_reduction] + pw_vars = [v for v, e in self.range_tree_nodes.items() if not e.is_reduction] + if not r_vars or not pw_vars: + return (-1,) + + red_numel = self._compute_reduction_numel() + if not red_numel or red_numel <= 1: + return (-1,) + + for buf_name, load_index in self.load_index_exprs.items(): + info = self._get_buffer_info(buf_name) + if info is None: + continue + _, buf_size, _, actual_strides, _ = info + nd = len(buf_size) + if nd < 2: + continue + strides_or_none = [self._safe_int(s) for s in actual_strides] + if any(s is None for s in strides_or_none): + continue + strides: list[int] = cast(list[int], strides_or_none) + + # Get reduction stride coefficients by zeroing pw_vars. + r_only = load_index + for pv in pw_vars: + r_only = r_only.subs(pv, 0) + r_coeffs: OrderedSet[int] = OrderedSet() + for term in sympy.Add.make_args(r_only): + if term.is_number: + continue + coeff, _ = term.as_coeff_Mul() + c = self._safe_int(coeff) + if c is not None and c > 0: + r_coeffs.add(c) + if not r_coeffs: + continue + + # Match all coefficients against buffer strides + matched = sorted( + (i for i in range(nd) if strides[i] in r_coeffs), + ) + if not matched: + continue + + # Multiple r_vars each map to a distinct dim — return directly. + # Single r_var with multiple coefficients (transposed access) + # → skip to fallback. + if len(r_coeffs) > 1: + if len(r_coeffs) == len(matched) and len(r_vars) > 1: + return tuple(i - nd for i in matched) + continue + + # Single coefficient: walk outward from the matched dim + # using span to find flattened contiguous dims. + r_stride = next(iter(r_coeffs)) + span = (red_numel - 1) * r_stride + is_contiguous = all(strides[i] > strides[i + 1] for i in range(nd - 1)) + if is_contiguous: + # Walk by dim index (strides are in descending order) + inner = matched[-1] + start = inner + while start > 0 and span > strides[start - 1]: + start -= 1 + axes = list(range(start, inner + 1)) + else: + # Non-contiguous layout: collect dims whose strides + # fall within the r_var's traversal range + axes = sorted( + i + for i in range(nd) + if r_stride <= strides[i] and strides[i] < span + r_stride + ) + if not axes: + axes = list(matched) + return tuple(i - nd for i in axes) + + # Fallback: stride-direction for gather/flatten loads + load_index = next(iter(self.load_index_exprs.values())) + r_coeff = load_index.coeff(r_vars[0]) + r_stride = self._safe_int(r_coeff) if r_coeff != 0 else 1 + if r_stride is None: + r_stride = 1 + pw_coeff = load_index.coeff(pw_vars[0]) + pw_stride = self._safe_int(pw_coeff) if pw_coeff != 0 else 1 + if pw_stride is None: + pw_stride = 1 + if r_stride > pw_stride: + return (0,) + return (-1,) + + def _compute_prefix_numel(self, prefixes: OrderedSet) -> int | None: + """Compute total numel for given prefixes (e.g., pointwise prefixes).""" + result = 1 + for p in prefixes: + if p in self.numels: + numel = self._safe_int(self.numels[p]) + if numel is None: + return None + result *= numel + return result + + def _compute_reduction_numel(self) -> int | None: + """Compute total reduction numel.""" + result = 1 + for tree in self.range_trees: + if tree.is_reduction: + numel = self._safe_int(tree.numel) + if numel is None: + return None + result *= numel + return result + + def _can_use_tma_approach(self) -> bool: + """ + Check if TMA (Tensor Memory Accelerator) approach can be used. + TMA works for simple element-wise ops but not for: + - Reductions (need different accumulation patterns) + TODO: TMA supports float64 for loading but not for reductions + - Broadcasting (inputs have different shapes or output differs) + - Non-contiguous tensors (strided, transposed) + """ + # TMA flattens to 1D tiles, incompatible with permutation detection + # which emits jnp.permute_dims expecting N-D input. + if self.permuted_input_buffers: + return False + + # Check for reductions + reduction_numel = self._compute_reduction_numel() + if reduction_numel is not None and reduction_numel > 1: + return False + + # Check all input buffers for contiguity, dtype, and shape consistency + input_shapes: list[tuple] = [] + for name in self.args.input_buffers: + info = self._get_buffer_info(name) + if info is None: + return False + buf_obj, buf_size, buf_numel, actual_strides, is_contiguous = info + if not is_contiguous: + return False + + # Check for unsupported dtypes + # TODO: TMA supports float64 for loading but current JAX Mosaic GPU + # implementation doesn't support it yet. Re-enable when JAX adds support. + buf_dtype = getattr(buf_obj, "get_dtype", lambda: None)() + if buf_dtype is not None: + import torch + + if buf_dtype == torch.float64: + return False + + # Collect shape as tuple for comparison + shape_tuple = tuple(self._safe_int(s) for s in buf_size) + if None in shape_tuple: + return False # Dynamic shapes not supported + input_shapes.append(shape_tuple) + + # Check if all input shapes are identical (no broadcasting) + if input_shapes and len(OrderedSet(input_shapes)) > 1: + return False + + # Check that output numel matches input numel (no broadcasting expansion) + if input_shapes: + input_numel = 1 + for s in input_shapes[0]: + input_numel *= s + + # Compute output numel from pointwise range trees (non-reduction) + output_numel = 1 + for tree in self.range_trees: + if not tree.is_reduction: + numel = self._safe_int(tree.numel) + if numel is None: + return False # Dynamic shapes not supported + output_numel *= numel + + if output_numel != input_numel: + return False + + return True + + def _get_buffer_info(self, name: str) -> tuple[Any, Any, Any, list, bool] | None: + """Get buffer metadata (buf_obj, buf_size, buf_numel, actual_strides, is_contiguous). + + Returns None if the buffer doesn't exist. + """ + buf_obj = V.graph.get_buffer(name) + if buf_obj is None: + return None + buf_size = buf_obj.get_size() + buf_numel = 1 + for s in buf_size: + sval = self._safe_int(s) + buf_numel *= sval if sval is not None else s + + # Get buffer strides and check contiguity + actual_strides: list = [] + is_contiguous = True + + layout = getattr(buf_obj, "get_layout", lambda: None)() + buf_stride = getattr(layout, "stride", None) if layout else None + + if buf_stride is not None: + for i in range(len(buf_size)): + actual_stride = self._safe_int(buf_stride[i]) + actual_strides.append(actual_stride) + + # Check contiguity + if len(buf_size) == 1: + if actual_strides[0] is not None and actual_strides[0] != 1: + is_contiguous = False + elif len(buf_size) > 1: + expected_stride = 1 + for i in range(len(buf_size) - 1, -1, -1): + actual_stride = actual_strides[i] + if actual_stride is None or actual_stride != expected_stride: + is_contiguous = False + dim_size = self._safe_int(buf_size[i]) + if dim_size is not None: + expected_stride *= dim_size + + return buf_obj, buf_size, buf_numel, actual_strides, is_contiguous + + def _compute_output_numel_from_index( + self, index: sympy.Expr + ) -> tuple[int, OrderedSet]: + """Compute expected output numel and used vars from iteration variables in index.""" + used_vars = self._get_used_iter_vars(index) + + used_range_lengths = [] + for var in used_vars: + if var in self.range_tree_nodes: + entry = self.range_tree_nodes[var] + length_val = self._safe_int(entry.length) + if length_val is not None: + used_range_lengths.append(length_val) + + output_numel = 1 + for l in used_range_lengths: + output_numel *= l + + return output_numel, used_vars + + def _get_index_coefficients( + self, index: sympy.Expr, used_vars: OrderedSet + ) -> OrderedSet: + """ + Extract coefficients of iteration variables from index expression. + """ + coefficients: OrderedSet = OrderedSet() + for var in used_vars: + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(index, var) + stride = BlockPatternMatcher.match_affine_block_expr(var_expr, var) + if stride is None: + stride = 1 # Variable without explicit coefficient has stride 1 + coef = self._safe_int(stride) + coefficients.add(coef if coef is not None else stride) + return coefficients + + def _check_gather_pattern( + self, + buf_size: list, + actual_strides: list, + is_contiguous: bool, + coefficients: OrderedSet, + ) -> bool: + """ + Check if access pattern requires gather (non-standard striding). + """ + expected_strides = [1] # 1D buffers have stride 1 + + if len(buf_size) > 1: + expected_stride = 1 + expected_strides = [] + for i in range(len(buf_size) - 1, -1, -1): + expected_strides.insert(0, expected_stride) + dim_size = self._safe_int(buf_size[i]) + if dim_size is not None: + expected_stride *= dim_size + + if is_contiguous: + # Buffer is contiguous - check if access coefficients match expected strides + expected_stride_set = OrderedSet(expected_strides) + for coef in coefficients: + if coef not in expected_stride_set: + return True + else: + # Buffer is NOT contiguous (strided input) + # Check if coefficients match actual buffer strides + actual_stride_set = OrderedSet(s for s in actual_strides if s is not None) + for coef in coefficients: + if coef not in actual_stride_set: + return True + + return False + + def _needs_strided_indexing( + self, + name: str, + index: sympy.Expr, + indexing: _BufferIndexing, + ) -> _BufferIndexing: + """Check if buffer access needs strided indexing due to size mismatch or gather patterns.""" + # Only applies when full array access is indicated + if indexing.index_str != "..." or indexing.needs_flatten: + return indexing + + info = self._get_buffer_info(name) + if info is None: + return indexing + + buf_obj, buf_size, buf_numel, actual_strides, is_contiguous = info + output_numel, used_vars = self._compute_output_numel_from_index(index) + all_iter_vars = self._get_iter_vars() + coefficients = self._get_index_coefficients(index, used_vars) + + # Check for gather pattern + has_non_unit_strides = self._check_gather_pattern( + buf_size, actual_strides, is_contiguous, coefficients + ) + + # Check for im2col-like pattern (more iter vars used than buffer dims) + buf_effective_dims = sum(1 for s in buf_size if self._safe_int(s) != 1) + not_all_vars_used = ( + len(used_vars) < len(all_iter_vars) + and len(used_vars) > 0 + and buf_effective_dims > 1 + and len(used_vars) > len(buf_size) + ) + + # Check various conditions for skipping strided indexing + is_tpu = V.graph.get_current_device_or_throw().type == "tpu" + is_known_non_contiguous = not is_contiguous and all( + s is not None for s in actual_strides + ) + has_symbolic_coef = any(not isinstance(c, int | float) for c in coefficients) + skip_for_non_contiguous = ( + is_known_non_contiguous and not is_tpu and buf_numel == output_numel + ) + + # Determine if strided indexing is needed + if ( + output_numel > 0 + and (buf_numel != output_numel or not_all_vars_used or has_non_unit_strides) + and len(used_vars) > 0 + and not skip_for_non_contiguous + and not has_symbolic_coef + ): + return _BufferIndexing( + index_str=self._generate_strided_index(index), needs_flatten=True + ) + + return indexing + + def _adjust_index_for_buffer_shape( + self, + name: str, + index: sympy.Expr, + indexing: _BufferIndexing, + ) -> _BufferIndexing: + """ + Adjust index expression based on buffer shape (0-dim scalar, multi-dim, etc.). + """ + if indexing.needs_flatten or indexing.index_str == "...": + return indexing + + buf_obj = V.graph.get_buffer(name) + if buf_obj is None: + return indexing + + buf_size = buf_obj.get_size() + + if len(buf_size) == 0: + return _BufferIndexing( + index_str="...", needs_flatten=indexing.needs_flatten + ) + + # if buffer size is 1, and index is an integer, use "..." + if ( + len(buf_size) == 1 + and buf_size[0] == 1 + and not self._has_iteration_vars(index) + ): + return _BufferIndexing( + index_str="...", needs_flatten=indexing.needs_flatten + ) + + # Multi-dimensional buffer with constant/scalar index + if len(buf_size) > 1: + has_iter_vars = self._has_iteration_vars(index) + if not has_iter_vars: + return _BufferIndexing( + index_str=indexing.index_str, needs_flatten=True + ) # Use flattened access + elif "::" in indexing.index_str: + # Strided slice patterns need flattened indexing for multi-dim + return _BufferIndexing( + index_str=self._generate_strided_index(index), needs_flatten=True + ) + + # GPU doesn't support gather from slice patterns on 1D buffers + if self.is_gpu and "::" in indexing.index_str: + return _BufferIndexing( + index_str=self._generate_strided_index(index), needs_flatten=True + ) + + return indexing + + def _try_multidim_slice( + self, + name: str, + index: sympy.Expr, + indexing: _BufferIndexing, + ) -> _BufferIndexing: + """ + Try to emit multi-dim slice notation instead of flatten + gather. + + For a buffer with shape (d0, ..., dk) and index `stride * var + offset`, + emit `buf[:, ..., :, offset::stride]` when stride divides dk. + """ + if not indexing.needs_flatten: + return indexing + + buf_obj = V.graph.get_buffer(name) + if buf_obj is None: + return indexing + + buf_size = buf_obj.get_size() + ndim = len(buf_size) + if ndim < 2: + return indexing + + # Need a single iteration variable with an affine index + used_vars = self._get_used_iter_vars(index) + if len(used_vars) != 1: + return indexing + + var = next(iter(used_vars)) + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(index, var) + stride = self._safe_int( + BlockPatternMatcher.match_affine_block_expr(var_expr, var) + ) + if stride is None or stride <= 1: + return indexing + + offset = V.graph.sizevars.simplify(index - var_expr) + try: + offset_val = int(offset) + except (TypeError, ValueError): + return indexing + + if offset_val < 0 or offset_val >= stride: + return indexing + + last_dim = self._safe_int(buf_size[-1]) + if last_dim is None or last_dim % stride != 0: + return indexing + + # Verify the iteration variable covers all buffer elements at the + # given stride: var_length * stride == buf_numel. This ensures + # the flattened stride-access 0, stride, 2*stride, ... maps exactly + # to buf[:, ..., :, offset::stride]. + entry = self.range_tree_nodes.get(var) + if entry is None: + return indexing + var_length = self._safe_int(entry.length) + buf_numel = 1 + for s in buf_size: + d = self._safe_int(s) + if d is None: + return indexing + buf_numel *= d + if var_length is None or var_length * stride != buf_numel: + return indexing + + prefix = ":, " * (ndim - 1) + if offset_val == 0: + slice_str = f"{prefix}::{stride}" + else: + slice_str = f"{prefix}{offset_val}::{stride}" + return _BufferIndexing(index_str=slice_str, needs_flatten=False) + + @staticmethod + def _gather_permute_expr(load_expr: str, perm: tuple[int, ...]) -> str: + """Generate gather-based permutation instead of jnp.permute_dims. + + Avoids a Mosaic compiler bug where jnp.permute_dims produces + corrupted output tensors on TPU for 3D+ arrays. Uses + pallas_permute which flattens to 1D and does a 1D gather. + """ + return f"pallas_permute({load_expr}, {perm})" + + def _trace_to_load_source(self, var_name: str) -> str | None: + """Trace a tmp variable back to its source buffer's kernel param. + + Follows CSE assignments backward through bounds-checking (where/clamp) + until it finds a variable that was directly loaded from a buffer. + """ + if var_name in self._cse_to_param: + return self._cse_to_param[var_name] + for line in self.compute._lines: + line_str = str(line).lstrip() + if not line_str.startswith(f"{var_name} = "): + continue + for ref in re.findall(r"\btmp\d+\b", line_str.split(" = ", 1)[1]): + result = self._trace_to_load_source(ref) + if result is not None: + return result + return None + + def _detect_indirect_access( + self, buf: str, name: str, index: sympy.Expr + ) -> _IndirectAccessInfo | None: + """Detect a load with data-dependent indexing suitable for scalar prefetch. + + Matches exactly one indirect variable whose coefficient corresponds to + a C-contiguous stride dimension. Rejects 1-to-1 gather patterns where + the indices buffer covers the full iteration space. + """ + buf_info = self._get_buffer_info(name) + if buf_info is None: + return None + _, buf_size, _, _, _ = buf_info + buf_size_raw = [self._safe_int(s) for s in buf_size] + if len(buf_size_raw) < 2 or any(s is None for s in buf_size_raw): + return None + buf_size_ints: list[int] = cast(list[int], buf_size_raw) + + indirect_vars = self._get_indirect_vars(index) + if len(indirect_vars) != 1: + return None + indirect_var = indirect_vars[0] + + coeff = self._get_index_coefficient(index, indirect_var) + if coeff == 0 or not isinstance(coeff, int): + return None + + # Use existing stride mapping to find which dimension is indirected + strides = self._c_contiguous_strides(buf_size_ints) + mapping = self._map_coeffs_to_dims([coeff], strides) + if mapping is None: + return None + indirect_dim = mapping[0] + + ndim = len(buf_size_ints) + if indirect_dim >= max(1, ndim - 2): + return None + + indirect_var_name = str(indirect_var) + indices_param = self._trace_to_load_source(indirect_var_name) + if indices_param is None: + return None + + # Reject gather patterns: only 1-D static index tensors supported + indices_graph_name = self._param_to_graph_name.get(indices_param) + if indices_graph_name is not None: + indices_info = self._get_buffer_info(indices_graph_name) + if indices_info is not None: + _, indices_size, _, _, _ = indices_info + if len(indices_size) != 1: + return None + if self._safe_int(indices_size[0]) is None: + return None + indices_numel = math.prod( + v for s in indices_size if (v := self._safe_int(s)) is not None + ) + iter_product = math.prod( + length + for var in self._get_used_iter_vars(index) + if var in self.range_tree_nodes + if (length := self._safe_int(self.range_tree_nodes[var].length)) + is not None + ) + if indices_numel >= iter_product: + return None + + return _IndirectAccessInfo( + table_param=buf, + table_buf_name=name, + table_shape=tuple(buf_size_ints), + indirect_dim=indirect_dim, + indirect_var=indirect_var_name, + indices_param=indices_param, + ) + + def _eliminate_dead_indirect_code(self) -> None: + """Remove dead compute lines after scalar prefetch replaces indirect load. + + When the table load is simplified to buf[0] (scalar prefetch handles + indexing), the indices load and all derived bounds-checking code become + dead. This performs backward liveness analysis from the store variables + to identify and remove dead lines. + """ + # Collect variables used by stores (live roots) + live_vars: OrderedSet[str] = OrderedSet() + for _, store_line in self.store_with_output: + for m in re.finditer(r"\btmp\d+\b", store_line): + live_vars.add(m.group()) + + # Parse assignments from compute lines + assignments: list[tuple[str | None, str, Any]] = [] + for line in self.compute._lines: + line_str = str(line).lstrip() + m = re.match(r"^(tmp\d+)\s*=\s*(.*)", line_str, re.DOTALL) + if m: + assignments.append((m.group(1), m.group(2), line)) + else: + assignments.append((None, line_str, line)) + + # Propagate liveness backward + changed = True + while changed: + changed = False + for var_name, rhs, _ in reversed(assignments): + if var_name and var_name in live_vars: + for m in re.finditer(r"\btmp\d+\b", rhs): + if m.group() not in live_vars: + live_vars.add(m.group()) + changed = True + + # Keep only live assignments (and non-assignment lines) + self.compute._lines = [ + line + for var_name, _, line in assignments + if var_name is None or var_name in live_vars + ] + + def _build_load_expr( + self, + buf: str, + name: str, + index: sympy.Expr, + indexing: _BufferIndexing, + ) -> str: + """ + Build the load expression based on indexing mode. + """ + if indexing.needs_flatten: + # Detect indirect (data-dependent) access for scalar prefetch + indirect = self._detect_indirect_access(buf, name, index) + if indirect is not None: + if self.indirect_access is not None: + # Fused nodes may re-visit the same indirect load (e.g. + # a reduction + pointwise over the same embedding). + # Allow that, but reject truly different indirect accesses. + if indirect != self.indirect_access: + raise AssertionError( + "only one indirect access per kernel supported" + ) + self.indirect_access = indirect + return f"{buf}[0]" + + self.has_flatten_indexing = True + self.flatten_indexed_buffers.add(name) + # Flatten then index for non-contiguous access (gather operation) + has_minmax = index.has(sympy.Min, sympy.Max, TorchMin, TorchMax) + idx_dtype = "jnp.int32" if self.is_tpu else "jnp.int64" + idx = ( + f"({indexing.index_str}).astype({idx_dtype})" + if has_minmax + else indexing.index_str + ) + return f"{buf}[...].flatten()[{idx}]" + else: + # Direct indexing for contiguous access + load_expr = f"{buf}[{indexing.index_str}]" + + if indexing.index_str == "..." and not self.is_gpu: + perm = self._get_full_load_permutation(name, index) + if perm is not None: + load_expr = self._gather_permute_expr(load_expr, perm) + self.permuted_input_buffers[name] = perm + else: + collapsed = self._get_collapsed_load_permutation(name, index) + if collapsed is not None: + collapsed_shape, cperm = collapsed + load_expr = f"jnp.permute_dims({load_expr}, {cperm})" + # Don't store cperm in permuted_input_buffers as it's for the reshaped tensor + # not the original shape, which causes issues later when used for tiling + self.collapsed_reshape_inputs[name] = collapsed_shape + self.collapsed_output_shape = tuple( + collapsed_shape[p] for p in cperm + ) + + return load_expr + + def _maybe_squeeze_intermediate_buffer(self, name: str, load_expr: str) -> str: + """ + Squeeze (N,1) intermediate buffers when kernel has 1D graph inputs. + + This avoids wrong broadcasting: (N,) op (N,1) -> (N,N) instead of (N,) + """ + if not name.startswith("buf"): + return load_expr + + # Check if any input buffer is a 1D graph input + has_1d_input = any( + not buf_name.startswith("buf") + and (buf_obj := V.graph.get_buffer(buf_name)) is not None + and len(buf_obj.get_size()) == 1 + for buf_name in self.args.input_buffers + ) + + if has_1d_input: + buf_obj = V.graph.get_buffer(name) + if buf_obj is not None: + buf_size = buf_obj.get_size() + if len(buf_size) == 2 and buf_size[-1] == 1: + return f"jnp.squeeze({load_expr}, axis=-1)" + + return load_expr + + def _maybe_broadcast_1d_buffer( + self, name: str, index: sympy.Expr, load_expr: str + ) -> str: + """Reshape 1D buffers for higher-dim broadcasting in reduction kernels. + + When a 1D buffer (e.g. a reduction result from a prior kernel, or a + batch-norm parameter) is loaded into a kernel with 2+ iteration dims, + JAX right-aligns it for broadcasting: (N,) becomes (1, N). This is + wrong when the buffer corresponds to a non-trailing axis; we reshape + to (N, 1, ...) so broadcasting matches the correct axis. + """ + buf_obj = V.graph.get_buffer(name) + if buf_obj is None or len(buf_obj.get_size()) != 1: + return load_expr + + # Only graph inputs, not intermediate buffers — intermediates are + # already shaped by the IR and their dim order may not match the + # reference buffer used below for axis inference. + if name.startswith("buf"): + return load_expr + + buf_length = self._safe_int(buf_obj.get_size()[0]) + if buf_length is None: + return load_expr + + dtype = V.graph.get_dtype(name) + if dtype is not None and not dtype.is_floating_point: + return load_expr + + # Find a higher-dimensional reference buffer + ref_buf_size = None + for buf_name in self.args.input_buffers: + other_buf = V.graph.get_buffer(buf_name) + if other_buf is not None and len(other_buf.get_size()) > 1: + ref_buf_size = [self._safe_int(s) for s in other_buf.get_size()] + if all(s is not None for s in ref_buf_size): + break + ref_buf_size = None + if ref_buf_size is None or len(ref_buf_size) <= 1: + return load_expr + + # Must use exactly one iteration variable + used_vars = self._get_used_iter_vars(index) + if len(used_vars) != 1: + return load_expr + used_var = next(iter(used_vars)) + if used_var not in self.range_tree_nodes: + return load_expr + + # Verify buffer length matches variable length + entry = self.range_tree_nodes[used_var] + if self._safe_int(entry.length) != buf_length: + return load_expr + + # Buffer length must uniquely match one non-reduction iteration variable. + # If multiple pointwise vars share the same length (e.g. 2D pointwise + # kernel with both dims equal), the axis is ambiguous and we bail out. + matching_vars = [ + v + for v, e in self.range_tree_nodes.items() + if self._safe_int(e.length) == buf_length and not e.is_reduction + ] + if len(matching_vars) != 1: + return load_expr + + # Determine axis position from the iteration variable's position + # in the range tree (pointwise vars first, then reduction vars). + axis_pos = None + matching_dims = [i for i, s in enumerate(ref_buf_size) if s == buf_length] + if len(matching_dims) == 1: + axis_pos = matching_dims[0] + else: + # Ambiguous by size (e.g. square tensor with reduction). + # Use the variable's position in the range tree. + pw_idx = 0 + for sym, e in self.range_tree_nodes.items(): + if sym == used_var: + axis_pos = pw_idx + break + if not e.is_reduction: + pw_idx += 1 + + if axis_pos is None: + return load_expr + if axis_pos == len(ref_buf_size) - 1: + return load_expr # Last dim uses default broadcasting + + reshape_dims = [1] * len(ref_buf_size) + reshape_dims[axis_pos] = -1 + return f"{load_expr}.reshape({', '.join(map(str, reshape_dims))})" + + def _check_im2col_pattern( + self, index: sympy.Expr, indexing: _BufferIndexing + ) -> _BufferIndexing: + """ + Check for im2col-like patterns where store uses block variables but load doesn't. + + For cat/expand patterns, both load and store prepared indices share block vars. + For im2col patterns, store compresses to block vars but load doesn't. + """ + if indexing.index_str != "..." or indexing.needs_flatten: + return indexing + + prepared_index = self.prepare_indexing(index) + iter_vars = self._get_iter_vars() + store_orig_vars = self._get_used_iter_vars(index) + store_prep_vars = ( + prepared_index.free_symbols + if hasattr(prepared_index, "free_symbols") + else OrderedSet() + ) & iter_vars + new_vars = store_prep_vars - store_orig_vars + + # Only trigger if store introduces new block vars + if not new_vars or len(store_orig_vars) <= 1: + return indexing + + # Check if loads are compatible with broadcast or cat pattern + has_im2col_pattern = False + for buf_name, load_index in self.load_index_exprs.items(): + load_orig_vars = self._get_used_iter_vars(load_index) + if not load_orig_vars: + continue + + # Load has iteration variables + if load_orig_vars != store_orig_vars: + continue + + # Same vars - check if load gets compressed too + prep_load = self.prepare_indexing(load_index) + load_prep_vars = ( + prep_load.free_symbols + if hasattr(prep_load, "free_symbols") + else OrderedSet() + ) & iter_vars + + # If store compresses but load doesn't, check for strided input vs im2col + if load_orig_vars != load_prep_vars or store_prep_vars == store_orig_vars: + continue + + # Check if load coefficients match buffer strides + if not self._check_load_is_strided_input( + buf_name, load_index, load_orig_vars + ): + has_im2col_pattern = True + break + + if has_im2col_pattern: + return _BufferIndexing( + index_str=self._generate_strided_index(prepared_index), + needs_flatten=True, + ) + + return indexing + + def _check_load_is_strided_input( + self, buf_name: str, load_index: sympy.Expr, load_orig_vars: OrderedSet + ) -> bool: + """ + Check if load coefficients match buffer strides (strided input vs im2col). + """ + buf = V.graph.get_buffer(buf_name) + if buf is None: + return False + + layout = getattr(buf, "get_layout", lambda: None)() + if layout is None: + return False + + buf_strides = getattr(layout, "stride", None) + if buf_strides is None: + return False + + buf_sizes = buf.get_size() + + # Get load coefficients + load_coeffs = [] + for var in load_orig_vars: + var_expr = BlockPatternMatcher.get_subexpr_involving_symbol(load_index, var) + coef = BlockPatternMatcher.match_affine_block_expr(var_expr, var) + if coef is not None: + int_coef = self._safe_int(coef) + load_coeffs.append(int_coef if int_coef is not None else coef) + + # Check if coefficients match buffer strides + # Only include strides for non-trivial dimensions (size > 1) + buf_stride_set = OrderedSet() + for i, s in enumerate(buf_strides): + dim_size = self._safe_int(buf_sizes[i]) + if dim_size is None or dim_size > 1: + int_s = self._safe_int(s) + buf_stride_set.add(int_s if int_s is not None else s) + + return OrderedSet(load_coeffs) == buf_stride_set + + def _check_store_needs_transpose(self, name: str) -> bool: + """ + Check if output needs transpose for column-major storage. + + Transpose on store is needed when: + - Output has column-major stride (s0 < s1) + - But input(s) have row-major stride + - And we haven't already transposed on load + """ + if self.permuted_input_buffers: + return False + + info = self._get_buffer_info(name) + if info is None: + return False + + _, buf_size, _, actual_strides, _ = info + if len(actual_strides) != 2 or len(buf_size) != 2: + return False + + size0 = self._safe_int(buf_size[0]) + size1 = self._safe_int(buf_size[1]) + s0 = actual_strides[0] + s1 = actual_strides[1] + + # Check if output is column-major with valid dimensions + if not ( + s0 is not None + and s1 is not None + and s0 < s1 + and size0 is not None + and size1 is not None + and size0 > 1 + and size1 > 1 + ): + return False + + # Check if any input is column-major (if so, no transpose needed) + for inp_name in self.args.input_buffers: + inp_info = self._get_buffer_info(inp_name) + if inp_info is None: + continue + _, _, _, inp_strides, _ = inp_info + if len(inp_strides) != 2: + continue + inp_s0 = inp_strides[0] + inp_s1 = inp_strides[1] + if inp_s0 is not None and inp_s1 is not None and inp_s0 < inp_s1: + return False # Input is also column-major + + return True + + def _build_full_array_store_expr( + self, out: str, value: CSEVariable, needs_transpose: bool + ) -> list[str]: + """ + Build store expression for full array assignment. + + Handles scalar broadcast, shape matching, and optional transpose. + Returns a list of lines to emit (variable assignment + store). + """ + lines = [f"_val = jnp.asarray({value})"] + if needs_transpose: + lines.append( + f"{out}[...] = " + f"jnp.full({out}.shape, _val) if _val.ndim == 0 " + f"else jnp.transpose(_val)" + ) + else: + lines.append( + f"{out}[...] = " + f"jnp.full({out}.shape, _val) if _val.ndim == 0 " + f"else (_val.reshape({out}.shape) if _val.size == {out}.size " + f"else jnp.broadcast_to(_val, {out}.shape))" + ) + return lines + + def _build_store_expr( + self, + out: str, + name: str, + index: sympy.Expr, + value: CSEVariable, + indexing: _BufferIndexing, + mode: Any = None, + ) -> list[str]: + """ + Build the store expression based on indexing mode. + mode can be None (set) or "atomic_add" (accumulate). + Returns a list of lines to emit. + """ + if indexing.index_str == "...": + # Full array store with shape matching + needs_transpose = self._check_store_needs_transpose(name) + return self._build_full_array_store_expr(out, value, needs_transpose) + + if indexing.needs_flatten: + self.has_flatten_indexing = True + # Block variable indexing (e.g., im2col) - use flattened scatter + scatter_op = "add" if mode == "atomic_add" else "set" + return [ + f"{out}[...] = {out}[...].flatten().at[jnp.asarray({indexing.index_str}).flatten()].{scatter_op}(" + f"jnp.asarray({value}).flatten()).reshape({out}.shape)" + ] + + # Direct indexed assignment + has_indirect = self._has_indirect_vars(index) + buf = V.graph.get_buffer(name) + + if buf is not None: + buf_size = buf.get_size() + if len(buf_size) > 1 and not self._has_iteration_vars(index): + # Multi-dim output with constant index - use [...] for full assignment + return self._build_full_array_store_expr(out, value, False) + + if has_indirect: + # Indirect indexed store (scatter): use .add() for atomic_add, .set() otherwise + scatter_op = "add" if mode == "atomic_add" else "set" + lines = [f"_val = jnp.asarray({value})"] + value_expr = f"(jnp.full({indexing.index_str}.shape, _val) if _val.ndim == 0 else {value})" + if mode == "atomic_add": + # For atomic_add, mark output as needing to be readable (for aliasing) + self.outputs_need_read.add(out) + alias_param = f"{out}_alias" + lines.append( + f"{out}[...] = {alias_param}[...].flatten().at[jnp.asarray({indexing.index_str}).flatten()].{scatter_op}(" + f"jnp.asarray({value_expr}).flatten()).reshape({out}.shape)" + ) + else: + lines.append(f"{out}[{indexing.index_str}] = {value_expr}") + return lines + + return [f"{out}[{indexing.index_str}] = {value}"] + + def _build_scatter_store_expr( + self, + out: str, + value: CSEVariable, + scatter_info: dict[str, Any], + name: str, + mode: Any, + ) -> str: + """Build store expression for scatter operations (indirect indexing).""" + is_point_scatter = scatter_info.get("is_point_scatter", False) + + # Mark this output parameter as needing to be readable (for aliasing) + self.outputs_need_read.add(out) + alias_param = f"{out}_alias" + + # Use .add() for atomic_add mode, .set() otherwise + scatter_op = "add" if mode == "atomic_add" else "set" + + if is_point_scatter: + # Single-element scatter + indirect_var = scatter_info["indirect_var"] + indirect_dim = scatter_info["indirect_dim"] + output_shape = scatter_info["output_shape"] + + # Build index tuple with 0s for other dimensions + index_parts = [] + for dim in range(len(output_shape)): + if dim == indirect_dim: + index_parts.append(indirect_var) + else: + index_parts.append("0") + + index_tuple = ", ".join(index_parts) + return f"{out}[...] = {alias_param}[...].at[{index_tuple}].{scatter_op}({value})" + + # Scatter with iteration variables + indirect_var = scatter_info["indirect_var"] + dims_before = scatter_info["dims_before"] + dims_after = scatter_info["dims_after"] + + # Determine if element-wise or slice-based scatter + buf = V.graph.get_buffer(name) + output_ndim = len(buf.get_size()) if buf is not None else 0 + + num_iter_vars_in_store = len(dims_before) + len(dims_after) + total_kernel_iter_vars = len(self.range_tree_nodes) + remaining_dims = output_ndim - 1 # dims other than indirect + + is_element_wise = ( + num_iter_vars_in_store == remaining_dims + and num_iter_vars_in_store == total_kernel_iter_vars + ) + + if is_element_wise: + # Element-wise scatter: use iteration variable names + index_parts = [var_name for var_name, size in dims_before] + + # Reshape indirect var for broadcasting if needed + n_leading = len(dims_before) + n_trailing = len(dims_after) + if n_leading > 0 and n_trailing > 0: + leading_ones = "None, " * n_leading + trailing_nones = ", None" * n_trailing + indirect_reshaped = f"{indirect_var}[{leading_ones}...{trailing_nones}]" + else: + indirect_reshaped = indirect_var + index_parts.append(indirect_reshaped) + + index_parts.extend(var_name for var_name, size in dims_after) + else: + # Slice-based scatter: use : for iteration dimensions + index_parts = [":" for _ in dims_before] + index_parts.append(indirect_var) + index_parts.extend(":" for _ in dims_after) + + index_tuple = ", ".join(index_parts) + return ( + f"{out}[...] = {alias_param}[...].at[{index_tuple}].{scatter_op}({value})" + ) + + @typing_extensions.override + def load(self, name: str, index: sympy.Expr) -> CSEVariable: + buf = self.args.input(name) + dtype = V.graph.get_dtype(name) + + # Track the load index expression for argmax/argmin axis detection + self.load_index_exprs[name] = index + + # Get base index expression + indexing = self._get_index_expr(index) + + # Check for buffer size mismatch requiring strided indexing + indexing = self._needs_strided_indexing(name, index, indexing) + + # Try strided decomposition before multidim slice or flatten. + # This generates reshape + static indexing which works on both + # CPU and TPU (unlike slice notation which fails on Mosaic). + decomp = self._decompose_strided_access(index, name) + if decomp is not None: + self.strided_input_buffers[name] = decomp + load_expr = self._strided_load_expr(buf, decomp) + else: + # Adjust index for buffer shape (scalar, multi-dim, etc.) + indexing = self._adjust_index_for_buffer_shape(name, index, indexing) + + # Try to emit multi-dim slice instead of flatten + gather + indexing = self._try_multidim_slice(name, index, indexing) + + # Build the load expression + load_expr = self._build_load_expr(buf, name, index, indexing) + + # Handle intermediate buffer squeezing for correct broadcasting + if not indexing.needs_flatten and indexing.index_str == "...": + load_expr = self._maybe_squeeze_intermediate_buffer(name, load_expr) + # Handle 1D buffer broadcasting for higher-dimensional kernels + load_expr = self._maybe_broadcast_1d_buffer(name, index, load_expr) + + cse_var = self.cse.generate( + self.compute, + load_expr, + dtype=dtype, + ) + # Track CSE var -> param -> graph name for indirect access detection + buf_param = self.args.input(name) + self._cse_to_param[str(cse_var)] = buf_param + self._param_to_graph_name[buf_param] = name + return cse_var + + def _handle_mixed_indexing(self, index: sympy.Expr) -> str: + """ + Handle indexing with both indirect variables and iteration variables. + + For example, x[indices, :] generates index = i0 + stride * tmp0 + where tmp0 is loaded from indices and i0 is the iteration variable. + + We need to convert this to JAX advanced indexing with proper broadcasting. + When there are multiple iteration variables, they need different shapes + to form an outer product (grid) rather than broadcasting together. + + Special case: For gather operations where a single iteration variable + and single indirect variable have the same extent, they should be + element-wise aligned, not broadcast into an outer product. + + PyTorch advanced indexing semantics: When multiple indirect indices have + the same shape, they are paired element-wise (not outer product), and + the combined result dimension appears at the FRONT of the output. + """ + used_iter_vars_set = self._get_used_iter_vars(index) + + # Track which iteration variables are used + self.used_iter_vars.update(used_iter_vars_set) + + if len(used_iter_vars_set) == 0: + return self.kexpr(index) + + # Sort iteration variables by their coefficient (stride) in the index expression. + # Variables with larger strides correspond to earlier output dimensions. + # Use inf default so symbolic coefficients sort as outermost dimensions. + def _coeff(var): + return self._get_index_coefficient(index, var, default=float("inf")) + + used_iter_vars = sorted(used_iter_vars_set, key=_coeff, reverse=True) + iter_coeffs = [_coeff(var) for var in used_iter_vars] + + # Rename symbolic sizes to kernel parameter names + index_str = self.kexpr(self.rename_indexing(index)) + indirect_var_syms = self._get_indirect_vars(index) + indirect_vars = [str(sym) for sym in indirect_var_syms] + + # Get coefficients for indirect vars to determine output ordering + indirect_coeffs = {str(s): _coeff(s) for s in indirect_var_syms} + + # Special case: reduction var + single indirect var = element-wise gather + # Reduction vars (r prefix) iterate over the reduction dimension, and when paired + # with an indirect var, both are aligned to that dimension (element-wise). + # Pointwise vars form output dimensions and need the complex reshape code. + if len(used_iter_vars) == 1 and len(indirect_vars) == 1: + var = used_iter_vars[0] + var_name = str(var) + is_reduction_var = ( + var in self.range_tree_nodes and self.range_tree_nodes[var].is_reduction + ) + + if is_reduction_var: + # Reduction var: simple element-wise gather + if var in self.range_tree_nodes: + range_entry = self.range_tree_nodes[var] + range_size = range_entry.length + # Rename to use kernel parameter names for symbolic sizes + renamed_size = self.rename_indexing(range_size) + arange_expr = f"jnp.arange({self.kexpr(renamed_size)})" + index_str = index_str.replace(var_name, arange_expr) + return index_str + # For pointwise vars, fall through to the complex reshape code + + # Check if multiple indirect vars should be paired element-wise. + # In PyTorch, when multiple advanced indices have the same shape, they pair up. + # The paired dimension goes to the FRONT of the output. + # However, if indirect vars have different shapes (e.g., (1,4) and (4,1)), + # they form an outer product instead. + # We detect element-wise pairing when: + # 1. Multiple indirect vars exist + # 2. There's exactly ONE unused iteration variable (for the shared paired dim) + # For outer product, there are MULTIPLE unused iter vars (one per indirect dim) + paired_indirect = False + if len(indirect_vars) > 1: + # Count unused iteration variables (defined but not in index expression) + unused_iter_vars = self._get_iter_vars() - used_iter_vars_set + # Element-wise pairing: one unused iter var for the shared paired dimension + # Outer product: multiple unused iter vars (one for each indirect var dimension) + paired_indirect = len(unused_iter_vars) == 1 + + if paired_indirect: + # Multiple indirect vars with element-wise pairing + # Output order: (paired_indirect_dim, iter_var_dims...) + # All indirect vars get the same shape: (N, 1, 1, ...) for first dim + # Iter vars come after: second dim onwards + + # Count total output dims: 1 (paired) + len(iter_vars) for non-newaxis + # But some iter vars may be for newaxis dimensions (size 1) + n_output_dims = 1 + len(used_iter_vars) + + # Reshape indirect vars to occupy the first dimension + for indirect_var in indirect_vars: + trailing_ones = ", 1" * len(used_iter_vars) + reshape_expr = f"{indirect_var}.reshape(-1{trailing_ones})" + index_str = index_str.replace(indirect_var, reshape_expr) + + # Reshape iteration variables to occupy subsequent dimensions + # Sort by coefficient (descending) to determine order + for i, var in enumerate(used_iter_vars): + var_name = str(var) + if var in self.range_tree_nodes: + range_entry = self.range_tree_nodes[var] + range_size = range_entry.length + # Rename to use kernel parameter names for symbolic sizes + renamed_size = self.rename_indexing(range_size) + + # Shape: (1, ..., N, ..., 1) where N is at position i+1 + # Position 0 is for paired indirect vars + shape_parts = ["1"] * n_output_dims + shape_parts[i + 1] = self.kexpr(renamed_size) + shape_str = ", ".join(shape_parts) + arange_expr = ( + f"jnp.arange({self.kexpr(renamed_size)}).reshape({shape_str})" + ) + + index_str = index_str.replace(var_name, arange_expr) + + return index_str + + # Single indirect var case (or no indirect vars handled above) + # Build a sorted list of all components by coefficient (descending) + # Each component is (coeff, type, var) where type is 'iter' or 'indirect' + all_components = [] + for var in used_iter_vars: + all_components.append((_coeff(var), "iter", var)) + for sym in indirect_var_syms: + all_components.append((_coeff(sym), "indirect", sym)) + all_components.sort(key=lambda x: x[0], reverse=True) + + # Calculate trailing dims needed for each component + # Each component needs trailing dims for all subsequent iter vars + # plus trailing dims for all dimensions of subsequent indirect vars + # For simplicity, assume each indirect var contributes some dimensions + # that will be handled by the reshape at store time + + # For iter vars, we need to count how many dimensions come after in the output + for i, var in enumerate(used_iter_vars): + var_name = str(var) + if var in self.range_tree_nodes: + range_entry = self.range_tree_nodes[var] + range_size = range_entry.length + # Rename to use kernel parameter names for symbolic sizes + renamed_size = self.rename_indexing(range_size) + var_coeff = _coeff(var) + + arange_expr = f"jnp.arange({self.kexpr(renamed_size)})" + + # Count trailing dims needed: + # - One for each subsequent iter var (with smaller coeff) + # - One for each dimension of indirect vars with smaller coeff + # For indirect vars, assume each contributes 2 dims (common case) + # The actual reshape at store time will fix any shape mismatches + n_trailing_iter = sum(1 for c in iter_coeffs if c < var_coeff) + n_trailing_indirect = sum( + 2 for c in indirect_coeffs.values() if c < var_coeff + ) + n_trailing = n_trailing_iter + n_trailing_indirect + + if n_trailing > 0: + trailing_dims = ", None" * n_trailing + arange_expr = f"{arange_expr}[:{trailing_dims}]" + + index_str = index_str.replace(var_name, arange_expr) + + # Reshape indirect variables for proper broadcasting. + for indirect_var in indirect_vars: + indirect_coeff = indirect_coeffs[indirect_var] + + # Count dims needed before and after this indirect var + n_leading = sum(1 for c in iter_coeffs if c > indirect_coeff) + n_trailing = sum(1 for c in iter_coeffs if c < indirect_coeff) + + # Build the indexing expression with leading Nones, ellipsis, trailing Nones + if n_leading > 0 and n_trailing > 0: + leading_nones = "None, " * n_leading + trailing_nones = ", None" * n_trailing + reshape_expr = f"{indirect_var}[{leading_nones}...{trailing_nones}]" + elif n_leading > 0: + leading_nones = "None, " * n_leading + reshape_expr = f"{indirect_var}[{leading_nones}...]" + elif n_trailing > 0: + trailing_nones = ", None" * n_trailing + reshape_expr = f"{indirect_var}[...{trailing_nones}]" + else: + reshape_expr = indirect_var + + index_str = index_str.replace(indirect_var, reshape_expr) + + return index_str + + @typing_extensions.override + def store( + self, name: str, index: sympy.Expr, value: CSEVariable, mode: Any = None + ) -> None: + # mode can be None (set), "atomic_add" (accumulate), etc. + if mode is not None and mode != "atomic_add": + raise Unsupported(f"pallas store mode '{mode}' not supported") + out = self.args.output(name) + self.store_buffer_names.add(name) + + # Check if this is a scalar output (reduction to scalar) + buf = V.graph.get_buffer(name) + is_scalar = buf is not None and len(buf.get_size()) == 0 + + if is_scalar: + store_lines = [ + f"_val = jnp.asarray({value})", + f"{out}[...] = jnp.full({out}.shape, _val) if _val.ndim == 0 else _val.reshape({out}.shape)", + ] + else: + # When collapsed_output_shape is set, the load-side permutation + # already produces data in the correct layout for the collapsed + # output. Force a full-array store ("...") so the scatter index + # (which was computed for the original output layout) does not + # rearrange the permuted data. + if self.collapsed_output_shape is not None: + store_lines = self._build_full_array_store_expr(out, value, False) + else: + # Check for scatter pattern (indirect indexing for stores) + scatter_info = self._detect_scatter_pattern(index, name) + + if scatter_info is not None: + # Track iteration variables used in scatter index + self.used_iter_vars.update(self._get_used_iter_vars(index)) + store_lines = [ + self._build_scatter_store_expr( + out, value, scatter_info, name, mode + ) + ] + else: + # Get base index expression + indexing = self._get_index_expr(index) + + # Adjust index for buffer shape (scalar, multi-dim, etc.) + indexing = self._adjust_index_for_buffer_shape( + name, index, indexing + ) + + # Check for im2col-like patterns + indexing = self._check_im2col_pattern(index, indexing) + + # Build the store expression + store_lines = self._build_store_expr( + out, name, index, value, indexing, mode + ) + + for line in store_lines: + self.stores.writeline(line) + # Track which output param this store uses for filtering in codegen_kernel + self.store_with_output.append((out, line)) + + @staticmethod + def _get_index_coefficient( + index: sympy.Expr, var: sympy.Symbol, default: int | float = 0 + ) -> int | float: + """Get integer coefficient of a variable in an index expression.""" + coeff = index.coeff(var) + if coeff == 0: + coeff = sympy.diff(index, var) + try: + return int(coeff) + except (TypeError, ValueError): + return default + + def _detect_scatter_pattern( + self, index: sympy.Expr, output_name: str = "" + ) -> dict[str, Any] | None: + """Detect scatter operation pattern. Returns scatter info dict or None.""" + indirect_syms = self._get_indirect_vars(index) + if len(indirect_syms) != 1: + return None + + indirect_sym = indirect_syms[0] + indirect_var = str(indirect_sym) + indirect_coeff: int = int(self._get_index_coefficient(index, indirect_sym)) + if indirect_coeff == 0: + return None + + # Point scatter: no iteration variables, just indirect indexing + if not self._has_iteration_vars(index): + return self._detect_point_scatter(output_name, indirect_var, indirect_coeff) + + # Regular scatter: has both indirect and iteration variables + return self._detect_iter_scatter(index, indirect_var, indirect_coeff) + + def _detect_point_scatter( + self, output_name: str, indirect_var: str, indirect_coeff: int + ) -> dict[str, Any] | None: + """Detect single-element scatter pattern.""" + if not output_name: + return None + try: + buf = V.graph.get_buffer(output_name) + output_shape = [int(s) for s in buf.get_size()] + except Exception: + return None + + if len(output_shape) < 2: + return None + + # Find which dimension indirect var indexes based on coefficient + cumulative = 1 + indirect_dim = len(output_shape) - 1 + for dim in range(len(output_shape) - 1, -1, -1): + if indirect_coeff == cumulative: + indirect_dim = dim + break + cumulative *= output_shape[dim] + + return { + "indirect_var": indirect_var, + "indirect_dim": indirect_dim, + "dims_before": [], + "dims_after": [], + "is_point_scatter": True, + "output_shape": output_shape, + } + + def _detect_iter_scatter( + self, index: sympy.Expr, indirect_var: str, indirect_coeff: int + ) -> dict[str, Any] | None: + """Detect scatter pattern with iteration variables.""" + used_iter_vars = self._get_used_iter_vars(index) + + # Collect (var_name, coefficient, length) for each variable + all_vars: list[tuple[str, int, int]] = [] + for var in used_iter_vars: + coeff = int(self._get_index_coefficient(index, var)) + if coeff > 0 and var in self.range_tree_nodes: + length = self._safe_int(self.range_tree_nodes[var].length) + if length is None: + return None + all_vars.append((str(var), coeff, length)) + + all_vars.append((indirect_var, indirect_coeff, -1)) + all_vars.sort(key=lambda x: x[1], reverse=True) + + # Find indirect variable position + indirect_pos = next( + (i for i, (name, _, _) in enumerate(all_vars) if name == indirect_var), + None, + ) + if indirect_pos is None: + return None + + # Verify coefficients form valid stride pattern + expected = 1 + for _, coeff, length in reversed(all_vars[indirect_pos + 1 :]): + if coeff != expected: + return None + expected *= length + if indirect_coeff != expected: + return None + + return { + "indirect_var": indirect_var, + "indirect_dim": indirect_pos, + "dims_before": [(n, l) for n, _, l in all_vars[:indirect_pos]], + "dims_after": [(n, l) for n, _, l in all_vars[indirect_pos + 1 :]], + "is_point_scatter": False, + "output_shape": None, + } + + def reduction( + self, + dtype: torch.dtype, + src_dtype: torch.dtype, + reduction_type: ReductionType, + value: CSEVariable | tuple[CSEVariable, ...], + ) -> CSEVariable | tuple[CSEVariable, ...]: # type: ignore[override] + """ + Generate code for reduction operations in JAX/Pallas. + + Reductions in Pallas work by: + 1. Loading the input data into the kernel + 2. Applying JAX reduction operations (jnp.sum, jnp.max, etc.) + 3. Storing the reduced result + + The reduction happens over the loaded block of data. + """ + if not self.inside_reduction: + raise AssertionError("expected to be inside a reduction") + + # Handle welford_reduce using the fallback (computes via sum reductions) + if reduction_type == "welford_reduce": + return self.welford_reduce_fallback(dtype, value) + + if isinstance(value, tuple): + raise Unsupported( + "Tuple reductions (e.g., welford_combine) not supported in Pallas backend" + ) + + # Check if this reduction is already cached. + cache_key = (src_dtype, reduction_type, value) + if cache_key in self.cse.reduction_cache: + return self.cse.reduction_cache[cache_key] + + # Map reduction types to JAX functions + reduction_ops = { + "sum": "jnp.sum", + "prod": "jnp.prod", # CPU only - not supported in Pallas GPU (Mosaic) backend + "max": "jnp.max", + "min": "jnp.min", + "any": "jnp.any", + "argmax": "jnp.argmax", + "argmin": "jnp.argmin", + } + + # Determine if this is a partial reduction (has pointwise dimensions) + # or a full reduction to scalar + pointwise_prefixes = OrderedSet(["x", "y", "z"]) + has_pointwise = any(p in self.numels for p in pointwise_prefixes) + pointwise_numel: int | None = self._compute_prefix_numel(pointwise_prefixes) + reduction_numel: int | None = self._compute_reduction_numel() + n_reduction_dims = sum( + 1 for entry in self.range_tree_nodes.values() if entry.is_reduction + ) + + is_partial_reduction = ( + has_pointwise + and pointwise_numel is not None + and pointwise_numel > 1 + and reduction_numel + and n_reduction_dims > 0 + ) + is_symbolic_partial = ( + has_pointwise and n_reduction_dims > 0 and pointwise_numel is None + ) + + if reduction_type == "xor_sum": + if is_partial_reduction: + axes = self._get_reduction_axes() + axis_expr = axes[0] if len(axes) == 1 else axes + reduction_expr = f"jnp.bitwise_xor.reduce({value}, axis={axis_expr})" + else: + reduction_expr = f"jnp.bitwise_xor.reduce({value})" + elif reduction_type in ("argmax", "argmin"): + reduction_op = reduction_ops[reduction_type] + if is_partial_reduction: + # argmax/argmin only accept a single axis + axes = self._get_reduction_axes() + reduction_expr = f"{reduction_op}({value}, axis={axes[-1]})" + else: + reduction_expr = f"{reduction_op}({value})" + elif reduction_type in reduction_ops: + reduction_op = reduction_ops[reduction_type] + if is_partial_reduction: + axes = self._get_reduction_axes() + axis_expr = axes[0] if len(axes) == 1 else axes + reduction_expr = ( + f"{reduction_op}({value}, axis={axis_expr}, keepdims=True)" + ) + elif is_symbolic_partial: + # With symbolic shapes, strided loads produce a degenerate + # batch dim at axis=0 that just needs squeezing. + reduction_expr = f"{reduction_op}({value}, axis=0)" + else: + reduction_expr = f"{reduction_op}({value})" + else: + raise Unsupported( + f"Reduction type '{reduction_type}' not yet supported in Pallas backend. " + f"Supported types: {list(reduction_ops.keys())}, xor_sum" + ) + + # Generate CSE variable for the reduction result + result = self.cse.generate( + self.compute, + reduction_expr, + dtype=dtype, + ) + + # Cache the result + self.cse.reduction_cache[cache_key] = result + return result + + @staticmethod + def _buffer_is_contiguous(buffer_name: str) -> bool: + buf = V.graph.get_buffer(buffer_name) + layout = buf.get_layout() + return layout.is_contiguous() + + def _can_tile_cpu_tpu(self) -> bool: + """Check if this kernel can use tiling on CPU/TPU. + + Tiling is compatible with reductions, transpositions, and multi-range-tree + kernels as long as no flatten-based indexing is used (buf[...].flatten()[idx]). + Flatten indexing requires global flat indices which don't decompose into + per-tile local indices. + + Reject: + - GPU (has its own TMA / padding path) + - Flatten-based indexing + - Scatter outputs (indirect indexing complicates tile boundaries) + """ + if self.is_gpu: + return False + if self.has_flatten_indexing: + return False + if self.outputs_need_read: + return False + + # If iteration variables appear in the compute body (not just in + # load/store index resolution that collapses to [...]), tiling is + # unsafe because the arange-based vars have full-tensor shapes. + # Exception: vars emitted in tile-relative form are safe. + if self.used_iter_vars: + compute_text = "\n".join(str(line) for line in self.compute._lines) + for var_sym in self.used_iter_vars: + if var_sym in self.tile_relative_iter_vars: + continue + if str(var_sym) in compute_text: + return False + + # Determine the reference output shape (highest-ndim output). + out_bufs = list(self.args.output_buffers.keys()) + + # Only check the current kernel's actual output buffers for transpose, + # not _has_column_major_output() which scans all graph buffers and can + # be triggered by unrelated intermediates (e.g., (N,1) reductions with + # degenerate column-major strides). + has_col_major_out = False + for buf_name in out_bufs: + info = self._get_buffer_info(buf_name) + if info is None: + continue + _, buf_size, _, actual_strides, _ = info + if len(actual_strides) >= 2 and len(buf_size) >= 2: + s0 = actual_strides[0] + s1 = actual_strides[1] + d0 = self._safe_int(buf_size[0]) + d1 = self._safe_int(buf_size[1]) + if ( + s0 is not None + and s1 is not None + and s0 < s1 + and d0 is not None + and d1 is not None + and d0 > 1 + and d1 > 1 + ): + has_col_major_out = True + break + self.tile_has_transpose = bool(self.permuted_input_buffers) or has_col_major_out + + # Count trailing reduction dimensions in the output shape that must + # not be tiled (the kernel body needs the full reduction range). + # Only count when the kernel actually performs reduction (numel > 1). + reduction_numel = self._compute_reduction_numel() + has_reduction = reduction_numel is not None and reduction_numel > 1 + self.tile_skip_last_n = ( + sum(1 for tree in self.range_trees if tree.is_reduction) + if has_reduction + else 0 + ) + + ref_shape: list[int] = [] + for buf_name in out_bufs: + info = self._get_buffer_info(buf_name) + if info is None: + return False + _, buf_size, _, _, _ = info + int_size = [self._safe_int(s) for s in buf_size] + if any(s is None for s in int_size): + return False + if len(int_size) > len(ref_shape): + ref_shape = int_size # type: ignore[assignment] + + if not ref_shape: + return False + + # For collapsed permutation kernels, override ref_shape with the + # collapsed output shape so all compatibility checks operate in + # collapsed-shape space. + if self.collapsed_output_shape is not None: + ref_shape = list(self.collapsed_output_shape) + + ref_nd = len(ref_shape) + + all_bufs = list(self.args.input_buffers) + out_bufs + has_tileable = False + for buf_name in all_bufs: + info = self._get_buffer_info(buf_name) + if info is None: + return False + _, buf_size, _, _, _ = info + if len(buf_size) == 0: + continue # scalar + + # Use collapsed shapes when available so dimension checks + # operate in the same space as the kernel. + if buf_name in self.collapsed_reshape_inputs: + int_size = list(self.collapsed_reshape_inputs[buf_name]) + elif self.collapsed_output_shape is not None and buf_name in out_bufs: + int_size = list(self.collapsed_output_shape) + else: + int_size = [self._safe_int(s) for s in buf_size] + if any(s is None for s in int_size): + return False + buf_nd = len(int_size) + + if buf_nd == ref_nd: + # Same ndim: check dimensions match or are broadcast (1). + # Allow strided buffers (dims may differ after reshape). + is_strided = buf_name in self.strided_input_buffers + mismatch = False + for i in range(ref_nd): + if ( + int_size[i] == ref_shape[i] + or int_size[i] == 1 + or ref_shape[i] == 1 + or is_strided + ): + continue + mismatch = True + break + + if mismatch and buf_name in self.permuted_input_buffers: + perm = self.permuted_input_buffers[buf_name] + if not ( + len(perm) == ref_nd + and all( + int_size[perm[i]] == ref_shape[i] + or int_size[perm[i]] == 1 + or ref_shape[i] == 1 + for i in range(ref_nd) + ) + ): + return False + elif mismatch: + return False + + # At least one buffer with a tileable dim + if is_strided or any( + int_size[i] == ref_shape[i] and ref_shape[i] > 1 + for i in range(ref_nd) + ): + has_tileable = True + + elif buf_nd > ref_nd: + # Reduction input with extra dims. Find an alignment offset k + # such that buf_shape[k+i] == ref_shape[i] for all i (skipping + # broadcast dims where ref_shape[i] == 1). + found = False + for k in range(buf_nd - ref_nd + 1): + ok = True + for i in range(ref_nd): + if ref_shape[i] == 1: + continue + if int_size[k + i] != ref_shape[i]: + ok = False + break + if ok: + found = True + break + if not found: + return False + has_tileable = True + + else: + # Fewer dims: verify numpy-style broadcastability + for a, b in zip(reversed(int_size), reversed(ref_shape)): + if a != b and a != 1 and b != 1: + return False + + if not has_tileable: + return False + + # On CPU (interpret mode) each tile iteration has significant + # Python/JAX overhead, so cap the grid size. Store the cap + # so _codegen_tiled_specs can pass it to pallas_compute_tiling, + # which will scale up tiles to stay within the limit. + is_tpu = V.graph.get_current_device_or_throw().type == "tpu" + if not is_tpu: + self._cpu_max_grid_product = 64 + else: + self._cpu_max_grid_product = None + + return True + + def codegen_kernel(self, name: str | None = None) -> str: # type: ignore[override] + """ + Generate the complete Pallas kernel code as a Python string. + + This includes: + - Import statements for JAX/Pallas + - The kernel function that operates on refs + - The main wrapper function that handles PyTorch<->JAX conversions via DLPack + + Args: + name: Optional kernel name (will use placeholder if not provided) + + Returns: + str: Complete Python source code for the Pallas kernel + """ + code = IndentedBuffer() + + # Define the Pallas kernel: accepts refs, uses broadcasted expressions + arg_defs, call_args, _, _ = self.args.python_argdefs() + kernel_params = [a.name for a in arg_defs] + pure_out_params = [p for p in kernel_params if p.startswith("out_ptr")] + output_params = [ + p for p in kernel_params if p.startswith(("out_ptr", "in_out_ptr")) + ] + # Identify size variable parameters (scalars like load_seed_offset) + size_var_names = OrderedSet(self.args.sizevars.values()) + size_var_params = [p for p in kernel_params if p in size_var_names] + if not output_params: + raise RuntimeError("Pallas backend requires at least one output buffer") + + output_buffer_lookup = { + inner: outer + for outer, inner in self.args.output_buffers.items() + if isinstance(inner, str) + } + + kernel_name = name or "" + interpret_is_cpu = V.graph.get_current_device_or_throw().type == "cpu" + interpret_literal = "True" if interpret_is_cpu else "False" + + aliasable_flags: dict[str, bool] = {} + for param in pure_out_params: + aliasable_flags[param] = True + alias_params = [ + f"{param}_alias" for param in pure_out_params if aliasable_flags[param] + ] + pointer_tail = [ + p for p in kernel_params if p.startswith(("in_out_ptr", "in_ptr")) + ] + kernel_input_params = alias_params + pointer_tail + full_kernel_params = alias_params + kernel_params + non_alias_out_set = OrderedSet( + [name for name, flag in aliasable_flags.items() if not flag] + ) + # On CPU (interpret=True), pallas_call returns new arrays so we must + # copy back every output. On TPU, call_custom_kernel with + # input_output_aliases handles donation (zero-copy), so no copy is + # needed. On CUDA, aliased outputs are mutated in-place by the + # donated-buffer mechanism so only non-aliased outputs need a copy. + if interpret_is_cpu: + copy_output_indices = list(range(len(output_params))) + elif self.is_tpu: + copy_output_indices = [] + else: + copy_output_indices = [ + idx + for idx, name in enumerate(output_params) + if name in non_alias_out_set + ] + + ctx = _CodegenContext( + code=code, + kernel_name=kernel_name, + is_tpu=self.is_tpu, + interpret_is_cpu=interpret_is_cpu, + interpret_literal=interpret_literal, + kernel_params=kernel_params, + pure_out_params=pure_out_params, + output_params=output_params, + size_var_params=size_var_params, + output_buffer_lookup=output_buffer_lookup, + aliasable_flags=aliasable_flags, + alias_params=alias_params, + pointer_tail=pointer_tail, + kernel_input_params=kernel_input_params, + full_kernel_params=full_kernel_params, + non_alias_out_set=non_alias_out_set, + copy_output_indices=copy_output_indices, + alias_pairs=[], + ) + self.aliasable_out_ptrs = aliasable_flags + + self._codegen_imports(ctx) + + kernel_body = IndentedBuffer() + with kernel_body.indent(): + self._codegen_iteration_vars(kernel_body, ctx) + + for line in self.compute._lines: + kernel_body.writeline(str(line)) + + # Recompute kernel parameters after kernel body generation. + # Size variables may have been registered during kernel body generation + # (e.g., via rename_indexing for symbolic sizes), so we need to re-fetch + # the arg defs to capture all parameters including newly-registered size vars. + arg_defs, call_args, _, _ = self.args.python_argdefs() + kernel_params = [a.name for a in arg_defs] + size_var_names = OrderedSet(self.args.sizevars.values()) + ctx.size_var_params = [p for p in kernel_params if p in size_var_names] + ctx.pointer_tail = [ + p for p in kernel_params if p.startswith(("in_out_ptr", "in_ptr")) + ] + ctx.kernel_input_params = alias_params + ctx.pointer_tail + ctx.full_kernel_params = alias_params + kernel_params + + # Decide whether to use tiling for CPU/TPU after kernel body is fully + # generated (used_iter_vars is populated during load/store codegen). + self.tile_cpu_tpu = self._can_tile_cpu_tpu() + + extra_kernel_params = "" + if self.tile_relative_iter_vars: + extra_kernel_params = ", _pallas_tile=None, _pallas_ax2g=None" + + ctx.alias_pairs = self._compute_alias_pairs(ctx, aliasable_flags) + + use_scalar_prefetch = bool(self.indirect_access) + + if use_scalar_prefetch: + self._eliminate_dead_indirect_code() + kernel_body_sp = IndentedBuffer() + with kernel_body_sp.indent(): + for line in self.compute._lines: + kernel_body_sp.writeline(str(line)) + self._codegen_scalar_prefetch_wrapper( + ctx, + kernel_name, + kernel_body_sp, + ) + return code.getvalue() + + # Emit the kernel function with the correct signature + kernel_signature = f"def {kernel_name}_kernel({', '.join(ctx.full_kernel_params)}{extra_kernel_params}):" + code.writeline(kernel_signature) + + with code.indent(): + self._emit_kernel_body(code, kernel_body, ctx) + + code.writeline("") + jit_wrapper_name = f"{kernel_name}_jit_wrapper" + donate_indices = [] + base_offset = 2 + len(ctx.size_var_params) + for idx, name in enumerate(ctx.kernel_input_params): + if (name in alias_params) or name.startswith("in_out_ptr"): + donate_indices.append(idx + base_offset) + if donate_indices: + donate_literal = "(" + ", ".join(str(x) for x in donate_indices) + ",)" + else: + donate_literal = "()" + static_argnums = list(range(2 + len(ctx.size_var_params))) + static_argnums_literal = "(" + ", ".join(str(x) for x in static_argnums) + ",)" + code.writeline( + "@functools.partial(" + f"jax.jit, static_argnums={static_argnums_literal}, donate_argnums=" + f"{donate_literal})" + ) + wrapper_params = ( + ["out_shapes", "out_dtypes"] + ctx.size_var_params + ctx.kernel_input_params + ) + code.writeline(f"def {jit_wrapper_name}({', '.join(wrapper_params)}):") + + alias_map_literal = ", ".join(f"{i}: {o}" for (i, o) in ctx.alias_pairs) + + has_zero_dim, has_unknown_dim = self._zero_dim_output_flags(ctx) + + zero_dim_return = ( + "results = tuple(jnp.empty(s, dtype=dt) " + "for s, dt in zip(out_shapes, out_dtypes))", + "return results if len(results) > 1 else results[0]", + ) + + with code.indent(): + if has_zero_dim: + code.writelines(zero_dim_return) + else: + if has_unknown_dim: + code.writeline("if any(0 in shape for shape in out_shapes):") + with code.indent(): + code.writelines(zero_dim_return) + # Pallas requires >= 1-d tensors; promote 0-d to (1,) + code.writeline( + "_pallas_out_shapes = tuple(" + "s if len(s) > 0 else (1,) for s in out_shapes)" + ) + if self.collapsed_output_shape is not None: + code.writeline( + f"_pallas_out_shapes = ({self.collapsed_output_shape},)" + ) + # Reshape aliased inputs to match promoted output shapes + for input_idx, out_idx in ctx.alias_pairs: + param = ctx.kernel_input_params[input_idx] + code.writeline( + f"{param} = {param}.reshape(_pallas_out_shapes[{out_idx}])" + ) + code.writeline("out_shapes_pallas = tuple(") + code.writeline(" jax.ShapeDtypeStruct(shape, dtype)") + code.writeline( + " for shape, dtype in zip(_pallas_out_shapes, out_dtypes)" + ) + code.writeline(")") + if self.tile_cpu_tpu: + self._codegen_tiled_specs(ctx) + else: + self._codegen_strided_reshapes(code, ctx.kernel_input_params) + for param in ctx.kernel_input_params: + buf_name = self._param_to_buf_name(param) + cshape = ( + self.collapsed_reshape_inputs.get(buf_name) + if buf_name + else None + ) + if cshape is not None: + code.writeline(f"{param} = {param}.reshape({cshape})") + + code.writeline("out_specs_pallas = tuple(") + code.writeline(" pallas_make_block_spec_non_tiled(shape)") + code.writeline( + " for shape, dtype in zip(_pallas_out_shapes, out_dtypes)" + ) + code.writeline(")") + code.writeline("in_specs_pallas = tuple(") + code.writeline(" pallas_make_block_spec_non_tiled(i.shape)") + code.writeline( + " for i in [" + ", ".join(ctx.kernel_input_params) + "]" + ) + code.writeline(")") + + if self.tile_relative_iter_vars: + if self.tile_cpu_tpu: + code.writeline("_pallas_tile = _tile") + code.writeline("_pallas_ax2g = _ax2g") + else: + code.writeline("_pallas_tile = _pallas_out_shapes[0]") + code.writeline("_pallas_ax2g = {}") + + # Wrap kernel with functools.partial to pass scalar arguments (size variables) + partial_args = [] + for sv_param in ctx.size_var_params: + partial_args.append(f"{sv_param}={sv_param}") + + if self.tile_relative_iter_vars: + partial_args.append("_pallas_tile=_pallas_tile") + partial_args.append("_pallas_ax2g=_pallas_ax2g") + + if partial_args: + kernel_arg = f"functools.partial({kernel_name}_kernel, {', '.join(partial_args)})," + else: + kernel_arg = f"{kernel_name}_kernel," + + use_tma = ( + self.is_gpu + and self.use_emit_pipeline + and self._can_use_tma_approach() + ) + if use_tma: + self._codegen_jit_wrapper_tma(ctx, kernel_arg) + elif self.is_gpu: + self._codegen_jit_wrapper_legacy_gpu(ctx, kernel_arg) + else: + self._codegen_jit_wrapper_cpu_tpu( + ctx, kernel_arg, ctx.alias_pairs, alias_map_literal + ) + + self._codegen_main_entry(ctx, jit_wrapper_name) + return code.getvalue() + + @staticmethod + def _compute_alias_pairs( + ctx: _CodegenContext, aliasable_flags: dict[str, bool] + ) -> list[tuple[int, int]]: + alias_pairs: list[tuple[int, int]] = [] + for out_idx, name in enumerate(ctx.output_params): + if name.startswith("out_ptr"): + if aliasable_flags.get(name, False): + alias_name = f"{name}_alias" + input_idx = ctx.kernel_input_params.index(alias_name) + alias_pairs.append((input_idx, out_idx)) + else: + input_idx = ctx.kernel_input_params.index(name) + alias_pairs.append((input_idx, out_idx)) + return alias_pairs + + def _emit_kernel_body( + self, + code: IndentedBuffer, + kernel_body: IndentedBuffer, + ctx: _CodegenContext, + ) -> None: + """Emit the kernel body lines and store operations into code.""" + for line in kernel_body._lines: + if isinstance(line, str): + code.writeline(line.lstrip()) + else: + code._lines.append(line) + for out_ptr, store_line in self.store_with_output: + if out_ptr in ctx.full_kernel_params: + code.writeline(store_line) + + def _codegen_scalar_prefetch_wrapper( + self, + ctx: _CodegenContext, + kernel_name: str, + kernel_body: IndentedBuffer, + ) -> None: + """Emit kernel, JIT wrapper, and main entry for scalar prefetch.""" + if self.indirect_access is None: + raise AssertionError("expected indirect_access to be set") + indirect = self.indirect_access + code = ctx.code + + alias_set = OrderedSet(ctx.alias_params) + other_input_params = [ + p + for p in ctx.kernel_input_params + if p != indirect.indices_param + and p != indirect.table_param + and p not in alias_set + ] + + # Emit kernel function with params reordered for PrefetchScalarGridSpec: + # [scalar_prefetch] + [in_specs refs] + [out_specs refs] + prefetch_kernel_params = ( + [indirect.indices_param] + + [indirect.table_param] + + other_input_params + + list(ctx.alias_params) + + ctx.output_params + ) + code.writeline( + f"def {kernel_name}_kernel({', '.join(prefetch_kernel_params)}):" + ) + with code.indent(): + self._emit_kernel_body(code, kernel_body, ctx) + + # Emit JIT wrapper + code.writeline("") + jit_wrapper_name = f"{kernel_name}_jit_wrapper" + wrapper_params = ( + ["out_shapes", "out_dtypes"] + ctx.size_var_params + ctx.kernel_input_params + ) + static_argnums = list(range(2 + len(ctx.size_var_params))) + static_argnums_literal = "(" + ", ".join(str(x) for x in static_argnums) + ",)" + code.writeline( + f"@functools.partial(jax.jit, static_argnums={static_argnums_literal})" + ) + code.writeline(f"def {jit_wrapper_name}({', '.join(wrapper_params)}):") + + with code.indent(): + table = indirect.table_param + indices = indirect.indices_param + + ind_dim = indirect.indirect_dim + ndim = len(indirect.table_shape) + code.writeline("_D = 1") + for i in range(ndim): + if i != ind_dim: + code.writeline(f"_D = _D * {table}.shape[{i}]") + code.writeline(f"_seq = {indices}.shape[0]") + + if ind_dim == 0: + code.writeline(f"_table_3d = {table}.reshape({table}.shape[0], 1, _D)") + else: + perm = (ind_dim, *[d for d in range(ndim) if d != ind_dim]) + code.writeline( + f"_table_3d = {table}.transpose{perm}.reshape(" + f"{table}.shape[{ind_dim}], 1, _D)" + ) + + # Reshape other (non-table, non-indices) inputs to 3D to match the + # table's (seq, 1, D) layout. Currently handles: + # - 2D with leading dim == seq: row-aligned, reshape to (seq, 1, D) + # - 1D: broadcast scalar/vector, reshape to (1, 1, numel) + # - else: flatten to (1, 1, -1) — assumes broadcastable with + # (seq, 1, D). This may not work correctly for 3D+ inputs. + pallas_call_other_args = [] + for p in other_input_params: + p3d = f"_{p}_3d" + code.writeline(f"if {p}.ndim == 2 and {p}.shape[0] == _seq:") + code.writeline(f" {p3d} = {p}.reshape(_seq, 1, _D)") + code.writeline(f"elif {p}.ndim == 1:") + code.writeline(f" {p3d} = {p}.reshape(1, 1, {p}.shape[0])") + code.writeline("else:") + code.writeline(f" {p3d} = {p}.reshape(1, 1, -1)") + pallas_call_other_args.append(p3d) + + pallas_call_alias_args = [] + for p in ctx.alias_params: + p3d = f"_{p}_3d" + code.writeline(f"{p3d} = {p}.reshape(_seq, 1, _D)") + pallas_call_alias_args.append(p3d) + + partial_args = [f"{sv}={sv}" for sv in ctx.size_var_params] + if partial_args: + kernel_ref = ( + f"functools.partial({kernel_name}_kernel," + f" {', '.join(partial_args)})" + ) + else: + kernel_ref = f"{kernel_name}_kernel" + + # Reusable row-tiled BlockSpec (all i32 index_map for Mosaic compat) + code.writeline( + "_ROW_SPEC = pl.BlockSpec((1, 1, _D)," + " lambda i, _: (i, jnp.int32(0), jnp.int32(0)))" + ) + + num_non_alias_in_specs = 1 + len(pallas_call_other_args) + code.writeline("_in_specs = [") + with code.indent(): + code.writeline( + "pl.BlockSpec((1, 1, _D)," + " lambda gi, idx: (idx[gi], jnp.int32(0), jnp.int32(0)))," + ) + for p3d in pallas_call_other_args: + code.writeline( + f"_ROW_SPEC" + f" if {p3d}.shape[0] == _seq else" + f" pl.BlockSpec({p3d}.shape," + f" lambda i, _: (jnp.int32(0), jnp.int32(0), jnp.int32(0)))," + ) + for _ in ctx.alias_params: + code.writeline("_ROW_SPEC,") + code.writeline("]") + + num_outputs = len(ctx.output_params) + code.writeline( + "_out_specs = [" + ", ".join(["_ROW_SPEC"] * num_outputs) + "]" + ) + + # input_output_aliases: pallas_call arg index -> output index + # (offset by 1 for scalar prefetch arg) + alias_map_parts = [] + for out_idx, _ in enumerate(ctx.alias_params): + arg_idx = 1 + num_non_alias_in_specs + out_idx + alias_map_parts.append(f"{arg_idx}: {out_idx}") + alias_map_literal = ", ".join(alias_map_parts) + + out_shape_parts = [ + f"jax.ShapeDtypeStruct((_seq, 1, _D), out_dtypes[{i}])" + for i in range(num_outputs) + ] + out_shape_expr = "[" + ", ".join(out_shape_parts) + "]" + + code.writeline("_result = pl.pallas_call(") + with code.indent(): + code.writeline(f"{kernel_ref},") + code.writeline(f"out_shape={out_shape_expr},") + code.writeline("grid_spec=pltpu.PrefetchScalarGridSpec(") + with code.indent(): + code.writeline("num_scalar_prefetch=1,") + code.writeline("grid=(_seq,),") + code.writeline("in_specs=_in_specs,") + code.writeline("out_specs=_out_specs,") + code.writeline("),") + if alias_map_parts: + code.writeline(f"input_output_aliases={{ {alias_map_literal} }},") + if not self.is_tpu: + code.writeline(f"interpret={ctx.interpret_literal},") + + all_pallas_args = ( + [indices] + + ["_table_3d"] + + pallas_call_other_args + + pallas_call_alias_args + ) + code.writeline(f")({', '.join(all_pallas_args)})") + + code.writeline( + "return tuple(r.reshape(s) for r, s in zip(_result, out_shapes))" + ) + + self._codegen_main_entry(ctx, jit_wrapper_name) + + def _codegen_imports(self, ctx: _CodegenContext) -> None: + imports = """ +import functools +import math +import torch +import jax +import jax.numpy as jnp +from jax.experimental import pallas as pl +from torch.utils._ordered_set import OrderedSet +from torch._inductor.runtime.runtime_utils import ( + pallas_compute_tiling, pallas_make_block_spec, pallas_permute, + pallas_gpu_align_output_specs, pallas_gpu_pad_inputs, + pallas_gpu_unpad_results, + pallas_ensure_nonzero_rank, + pallas_make_block_spec_non_tiled, + torch_dtype_to_jax_runtime, +) +""" + if ctx.is_tpu: + imports += "\nimport jax.export" + imports += "\nfrom jax.experimental.pallas import tpu as pltpu" + imports += "\nfrom torch_tpu._internal.pallas import tpu_torch_pallas" + elif not ctx.interpret_is_cpu: + imports += "\nfrom jax.experimental.pallas import mosaic_gpu as plgpu" + if self.indirect_access and not ctx.is_tpu: + imports += ( + "\nimport os as _os; _os.environ.setdefault('JAX_PLATFORMS', 'cpu')" + ) + imports += "\nfrom jax.experimental.pallas import tpu as pltpu" + ctx.code.splice(imports, strip=True) + + def _get_iter_var_axis(self, var_sym: sympy.Symbol) -> int | None: + """Map an iteration variable to its output tensor axis index. + + Non-reduction variables map to axes 0, 1, 2, ... in order. + Reduction variables map to axes after all pointwise axes. + Returns None if the mapping cannot be determined. + """ + pw_idx = 0 + r_idx = 0 + n_pw = sum(1 for e in self.range_tree_nodes.values() if not e.is_reduction) + for sym, entry in self.range_tree_nodes.items(): + if sym == var_sym: + return pw_idx if not entry.is_reduction else n_pw + r_idx + if entry.is_reduction: + r_idx += 1 + else: + pw_idx += 1 + return None + + def _get_reshape_target_shape_and_numel( + self, + ) -> tuple[tuple[int, ...] | None, int | None]: + # Find reshape target: N-D shape whose numel matches an iteration + # var. Try output first (repeat/upsample), then inputs (reductions). + iter_lengths = OrderedSet( + [ + int(e.length) + for e in self.range_tree_nodes.values() + if isinstance(e.length, (int, sympy.Integer)) + ] + ) + + def _get_nd_shape_if_matches(buf_name): + buf = V.graph.try_get_buffer(buf_name) + if buf is None or len(buf.get_size()) <= 1: + return None, None + shape = tuple( + int(s) if isinstance(s, (int, sympy.Integer)) else s + for s in buf.get_size() + ) + numel = math.prod(shape) + return (shape, numel) if numel in iter_lengths else (None, None) + + candidate_buf_names = self._output_buffer_names.copy() + candidate_buf_names.extend(self.args.input_buffers) + + reshape_target_shape, reshape_target_numel = None, None + for buf_name in candidate_buf_names: + result = _get_nd_shape_if_matches(buf_name) + if result[0]: + reshape_target_shape, reshape_target_numel = result + break + + return reshape_target_shape, reshape_target_numel + + def _make_broadcasted_iteration_var_expr( + self, broadcast_vars: list[_BroadcastedIterVar], broadcast_idx: int + ) -> str: + bv = broadcast_vars[broadcast_idx] + length = bv.entry.length + renamed_length = self.rename_indexing(length) + length_str = self.kexpr(renamed_length) + + num_broadcast_dims = len(broadcast_vars) + axis_idx = self._broadcast_axis_idx( + broadcast_vars, broadcast_idx, num_broadcast_dims + ) + shape_parts = ["1"] * num_broadcast_dims + shape_parts[axis_idx] = length_str + shape_str = ", ".join(shape_parts) + arange = f"jnp.arange({length_str})" + reshaped = f"{arange}.reshape({shape_str})" + return reshaped + + def _codegen_iteration_vars( + self, kernel_body: IndentedBuffer, ctx: _CodegenContext + ) -> None: + # Generate iteration variables as jnp.arange arrays + # Skip on GPU - jnp.arange is not supported by Pallas Mosaic backend + if not (self.range_tree_nodes and not self.is_gpu and self.used_iter_vars): + return + + kernel_body.writeline("# Define iteration variables as JAX arrays") + + reshape_target_shape, reshape_target_numel = ( + self._get_reshape_target_shape_and_numel() + ) + + var_items = list(self.range_tree_nodes.items()) + + broadcast_vars = [] + total_var_idx = None + for idx, (var_sym, entry) in enumerate(var_items): + length_val = self._safe_int(entry.length) + if length_val is not None and length_val == reshape_target_numel: + total_var_idx = idx + else: + broadcast_vars.append( + _BroadcastedIterVar(idx, var_sym, entry, length_val) + ) + + num_broadcast_dims = len(broadcast_vars) + + for idx, (var_sym, entry) in enumerate(var_items): + if var_sym not in self.used_iter_vars: + continue + var_name = str(var_sym) + length = entry.length + renamed_length = self.rename_indexing(length) + length_str = self.kexpr(renamed_length) + length_val = self._safe_int(length) + + if length_val is None: + if ( + reshape_target_shape + and num_broadcast_dims > 1 + and idx != total_var_idx + ): + broadcast_idx = next( + (i for i, v in enumerate(broadcast_vars) if v.idx == idx), + None, + ) + if broadcast_idx is not None: + expr = self._make_broadcasted_iteration_var_expr( + broadcast_vars, broadcast_idx + ) + kernel_body.writeline(f"{var_name} = {expr}") + continue + kernel_body.writeline(f"{var_name} = jnp.arange({length_str})") + continue + + if ( + reshape_target_shape + and len(reshape_target_shape) > 1 + and length_val == reshape_target_numel + ): + shape_str = ", ".join(str(s) for s in reshape_target_shape) + arange = f"jnp.arange({length_str})" + kernel_body.writeline(f"{var_name} = {arange}.reshape({shape_str})") + elif num_broadcast_dims > 1 and idx != total_var_idx: + broadcast_idx = next( + i for i, v in enumerate(broadcast_vars) if v.idx == idx + ) + expr = self._make_broadcasted_iteration_var_expr( + broadcast_vars, broadcast_idx + ) + kernel_body.writeline(f"{var_name} = {expr}") + else: + # Simple 1D arange — emit tile-relative form so tiling is safe. + # When grid=(1,), _pallas_tile[ax] == full length and + # pl.program_id(0) == 0, so this degenerates to jnp.arange(N). + # Only do this when the var actually appears in compute body + # (otherwise tiling is not blocked and the full arange is fine). + # Skip for scatter/index kernels where the iter var is used + # as a global index, not a data value. + compute_text = "\n".join(str(line) for line in self.compute._lines) + var_in_compute = var_name in compute_text + can_tile_relative = ( + var_in_compute + and not self.is_gpu + and not self.outputs_need_read + and not self.has_flatten_indexing + and not entry.is_reduction + ) + axis_idx = ( + self._get_iter_var_axis(var_sym) if can_tile_relative else None + ) + if axis_idx is not None: + kernel_body.writeline( + f"{var_name} = jnp.arange(_pallas_tile[{axis_idx}])" + f" + pl.program_id(_pallas_ax2g.get({axis_idx}, 0))" + f" * _pallas_tile[{axis_idx}]" + ) + self.tile_relative_iter_vars.add(var_sym) + else: + kernel_body.writeline(f"{var_name} = jnp.arange({length_str})") + + @staticmethod + def _broadcast_axis_idx( + broadcast_vars: list[_BroadcastedIterVar], + broadcast_idx: int, + num_broadcast_dims: int, + ) -> int: + # Axis placement depends on var types (reduction r* vs x*): + # - Mixed: pointwise first, reduction last for output reshape + # - Same-type: reverse order, first var innermost + has_reduction_vars = any( + str(bv.var_sym).startswith("r") for bv in broadcast_vars + ) + has_pointwise_vars = any( + not str(bv.var_sym).startswith("r") for bv in broadcast_vars + ) + is_mixed = has_reduction_vars and has_pointwise_vars + if is_mixed: + return broadcast_idx + return num_broadcast_dims - 1 - broadcast_idx + + def _codegen_jit_wrapper_tma(self, ctx: _CodegenContext, kernel_arg: str) -> None: + code = ctx.code + kernel_input_params = ctx.kernel_input_params + output_params = ctx.output_params + + # TMA automatically handles out-of-bounds accesses + code.writeline("# Use lax.fori_loop with TMA for automatic OOB masking") + code.writeline("from jax import lax") + code.writeline("_tile_size = 128 # Warpgroup size") + code.writeline("_orig_out_shapes = out_shapes") + + code.writeline("_max_numel = 0") + for param in kernel_input_params: + code.writeline(f"_max_numel = max(_max_numel, {param}.size)") + code.writeline("for shape in out_shapes:") + code.writeline(" _max_numel = max(_max_numel, math.prod(shape))") + + code.writeline("_num_tiles = (_max_numel + _tile_size - 1) // _tile_size") + + gmem_input_params = [f"{p}_gmem" for p in kernel_input_params] + gmem_output_params = [f"{p}_gmem" for p in output_params] + smem_input_params = [f"{p}_smem" for p in kernel_input_params] + smem_output_params = [f"{p}_smem" for p in output_params] + + code.writeline("") + code.writeline("# Wrapper kernel using lax.fori_loop with direct TMA") + + wrapper_kernel_params = gmem_input_params + gmem_output_params + all_smem_params = smem_input_params + smem_output_params + barrier_params = [f"_barrier_{i}" for i in range(len(kernel_input_params))] + scratch_params = ", ".join(all_smem_params + barrier_params) + + code.writeline( + f"def _tma_kernel({', '.join(wrapper_kernel_params)}, *, {scratch_params}):" + ) + with code.indent(): + code.writeline("") + code.writeline("def _tile_body(_tile_idx, _):") + with code.indent(): + code.writeline("_tile_start = _tile_idx * _tile_size") + code.writeline("") + + code.writeline("# TMA load inputs from GMEM to SMEM (OOB auto-masked)") + for i, (gmem_in, smem_in) in enumerate( + zip(gmem_input_params, smem_input_params) + ): + code.writeline( + f"plgpu.copy_gmem_to_smem({gmem_in}.at[pl.ds(_tile_start, _tile_size)], {smem_in}, _barrier_{i})" + ) + + code.writeline("") + code.writeline("# Wait for TMA loads to complete") + for i, _ in enumerate(gmem_input_params): + code.writeline(f"plgpu.barrier_wait(_barrier_{i})") + + code.writeline("") + code.writeline("# Compute on SMEM tiles") + kernel_call_args = smem_input_params + smem_output_params + kernel_fn = kernel_arg.rstrip(",").strip() + code.writeline(f"{kernel_fn}({', '.join(kernel_call_args)})") + + code.writeline("") + code.writeline( + "# TMA store outputs from SMEM to GMEM (OOB auto-masked)" + ) + code.writeline("plgpu.commit_smem()") + for gmem_out, smem_out in zip(gmem_output_params, smem_output_params): + code.writeline( + f"plgpu.copy_smem_to_gmem({smem_out}, {gmem_out}.at[pl.ds(_tile_start, _tile_size)])" + ) + code.writeline("plgpu.wait_smem_to_gmem(0)") + code.writeline("") + code.writeline("return None") + + code.writeline("") + code.writeline("# Iterate over all tiles") + code.writeline("lax.fori_loop(0, _num_tiles, _tile_body, None)") + + # Build scratch_shapes dict + code.writeline("") + code.writeline( + "# Build SMEM scratch shapes for inputs, outputs, and TMA barriers" + ) + code.writeline("_scratch_shapes = {}") + for i, smem_param in enumerate(smem_input_params): + orig_param = kernel_input_params[i] + code.writeline( + f"_scratch_shapes['{smem_param}'] = plgpu.SMEM((_tile_size,), {orig_param}.dtype)" + ) + for i, smem_param in enumerate(smem_output_params): + code.writeline( + f"_scratch_shapes['{smem_param}'] = plgpu.SMEM((_tile_size,), out_dtypes[{i}])" + ) + for barrier_param in barrier_params: + code.writeline( + f"_scratch_shapes['{barrier_param}'] = plgpu.Barrier(num_arrivals=1)" + ) + + code.writeline("") + code.writeline("# Create flattened output specs aligned to tile size") + code.writeline( + "_flat_out_specs, _ = pallas_gpu_align_output_specs(out_shapes, out_dtypes, _tile_size)" + ) + + code.writeline("") + code.writeline("# Call plgpu.kernel with TMA kernel") + code.writeline("_result = plgpu.kernel(") + with code.indent(): + code.writeline("_tma_kernel,") + code.writeline("out_shape=_flat_out_specs,") + code.writeline("scratch_shapes=_scratch_shapes,") + code.writeline(")(") + for param in kernel_input_params: + code.writeline(f" {param}.flatten(),") + code.writeline(")") + + code.writeline("") + code.writeline("# Reshape results to original shapes") + code.writeline("return pallas_gpu_unpad_results(_result, _orig_out_shapes)") + + def _codegen_jit_wrapper_legacy_gpu( + self, ctx: _CodegenContext, kernel_arg: str + ) -> None: + code = ctx.code + kernel_input_params = ctx.kernel_input_params + input_list = f"[{', '.join(kernel_input_params)}]" + + # Legacy GPU path with explicit padding (use_emit_pipeline=False) + # Mosaic GPU requires tensor sizes to be multiples of 128. + # Only apply padding when all tensors have the same size (no broadcasting). + code.writeline("# Check if all tensors have same size (no broadcasting)") + code.writeline("_all_sizes = []") + for param in kernel_input_params: + code.writeline(f"_all_sizes.append({param}.size)") + code.writeline("for shape in out_shapes:") + code.writeline(" _all_sizes.append(math.prod(shape))") + code.writeline("_unique_sizes = OrderedSet(_all_sizes)") + code.writeline( + "_can_pad = len(_unique_sizes) == 1 and all(s > 1 for s in _unique_sizes)" + ) + + code.writeline("") + code.writeline("if _can_pad:") + code.writeline(" # All tensors same size - safe to flatten and pad") + code.writeline(f" _padded_inputs = pallas_gpu_pad_inputs({input_list})") + code.writeline( + " _aligned_out_specs, _is_scalar = pallas_gpu_align_output_specs(out_shapes, out_dtypes)" + ) + code.writeline(" _result = plgpu.kernel(") + code.writeline(" " + kernel_arg) + code.writeline(" out_shape=_aligned_out_specs,") + code.writeline(" )(*_padded_inputs)") + code.writeline( + " return pallas_gpu_unpad_results(_result, out_shapes, _is_scalar)" + ) + + code.writeline("else:") + code.writeline( + " # Different sizes - check if it's a reduction (scalar output)" + ) + code.writeline(" _out_numel = math.prod(out_shapes[0])") + code.writeline(" ") + code.writeline(" if _out_numel <= 1:") + code.writeline( + " # Scalar output (reduction) - pad inputs but keep scalar output" + ) + code.writeline(f" _padded_inputs = pallas_gpu_pad_inputs({input_list})") + code.writeline(" _aligned_out_specs = tuple(") + code.writeline(" jax.ShapeDtypeStruct(shape, dtype)") + code.writeline(" for shape, dtype in zip(out_shapes, out_dtypes)") + code.writeline(" )") + code.writeline(" _result = plgpu.kernel(") + code.writeline(" " + kernel_arg) + code.writeline(" out_shape=_aligned_out_specs,") + code.writeline(" )(*_padded_inputs)") + code.writeline(" return _result") + code.writeline(" else:") + code.writeline( + " # Non-scalar output with broadcasting - broadcast inputs to output shape" + ) + code.writeline(" _target_shape = out_shapes[0]") + code.writeline(" _broadcasted = [") + code.writeline( + f" jnp.broadcast_to(_inp, _target_shape) for _inp in {input_list}" + ) + code.writeline(" ]") + code.writeline(" _padded_inputs = pallas_gpu_pad_inputs(_broadcasted)") + code.writeline( + " _aligned_out_specs, _is_scalar = pallas_gpu_align_output_specs(out_shapes, out_dtypes)" + ) + code.writeline(" _result = plgpu.kernel(") + code.writeline(" " + kernel_arg) + code.writeline(" out_shape=_aligned_out_specs,") + code.writeline(" )(*_padded_inputs)") + code.writeline( + " return pallas_gpu_unpad_results(_result, out_shapes, _is_scalar)" + ) + + def _param_to_buf_name(self, param: str) -> str | None: + """Map a kernel parameter name back to its graph buffer name.""" + for graph_name, inner_name in self.args.input_buffers.items(): + if inner_name == param: + return graph_name + return None + + def _codegen_tiled_specs(self, ctx: _CodegenContext) -> None: + """Generate tiled BlockSpec and grid variables for CPU/TPU. + + Tiles the last 1–2 dimensions of each tensor, respecting TPU + alignment constraints (last dim multiple of 128, second-to-last + multiple of 8). Lower-ndim inputs are right-aligned with the + reference output shape per numpy broadcast rules. + """ + code = ctx.code + skip_n = self.tile_skip_last_n + has_transpose = "True" if self.tile_has_transpose else "False" + is_tpu_literal = "True" if ctx.is_tpu else "False" + + # Collect per-input permutations for tiling alignment. + all_perms: list[tuple[int, ...] | None] = [] + for p in ctx.kernel_input_params: + buf_name = self._param_to_buf_name(p) + all_perms.append( + self.permuted_input_buffers.get(buf_name) if buf_name else None + ) + + mgp = self._cpu_max_grid_product + mgp_arg = f", max_grid_product={mgp}" if mgp else "" + perms_arg = ( + f", permutations={repr(all_perms)}" + if any(p is not None for p in all_perms) + else "" + ) + code.writeline( + f"_tile, _grid, _ax2g = pallas_compute_tiling(" + f"_pallas_out_shapes[0], " + f"transpose={has_transpose}, " + f"skip_last_n={skip_n}, exact_only=len(_pallas_out_shapes[0]) < 2, " + f"is_tpu={is_tpu_literal}" + f"{perms_arg}{mgp_arg})" + ) + code.writeline("_ng = len(_grid)") + code.writeline("_ref = _pallas_out_shapes[0]") + + code.writeline("out_specs_pallas = tuple(") + code.writeline( + " pallas_make_block_spec(s, _ref, _tile, _ax2g, _ng, is_output=True)" + ) + code.writeline(" for s in _pallas_out_shapes") + code.writeline(")") + + self._codegen_strided_reshapes(code, ctx.kernel_input_params) + + # Reshape collapsed inputs before building specs. + for param in ctx.kernel_input_params: + buf_name = self._param_to_buf_name(param) + cshape = self.collapsed_reshape_inputs.get(buf_name) if buf_name else None + if cshape is not None: + code.writeline(f"{param} = {param}.reshape({cshape})") + + # Build input BlockSpecs (with per-input permutation when needed). + input_list = ", ".join(ctx.kernel_input_params) + if any(p is not None for p in all_perms): + perm_list = ", ".join(repr(p) for p in all_perms) + code.writeline(f"_perm_flags = [{perm_list}]") + code.writeline("in_specs_pallas = tuple(") + code.writeline( + f" pallas_make_block_spec(i.shape, _ref, _tile, _ax2g, _ng, permutation=p)" + f" for i, p in zip([{input_list}], _perm_flags)" + ) + code.writeline(")") + else: + code.writeline("in_specs_pallas = tuple(") + code.writeline( + f" pallas_make_block_spec(i.shape, _ref, _tile, _ax2g, _ng) for i in [{input_list}]" + ) + code.writeline(")") + + def _codegen_jit_wrapper_cpu_tpu( + self, + ctx: _CodegenContext, + kernel_arg: str, + alias_pairs: list[tuple[int, int]], + alias_map_literal: str, + ) -> None: + code = ctx.code + grid_expr = "_grid" if self.tile_cpu_tpu else "(1,)" + code.writeline("_result = pl.pallas_call(") + code.writeline(" " + kernel_arg) + code.writeline(" out_shape=out_shapes_pallas,") + code.writeline(" out_specs=out_specs_pallas,") + code.writeline(" in_specs=in_specs_pallas,") + code.writeline(f" interpret={ctx.interpret_literal},") + code.writeline(f" grid={grid_expr},") + code.writeline( + f" input_output_aliases={{ {alias_map_literal} }}," + if alias_pairs + else " input_output_aliases={}," + ) + code.writeline(")(") + if ctx.kernel_input_params: + kernel_input_params_nonzero_rank = [ + f"pallas_ensure_nonzero_rank({p})" for p in ctx.kernel_input_params + ] + code.writeline(f" {', '.join(kernel_input_params_nonzero_rank)},") + code.writeline(")") + # Reshape results back to original shapes (restores 0-d from promoted (1,)) + code.writeline("if isinstance(_result, tuple):") + code.writeline( + " _result = tuple(r.reshape(s) for r, s in zip(_result, out_shapes))" + ) + code.writeline("else:") + code.writeline(" _result = _result.reshape(out_shapes[0])") + code.writeline("return _result") + + def _codegen_main_entry(self, ctx: _CodegenContext, jit_wrapper_name: str) -> None: + if ctx.is_tpu: + self._codegen_main_entry_tpu(ctx, jit_wrapper_name) + else: + self._codegen_main_entry_default(ctx, jit_wrapper_name) + + def _codegen_main_entry_tpu( + self, ctx: _CodegenContext, jit_wrapper_name: str + ) -> None: + code = ctx.code + code.writeline("") + main_name = f"{ctx.kernel_name}_main" + kernel_name_str = ctx.kernel_name + code.writeline( + f"def {main_name}({', '.join(ctx.full_kernel_params)}, stream=None):" + ) + with code.indent(): + # `jax_enable_x64` is per-process. The CPU path sets it to True, + # so running both CPU and TPU tests in one process can cause + # x64-related TPU crashes if we do not explicitly set it to + # False here. + code.writeline("jax.config.update('jax_enable_x64', False)") + code.writeline("jax.clear_caches()") + + # Convert int64 inputs to int32 (TPU doesn't support int64) + all_input_params = list(ctx.alias_params) + list(ctx.pointer_tail) + for param_name in all_input_params: + code.writeline( + f"{param_name} = {param_name}.to(torch.int32) " + f"if {param_name}.dtype == torch.int64 else {param_name}" + ) + + # Build JAX placeholders for all inputs + code.writeline("# Build JAX placeholders for export tracing") + all_jax_input_names = [] + for alias_name in ctx.alias_params: + code.writeline( + f"{alias_name}_placeholder = jax.ShapeDtypeStruct(" + f"{alias_name}.shape, torch_dtype_to_jax_runtime({alias_name}.dtype))" + ) + all_jax_input_names.append(f"{alias_name}_placeholder") + for ptr in ctx.pointer_tail: + code.writeline( + f"{ptr}_placeholder = jax.ShapeDtypeStruct(" + f"{ptr}.shape, torch_dtype_to_jax_runtime({ptr}.dtype))" + ) + all_jax_input_names.append(f"{ptr}_placeholder") + + # Prepare output metadata + code.writeline( + "out_shapes = (" + + ", ".join([f"tuple({name}.shape)" for name in ctx.output_params]) + + ",)" + ) + dtype_exprs: list[str] = [] + for name in ctx.output_params: + buf_name = ctx.output_buffer_lookup.get(name) + if buf_name is not None: + dtype = V.graph.get_dtype(buf_name) + if dtype is not None: + dtype_exprs.append(torch_dtype_to_jax(dtype)) + continue + dtype_exprs.append(f"torch_dtype_to_jax_runtime({name}.dtype)") + code.writeline("out_dtypes = (" + ", ".join(dtype_exprs) + ",)") + + # Export the jit_wrapper + wrapper_placeholder_args = ["out_shapes", "out_dtypes"] + wrapper_placeholder_args.extend(ctx.size_var_params) + wrapper_placeholder_args.extend(all_jax_input_names) + code.writeline( + f"exported = jax.export.export(" + f"{jit_wrapper_name}, platforms=['tpu'])" + f"({', '.join(wrapper_placeholder_args)})" + ) + + # Register and call via tpu_torch_pallas + # Include all output and input shapes in the key to avoid stale + # cache hits when the same kernel name is compiled with different + # input/output ranks (e.g. broadcasting vs non-broadcasting calls). + shape_key_parts = [] + for p in ctx.output_params: + shape_key_parts.append(f"'_'.join(str(s) for s in {p}.shape)") + output_key_expr = ( + " + 'x' + ".join(shape_key_parts) if shape_key_parts else "''" + ) + input_key_parts = [] + for p in ctx.kernel_input_params: + input_key_parts.append(f"'_'.join(str(s) for s in {p}.shape)") + input_key_expr = ( + " + 'x' + ".join(input_key_parts) if input_key_parts else "''" + ) + code.writeline( + f"kernel_key = '{kernel_name_str}_out_' + " + f"{output_key_expr}" + f" + '_in_' + {input_key_expr}" + ) + + code.writeline( + f"if not tpu_torch_pallas.lookup_custom_kernel('{kernel_name_str}', kernel_key):" + ) + with code.indent(): + code.writeline("try:") + with code.indent(): + code.writeline( + f"tpu_torch_pallas.register_custom_kernel(" + f"'{kernel_name_str}', kernel_key, " + f"serialized_mlir_module=exported.mlir_module_serialized)" + ) + code.writeline("except TypeError:") + with code.indent(): + code.writeline( + f"tpu_torch_pallas.register_custom_kernel(" + f"'{kernel_name_str}', kernel_key, " + f"exported.mlir_module_serialized)" + ) + + # Build input tensor list (all non-size-var inputs) + input_tensor_names = list(ctx.alias_params) + list(ctx.pointer_tail) + code.writeline(f"input_tensors = [{', '.join(input_tensor_names)}]") + + # Build output shapes list + code.writeline("output_shape_tensors = [") + with code.indent(): + for name in ctx.output_params: + buf_name = ctx.output_buffer_lookup.get(name) + if buf_name is not None: + dtype = V.graph.get_dtype(buf_name) + if dtype is not None: + code.writeline( + f"torch.empty({name}.shape, dtype={dtype!r}, device='tpu')," + ) + continue + code.writeline( + f"torch.empty({name}.shape, dtype={name}.dtype, device='tpu')," + ) + code.writeline("]") + + # Build donation info for zero-copy aliasing. Current torch_tpu + # exposes donate_argnums (the donated input indices); older + # versions took input_output_aliases ({input: output}). torch_tpu + # itself maps the latter to list(input_output_aliases.keys()), so + # the donated input indices are the alias-pair keys. + if ctx.alias_pairs: + alias_map_str = ", ".join(f"{i}: {o}" for (i, o) in ctx.alias_pairs) + code.writeline(f"_input_output_aliases = {{ {alias_map_str} }}") + donate_argnums_str = ", ".join(str(i) for (i, _o) in ctx.alias_pairs) + code.writeline(f"_donate_argnums = [{donate_argnums_str}]") + else: + code.writeline("_input_output_aliases = {}") + code.writeline("_donate_argnums = []") + + code.writeline("try:") + with code.indent(): + code.writeline( + f"_results = tpu_torch_pallas.call_custom_kernel(" + f"'{kernel_name_str}', kernel_key, " + f"inputs=input_tensors, " + f"output_shapes=output_shape_tensors, " + f"donate_argnums=_donate_argnums)" + ) + code.writeline("except TypeError:") + with code.indent(): + code.writeline( + f"_results = tpu_torch_pallas.call_custom_kernel(" + f"'{kernel_name_str}', kernel_key, " + f"inputs=input_tensors, " + f"output_shapes=output_shape_tensors, " + f"input_output_aliases=_input_output_aliases)" + ) + # call_custom_kernel returns freshly allocated result tensors; + # donate_argnums only lets the kernel reuse the donated buffers + # internally, it does not write back into the passed-in tensors. + # Copy each result into the aliased output buffer the caller reads + # (this mirrors torch_tpu's own JaxCallable alias handling). + code.writeline("if _results is not None:") + with code.indent(): + code.writeline( + "for _in_idx, _out_idx in _input_output_aliases.items():" + ) + with code.indent(): + code.writeline("input_tensors[_in_idx].copy_(_results[_out_idx])") + + def _codegen_main_entry_default( + self, ctx: _CodegenContext, jit_wrapper_name: str + ) -> None: + code = ctx.code + code.writeline("") + main_name = f"{ctx.kernel_name}_main" + code.writeline( + f"def {main_name}({', '.join(ctx.full_kernel_params)}, stream=None):" + ) + with code.indent(): + code.writeline("jax.config.update('jax_enable_x64', True)") + if ctx.interpret_is_cpu: + code.writeline( + "jax.config.update('jax_default_device', jax.devices('cpu')[0])" + ) + code.writeline("jax.clear_caches()") + if ctx.alias_params: + code.writeline("# Convert Torch -> JAX for donated outputs") + for alias_name in ctx.alias_params: + # On CPU/TPU, alias outputs may be non-contiguous (e.g. + # torch.cat slices) and JAX's from_dlpack rejects + # non-trivially strided tensors. Making them contiguous + # is safe because CPU/TPU already copies all results back + # via copy_output_indices. On CUDA, the donated-buffer + # mechanism requires the original buffer for in-place + # mutation, so we cannot make a contiguous copy. + self._emit_torch_to_jax( + code, + alias_name, + ctx.is_tpu, + contiguous=ctx.interpret_is_cpu, + ) + code.writeline("# Convert Torch -> JAX for in-place tensors") + for ptr in ctx.pointer_tail: + if ptr.startswith("in_out_ptr"): + self._emit_torch_to_jax(code, ptr, ctx.is_tpu, contiguous=False) + code.writeline("# Convert Torch -> JAX for inputs") + for ptr in ctx.pointer_tail: + if ptr.startswith("in_ptr"): + self._emit_torch_to_jax(code, ptr, ctx.is_tpu, contiguous=True) + + code.writeline("# Prepare output metadata from PyTorch tensor") + code.writeline( + "out_shapes = (" + + ", ".join([f"tuple({name}.shape)" for name in ctx.output_params]) + + ",)" + ) + dtype_exprs: list[str] = [] + for name in ctx.output_params: + buf_name = ctx.output_buffer_lookup.get(name) + if buf_name is not None: + dtype = V.graph.get_dtype(buf_name) + if dtype is not None: + dtype_exprs.append(torch_dtype_to_jax(dtype)) + continue + dtype_exprs.append(f"torch_dtype_to_jax_runtime({name}.dtype)") + code.writeline("out_dtypes = (" + ", ".join(dtype_exprs) + ",)") + arg_name_map: dict[str, str] = {} + for alias_name in ctx.alias_params: + arg_name_map[alias_name] = f"{alias_name}_jax" + for ptr in ctx.pointer_tail: + arg_name_map[ptr] = f"{ptr}_jax" + + wrapper_call_args = ["out_shapes", "out_dtypes"] + wrapper_call_args.extend(ctx.size_var_params) + wrapper_call_args.extend( + arg_name_map[name] for name in ctx.kernel_input_params + ) + code.writeline(f"res = {jit_wrapper_name}({', '.join(wrapper_call_args)})") + code.writeline("jax.block_until_ready(res)") + if ctx.copy_output_indices: + code.writeline( + "result_values = res if isinstance(res, tuple) else (res,)" + ) + for idx in ctx.copy_output_indices: + out_name = ctx.output_params[idx] + code.writeline( + f"{out_name}.copy_(torch.from_dlpack(result_values[{idx}]))" + ) + + @staticmethod + def _emit_torch_to_jax( + code: IndentedBuffer, var_name: str, is_tpu: bool, *, contiguous: bool + ) -> None: + suffix = ".detach().contiguous()" if contiguous else ".detach()" + code.writeline(f"{var_name}_jax = jax.dlpack.from_dlpack({var_name}{suffix})") + + def call_kernel(self, name: str, node: IRNode | None = None) -> None: # type: ignore[override] + """Generate the Python code that calls this Pallas kernel.""" + wrapper = V.graph.wrapper_code + arg_defs, call_args, _, _ = self.args.python_argdefs() + kernel_param_names = [a.name for a in arg_defs] + pure_out_params = [p for p in kernel_param_names if p.startswith("out_ptr")] + call_arg_strs = list(map(str, call_args)) + aliasable = getattr(self, "aliasable_out_ptrs", {}) + alias_call_args = [ + call_arg_strs[kernel_param_names.index(p)] + for p in pure_out_params + if aliasable.get(p, False) + ] + + # Generate kernel call: kernel_name.run(arg1, arg2, ...) + # Note: async_compile.pallas loads {name}_main function and wraps it in PallasKernelWrapper + # which exposes a run() method + kernel_call = f"{name}.run({', '.join(alias_call_args + call_arg_strs)})" + wrapper.writeline(kernel_call) + + +class PallasScheduling(SIMDScheduling): + kernel_type = PallasKernel # type: ignore[assignment] + + @classmethod + def get_backend_features(cls, device: torch.device) -> OrderedSet[BackendFeature]: + # Pallas/JAX can handle reductions to single elements efficiently + # without requiring split reductions + return OrderedSet([BackendFeature.REDUCE_TO_SINGLE_ELEMENT]) + + def can_fuse(self, node1, node2): # type: ignore[override] + if not super().can_fuse(node1, node2): + return False + # Pallas partial reductions use keepdims, so fusing two reductions + # that read the same buffer with different index patterns produces + # intermediates with incompatible shapes (e.g. (1,8) + (8,1) = (8,8) + # instead of (8,)). Prevent this by rejecting fusion when the read + # indices differ. + if node1.is_reduction() and node2.is_reduction(): + from torch._inductor.dependencies import MemoryDep + + reads1 = {} + for dep in node1.read_writes.reads: + if isinstance(dep, MemoryDep): + reads1[dep.name] = dep.index + for dep in node2.read_writes.reads: + if isinstance(dep, MemoryDep) and dep.name in reads1: + if reads1[dep.name] != dep.index: + return False + return True + + can_fuse_vertical = can_fuse # type: ignore[assignment] + can_fuse_horizontal = can_fuse # type: ignore[assignment] + + def define_kernel( + self, + src_code: str, + node_schedule: Sequence[BaseSchedulerNode], + kernel: PallasKernel, + ) -> str: # type: ignore[override] + wrapper = V.graph.wrapper_code + if src_code in wrapper.src_to_kernel: + return wrapper.src_to_kernel[src_code] + + fused_name = ( + get_fused_kernel_name(node_schedule, config.triton.descriptive_names) + if config.triton.descriptive_names + else "" + ) + kernel_hash = hashlib.sha256(src_code.encode("utf-8")).hexdigest()[:8] + if fused_name == "fused": + kernel_name = f"pallas_{kernel_hash}" + else: + kernel_name = f"pallas_{fused_name}_{kernel_hash}" + wrapper.src_to_kernel[src_code] = kernel_name + + # Replace placeholder if any + src_code = src_code.replace("", kernel_name) + + compile_wrapper = IndentedBuffer() + compile_wrapper.writeline(f"async_compile.pallas({kernel_name!r}, r'''") + compile_wrapper.splice(src_code, strip=True) + compile_wrapper.writeline("''')") + + origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper) + metadata_comment = f"{origins}\n{detailed_origins}" + wrapper.define_kernel(kernel_name, compile_wrapper.getvalue(), metadata_comment) + + return kernel_name diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/python_wrapper_mtia.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/python_wrapper_mtia.py new file mode 100644 index 0000000000000000000000000000000000000000..4a0309f2088ae1785a548db4f77103320d11a5b0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/python_wrapper_mtia.py @@ -0,0 +1,33 @@ +from typing_extensions import override + +from torch._inductor import ir + +from .wrapper import PythonWrapperCodegen + + +class PythonWrapperMtia(PythonWrapperCodegen): + """ + A thin wrapper of PythonWrapperCodegen with MTIA specific logic + """ + + @override + def write_header(self) -> None: + super().write_header() + + # MITA specific imports + self.imports.splice("import mtia.host_runtime.torch_mtia.dynamic_library") + + @override + @staticmethod + def create( + is_subgraph: bool, + subgraph_name: str | None, + parent_wrapper: PythonWrapperCodegen | None, + partition_signatures: ir.GraphPartitionSignature | None = None, + ) -> PythonWrapperCodegen: + if is_subgraph: + # Delegate to the parent class to handle the case of subgraph + return PythonWrapperCodegen.create( + is_subgraph, subgraph_name, parent_wrapper, partition_signatures + ) + return PythonWrapperMtia() diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__init__.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af630c55f309014c29dd447c67b47a20548dd18d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_conv_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_conv_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..149659bd9fdd973d2856eb0d180181d54d79b516 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_conv_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3be2ae40f4a258c71313a5dcc87315276ea4dc0e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e30363738af1b96c60a3f689c5248e000295142 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_universal_gemm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_universal_gemm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4742b706be9446ef7a0f510f3ab672d1f8b9461a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_tile_universal_gemm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_universal_gemm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_universal_gemm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0c42b2a61172fb0010f1f513ea5a49f0b63d1e8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/ck_universal_gemm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/compile_command.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/compile_command.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..306e9a10270ad28fbe3f1486c560eac62abbb9b9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/compile_command.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_benchmark_request.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_benchmark_request.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..049d1c9de5bc3d45fcdb5af8712b581eb0269826 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_benchmark_request.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_cpp_scheduling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_cpp_scheduling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..115be847ad3a71ec3b7b93c3de5c8bcf8118ef02 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_cpp_scheduling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_kernel.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4dd57dd30db43fdc970ee0f915086594d7a549b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_kernel.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d25f3af2f6690832b5023f8d9bfbcff7abd18dea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template_buffer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template_buffer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6567d84f7f84ea9037af5b8a41617c8449cbb8c9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_template_buffer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05832191030aeb705dc7dc3fde63d5e8f7238ea4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/__pycache__/rocm_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_conv_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_conv_template.py new file mode 100644 index 0000000000000000000000000000000000000000..5210b5fbd577f1d6623819ac50f55535bc7c9c44 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_conv_template.py @@ -0,0 +1,623 @@ +# mypy: allow-untyped-defs +import copy +import logging +import random +from typing import Any +from typing_extensions import override + +from torch._inductor.virtualized import V + +from .rocm_template import ArgInfo + + +try: + import ck4inductor # type: ignore[import] +except ImportError: + ck4inductor = None + +if ck4inductor is not None: + from ck4inductor.grouped_conv_fwd.gen_instances import ( # type: ignore[import] + gen_conv_ops_library, + ) + from ck4inductor.grouped_conv_fwd.op import ( # type: ignore[import] # noqa: TCH002 + CKGroupedConvFwdOp, + ) +else: + + def gen_conv_ops_library(): + return [] + + +from torch._inductor import config +from torch._inductor.codegen.rocm.ck_template import CKTemplate +from torch._inductor.codegen.rocm.rocm_kernel import ROCmTemplateKernel +from torch._inductor.utils import IndentedBuffer + + +log = logging.getLogger(__name__) + + +def torch_layout_to_ck_layouts(torch_layout): + # logically, torch tensors are always NCHW, + # and channels-last memory layout is visible in the strides + if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1): + # when input or output is NCHW + # NB: torch.conv2d result is always NCHW + return ["NGCHW", "GKCYX", "NGKHW"] + elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1): + # when input or output or weight is channels-last + return ["NHWGC", "GKYXC", "NHWGK"] + else: + return None + + +def torch_layout_to_ck_input_layout(torch_layout): + if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1): + return "NGCHW" + elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1): + return "NHWGC" + else: + return None + + +def torch_layout_to_ck_weight_layout(torch_layout): + if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1): + return "GKCYX" + elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1): + return "GKYXC" + else: + return None + + +def torch_layout_to_ck_output_layout(torch_layout): + if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1): + return "NGKHW" + elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1): + return "NHWGK" + else: + return None + + +class CKGroupedConvFwdTemplate(CKTemplate): + conv_template = r""" + {{headers}} + {{globals}} + {{instance_definition}} + extern "C" { + PT_EXPORT {{kernel_definition}} { + auto conv = {{instance_type}} {}; + auto invoker = conv.MakeInvoker(); + + using ck::index_t; + + constexpr index_t NumDTensor = {{n_d_tensors}}; + constexpr index_t NDimSpatial = {{n_dim_spatial}}; + const std::vector FilterSize = { FilterSize_0, FilterSize_1 }; + const std::vector InputSize = { InputSize_0, InputSize_1 }; + const std::vector ConvolutionStrides = { ConvolutionStrides_0, ConvolutionStrides_1 }; + const std::vector Dilations = { Dilations_0, Dilations_1 }; + const std::vector LeftPads = { LeftPads_0, LeftPads_1 }; + const std::vector RightPads = { RightPads_0, RightPads_1 }; + + + auto conv_param = ck::utils::conv::ConvParam { + NDimSpatial, + GroupCount, + NBatch, + NOutChannels, + NInChannels, + FilterSize, + InputSize, + ConvolutionStrides, + Dilations, + LeftPads, + RightPads, + }; + + using InLayout = ck::tensor_layout::convolution::{{input_layout}}; + using WeiLayout = ck::tensor_layout::convolution::{{weight_layout}}; + using OutLayout = ck::tensor_layout::convolution::{{output_layout}}; + + const auto in_g_n_c_wis_desc = + ck::utils::conv::make_input_host_tensor_descriptor_g_n_c_wis_packed(conv_param); + const auto wei_g_k_c_xs_desc = + ck::utils::conv::make_weight_host_tensor_descriptor_g_k_c_xs_packed(conv_param); + const auto out_g_n_k_wos_desc = + ck::utils::conv::make_output_host_tensor_descriptor_g_n_k_wos_packed(conv_param); + + const void* p_a = input; + const void* p_b = weight; + const std::array p_ds; + void* p_e = output; + std::array a_g_n_c_wis_lengths; + std::array a_g_n_c_wis_strides; + std::array b_g_k_c_xs_lengths; + std::array b_g_k_c_xs_strides; + std::array, NumDTensor> ds_g_n_k_wos_lengths; + std::array, NumDTensor> ds_g_n_k_wos_strides; + std::array e_g_n_k_wos_lengths; + std::array e_g_n_k_wos_strides; + std::array conv_filter_strides; + std::array conv_filter_dilations; + std::array input_left_pads; + std::array input_right_pads; + const auto a_element_op = PassThrough {}; + const auto b_element_op = PassThrough {}; + const auto cde_element_op = PassThrough {}; + + auto copy = [](auto& x, auto& y) { ck::ranges::copy(x, y.begin()); }; + + copy(in_g_n_c_wis_desc.GetLengths(), a_g_n_c_wis_lengths); + copy(in_g_n_c_wis_desc.GetStrides(), a_g_n_c_wis_strides); + copy(wei_g_k_c_xs_desc.GetLengths(), b_g_k_c_xs_lengths); + copy(wei_g_k_c_xs_desc.GetStrides(), b_g_k_c_xs_strides); + copy(out_g_n_k_wos_desc.GetLengths(), e_g_n_k_wos_lengths); + copy(out_g_n_k_wos_desc.GetStrides(), e_g_n_k_wos_strides); + copy(conv_param.conv_filter_strides_, conv_filter_strides); + copy(conv_param.conv_filter_dilations_, conv_filter_dilations); + copy(conv_param.input_left_pads_, input_left_pads); + copy(conv_param.input_right_pads_, input_right_pads); + + auto argument = conv.MakeArgument( + p_a, + p_b, + p_ds, + p_e, + a_g_n_c_wis_lengths, + a_g_n_c_wis_strides, + b_g_k_c_xs_lengths, + b_g_k_c_xs_strides, + ds_g_n_k_wos_lengths, + ds_g_n_k_wos_strides, + e_g_n_k_wos_lengths, + e_g_n_k_wos_strides, + conv_filter_strides, + conv_filter_dilations, + input_left_pads, + input_right_pads, + a_element_op, + b_element_op, + cde_element_op + ); + if (!conv.IsSupportedArgument(argument)) { + // we do our best to statically avoid this case in `filter_op` + std::cerr << "invalid argument for conv instance " << conv.GetTypeString() << std::endl; + argument.Print(); + return -23; + } + if (workspace_size) { + *workspace_size = conv.GetWorkSpaceSize(&argument); + return 0; + } + + if (p_a == nullptr) { + std::cerr << "p_a is nullptr" << std::endl; + return -1; + } + if (p_b == nullptr) { + std::cerr << "p_b is nullptr" << std::endl; + return -1; + } + if (p_e == nullptr) { + std::cerr << "p_e is nullptr" << std::endl; + return -1; + } + + // when debugging, do time kernel to serialize launches + auto stream_config = StreamConfig{stream, /* time kernel */ false, /* log level */ 0}; + + if (workspace != nullptr) { + conv.SetWorkSpacePointer(&argument, workspace, stream_config); + } + + // run the kernel + float elapsed_time = invoker.Run(argument, stream_config); + return 0; + } // kernel definition + } // extern C + + #ifdef GENERATE_CK_STANDALONE_RUNNER + int main(int argc, char** argv) { + (void) argc; + (void) argv; + return 0; + } + #endif // GENERATE_CK_STANDALONE_RUNNER +""" + + def globals(self) -> IndentedBuffer: + res = super().globals() + res.splice( + """ + // CK conv globals + + using NWC = ck::tensor_layout::convolution::NWC; + using NHWC = ck::tensor_layout::convolution::NHWC; + using NDHWC = ck::tensor_layout::convolution::NDHWC; + + using KXC = ck::tensor_layout::convolution::KXC; + using KYXC = ck::tensor_layout::convolution::KYXC; + using KZYXC = ck::tensor_layout::convolution::KZYXC; + + using NWK = ck::tensor_layout::convolution::NWK; + using NHWK = ck::tensor_layout::convolution::NHWK; + using NDHWK = ck::tensor_layout::convolution::NDHWK; + + using GNWC = ck::tensor_layout::convolution::GNWC; + using GNHWC = ck::tensor_layout::convolution::GNHWC; + using GNDHWC = ck::tensor_layout::convolution::GNDHWC; + + using GKXC = ck::tensor_layout::convolution::GKXC; + using GKYXC = ck::tensor_layout::convolution::GKYXC; + using GKZYXC = ck::tensor_layout::convolution::GKZYXC; + + using GKCX = ck::tensor_layout::convolution::GKCX; + using GKCYX = ck::tensor_layout::convolution::GKCYX; + using GKCZYX = ck::tensor_layout::convolution::GKCZYX; + + using GNWK = ck::tensor_layout::convolution::GNWK; + using GNHWK = ck::tensor_layout::convolution::GNHWK; + using GNDHWK = ck::tensor_layout::convolution::GNDHWK; + + using NGKW = ck::tensor_layout::convolution::NGKW; + using NGKHW = ck::tensor_layout::convolution::NGKHW; + using NGKDHW = ck::tensor_layout::convolution::NGKDHW; + + using NWGC = ck::tensor_layout::convolution::NWGC; + using NHWGC = ck::tensor_layout::convolution::NHWGC; + using NDHWGC = ck::tensor_layout::convolution::NDHWGC; + + using KXGC = ck::tensor_layout::convolution::KXGC; + using KYXGC = ck::tensor_layout::convolution::KYXGC; + using KZYXGC = ck::tensor_layout::convolution::KZYXGC; + + using NWGK = ck::tensor_layout::convolution::NWGK; + using NHWGK = ck::tensor_layout::convolution::NHWGK; + using NDHWGK = ck::tensor_layout::convolution::NDHWGK; + + using NGCW = ck::tensor_layout::convolution::NGCW; + using NGCHW = ck::tensor_layout::convolution::NGCHW; + using NGCDHW = ck::tensor_layout::convolution::NGCDHW; + + using G_K = ck::tensor_layout::convolution::G_K; + + using BlockGemmPipelineScheduler = ck::BlockGemmPipelineScheduler; + using GemmSpecialization = ck::tensor_operation::device::GemmSpecialization; + using BlockGemmPipelineVersion = ck::BlockGemmPipelineVersion; + + using ConvolutionForwardSpecialization = ck::tensor_operation::device::ConvolutionForwardSpecialization; + + using OutElementOp = PassThrough; + + namespace ck { + namespace utils { + namespace conv { + + ConvParam::ConvParam(ck::index_t n_dim, + ck::index_t group_count, + ck::index_t n_batch, + ck::index_t n_out_channels, + ck::index_t n_in_channels, + const std::vector& filters_len, + const std::vector& input_len, + const std::vector& strides, + const std::vector& dilations, + const std::vector& left_pads, + const std::vector& right_pads) + : num_dim_spatial_(static_cast(n_dim)), + G_(static_cast(group_count)), + N_(static_cast(n_batch)), + K_(static_cast(n_out_channels)), + C_(static_cast(n_in_channels)), + filter_spatial_lengths_(num_dim_spatial_), + input_spatial_lengths_(num_dim_spatial_), + output_spatial_lengths_(num_dim_spatial_), + conv_filter_strides_(num_dim_spatial_), + conv_filter_dilations_(num_dim_spatial_), + input_left_pads_(num_dim_spatial_), + input_right_pads_(num_dim_spatial_) + { + if(static_cast(filter_spatial_lengths_.size()) != num_dim_spatial_ || + static_cast(input_spatial_lengths_.size()) != num_dim_spatial_ || + static_cast(conv_filter_strides_.size()) != num_dim_spatial_ || + static_cast(conv_filter_dilations_.size()) != num_dim_spatial_ || + static_cast(input_left_pads_.size()) != num_dim_spatial_ || + static_cast(input_right_pads_.size()) != num_dim_spatial_) + { + throw( + std::runtime_error("ConvParam::ConvParam: " + "parameter size is different from number of declared dimensions!")); + } + + for(ck::index_t i = 0; i < num_dim_spatial_; ++i) + { + filter_spatial_lengths_[i] = static_cast(filters_len[i]); + input_spatial_lengths_[i] = static_cast(input_len[i]); + conv_filter_strides_[i] = static_cast(strides[i]); + conv_filter_dilations_[i] = static_cast(dilations[i]); + input_left_pads_[i] = static_cast(left_pads[i]); + input_right_pads_[i] = static_cast(right_pads[i]); + + // XEff = (X - 1) * conv_dilation_w + 1; + // Wo = (Wi + in_left_pad_w + in_right_pad_w - XEff) / conv_stride_w + 1; + const ck::long_index_t x_eff = + (filter_spatial_lengths_[i] - 1) * conv_filter_dilations_[i] + 1; + + output_spatial_lengths_[i] = + (input_spatial_lengths_[i] + input_left_pads_[i] + input_right_pads_[i] - x_eff) / + conv_filter_strides_[i] + + 1; + } + } + + } // namespace conv + } // namespace utils + } // namespace ck + + // NOTE: HostTensorDescriptor methods are declared in CK headers but defined + // in CK's utility library. For architectural reasons, generated code doesn't + // link with this library, so we provide local definitions here. + // CalculateStrides is omitted as it became a template method in CK 4266f867. + const std::vector& ck::HostTensorDescriptor::GetLengths() const { return mLens; } + const std::vector& ck::HostTensorDescriptor::GetStrides() const { return mStrides; } + std::size_t ck::HostTensorDescriptor::GetNumOfDimension() const { return mLens.size(); } + """ + ) + return res + + def header(self) -> IndentedBuffer: + res = super().header() + res.splice( + """ + // CK conv headers + + #include "ck/tensor_operation/gpu/device/impl/device_grouped_conv_fwd_multiple_abd_xdl_cshuffle_v3.hpp" + #include "ck/tensor_operation/gpu/device/convolution_forward_specialization.hpp" + #include "ck/tensor_operation/gpu/device/gemm_specialization.hpp" + + #include "ck/library/utility/convolution_parameter.hpp" + #include "ck/library/utility/convolution_host_tensor_descriptor_helper.hpp" + """ + ) + return res + + @staticmethod + def add_ck_conv_choices( + choices, + layout, + input_nodes, + *, + stride, + padding, + dilation, + groups, + n_spatial_dimensions, + ): + template = CKGroupedConvFwdTemplate( + input_nodes, + layout, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + n_spatial_dimensions=n_spatial_dimensions, + ) + ops = template.gen_ops() + for op in ops: + template.maybe_append_choice( + choices, + op=op, + ) + + def __init__( + self, + input_nodes, + layout, + *, + stride, + padding, + dilation, + groups, + n_spatial_dimensions, + ): + super().__init__( + "ck_conv_template", + input_nodes, + layout, + ) + self.stride = stride + self.padding = padding + self.dilation = dilation + self.groups = groups + self.n_spatial_dimensions = n_spatial_dimensions + + def filter_op(self, op: "CKGroupedConvFwdOp"): # type: ignore[name-defined] + metas = [ + T.get_layout() + for T in [*self.input_nodes, self.output_node] + if T is not None + ] + X_meta = metas[0] + W_meta = metas[1] + Y_meta = metas[-1] + # disable the instance if dtypes don't match + if op.a_element_dtype != self._TORCH_DTYPE_TO_CK[X_meta.dtype]: + return None + if op.b_element_dtype != self._TORCH_DTYPE_TO_CK[W_meta.dtype]: + return None + if op.e_element_dtype != self._TORCH_DTYPE_TO_CK[Y_meta.dtype]: + return None + # disable the instance if layouts don't match + if op.a_layout != torch_layout_to_ck_input_layout(X_meta): + return None + if op.b_layout != torch_layout_to_ck_weight_layout(W_meta): + return None + if op.e_layout != torch_layout_to_ck_output_layout(Y_meta): + return None + # disable the instance if number of spatial dimensions doesn't match + if op.n_dim_spatial != self.n_spatial_dimensions: + return None + # disable 1x1 and odd-channels conv specializations for now + if "Default" not in op.conv_forward_specialization: + return None + if self.is_blocked_by_tf32_setting(op): + return None + return op + + def gen_ops(self): + unfiltered_instances = gen_conv_ops_library() + + filtered_instances = list( + filter(lambda op: self.filter_op(op), unfiltered_instances) + ) + # NB: when using a fixed list order, most likely we will pick the subset of instances + # which are very similar to each other. Randomizing the choice seems to solve this. + random.seed(-11) + chosen_instances = ( + random.sample( + filtered_instances, + min(len(filtered_instances), config.rocm.ck_max_profiling_configs), + ) + if config.rocm.ck_max_profiling_configs + else filtered_instances + ) + log.debug( + "generated %d ck instances after filter: %s", + len(chosen_instances), + chosen_instances, + ) + return chosen_instances + + def emit_ck_instance(self, op: "CKGroupedConvFwdOp") -> tuple[str, str]: # type: ignore[name-defined] + # The Jinja template for generating a C++ type alias *definition* for a Universal GEMM instance + template_definition = r""" + // Gemm operator {{operation_name}} + using Operation_{{operation_name}} = + ck::tensor_operation::device::DeviceGroupedConvFwdMultipleABD_Xdl_CShuffle_V3< + {{template_params}}>; + +""" + # The Jinja template for generating a C++ type alias *usage* for a Universal GEMM instance + template_type = r""" + Operation_{{operation_name}} +""" + template_params = [] + for field_name, field_value in op.dict_items(): + if isinstance(field_value, tuple): + tuple_elements = ", ".join(map(str, iter(field_value))) + if "ds" in field_name: # element type and layout for bias + arg = f"/* {field_name} */ Tuple<{tuple_elements}>" + else: # tile shape + arg = f"/* {field_name} */ S<{tuple_elements}>" + # pyrefly: ignore [bad-argument-type] + template_params.append(arg) + else: + if field_value is not None: + # pyrefly: ignore [bad-argument-type] + template_params.append(f"/* {field_name} */ {field_value}") + return self._template_from_string(template_definition).render( + operation_name=op.name(), + template_params=(",\n" + 12 * " ").join(template_params), + ), self._template_from_string(template_type).render(operation_name=op.name()) + + def render( # type: ignore[override] + self, + kernel: ROCmTemplateKernel, + op: "CKGroupedConvFwdOp", # type: ignore[name-defined] + **kwargs, + ) -> str: + template_buffer_node = kwargs.get("template_buffer_node") + if template_buffer_node is not None: + self.output_node = template_buffer_node + X, W = self.input_nodes[0], self.input_nodes[1] + Y = self.output_node + Bias = self.input_nodes[2] if 3 == len(self.input_nodes) else None + + op = copy.deepcopy(op) + + instance_definition, instance_type = self.emit_ck_instance(op) + + size_arg_strs = [ + "GroupCount", + "NBatch", + "NOutChannels", + "NInChannels", + "FilterSize_0", + "FilterSize_1", + "InputSize_0", + "InputSize_1", + "ConvolutionStrides_0", + "ConvolutionStrides_1", + "Dilations_0", + "Dilations_1", + "LeftPads_0", + "LeftPads_1", + "RightPads_0", + "RightPads_1", + ] + + return self._template_from_string(self.conv_template).render( + headers=self.header().getvalue(), + globals=self.globals().getvalue(), + instance_definition=instance_definition, + instance_type=instance_type, + kernel_definition=kernel.def_kernel( + inputs=[X, W, Bias] if Bias is not None else [X, W], + outputs=[Y], + names_str="input, weight, bias, output" + if Bias is not None + else "input, weight, output", + size_args=[f"int32_t {arg}" for arg in size_arg_strs], + ), + n_d_tensors=1 if Bias is not None else 0, + n_dim_spatial=self.n_spatial_dimensions, + input_layout=op.a_layout, + weight_layout=op.b_layout, + output_layout=op.e_layout, + ) + + def size_args(self): + x, w = self.input_nodes[0], self.input_nodes[1] + y = self.output_node + + group_count = self.groups + n_batch = x.shape[0] # type: ignore[index] + n_out_channels = y.shape[1] # type: ignore[index] + n_in_channels = x.shape[1] # type: ignore[index] + + filter_size_0, filter_size_1 = w.shape[2:4] # type: ignore[index] + input_size_0, input_size_1 = x.shape[2:4] # type: ignore[index] + convolution_strides_0, convolution_strides_1 = self.stride + dilations_0, dilations_1 = self.dilation + left_pads_0, left_pads_1 = self.padding + right_pads_0, right_pads_1 = self.padding + + return ( + group_count, + n_batch, + n_out_channels, + n_in_channels, + filter_size_0, + filter_size_1, + input_size_0, + input_size_1, + convolution_strides_0, + convolution_strides_1, + dilations_0, + dilations_1, + left_pads_0, + left_pads_1, + right_pads_0, + right_pads_1, + ) + + @override + def get_runtime_arg_info(self) -> list[ArgInfo]: + return [] + + @override + def get_runtime_arg_values(self, **kwargs: Any) -> list[Any]: + """ + Helper method to retrieve runtime args from generate kwargs + """ + return [] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_template.py new file mode 100644 index 0000000000000000000000000000000000000000..863033385ae87716b5029501ed9e15bad96a1941 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_template.py @@ -0,0 +1,125 @@ +from typing import Any +from typing_extensions import override + +import torch +from torch._inductor.codegen.rocm.rocm_template import ROCmTemplate +from torch._inductor.ir import IRNode +from torch._inductor.utils import IndentedBuffer + +from .rocm_template import ArgInfo + + +class CKTemplate(ROCmTemplate): + """ + Base class for generating CK templates, has common, i.e. non-gemm-specific, code generation logic + """ + + _TORCH_DTYPE_TO_CK = { + torch.float32: "F32", + torch.float64: "F64", + torch.float16: "F16", + torch.bfloat16: "BF16", + torch.int32: "I32", + torch.int8: "I8", + torch.float8_e4m3fnuz: "F8", # gfx94 + torch.float8_e4m3fn: "F8", # gfx95 + torch.float8_e5m2fnuz: "BF8", # gfx94 + torch.float8_e5m2: "BF8", # gfx95 + } + + @staticmethod + def is_blocked_by_tf32_setting(op) -> bool: + """True if op internally computes in TF32 but the user has disabled TF32. + + CK exposes this via {a,b}_compute_dtype on op (None == strict compute + matching the element type). Some F32 instances ship with `TF32` here. + """ + if torch.backends.cuda.matmul.allow_tf32: + return False + return ( + getattr(op, "a_compute_dtype", None) == "TF32" + or getattr(op, "b_compute_dtype", None) == "TF32" + ) + + def header(self) -> IndentedBuffer: + res = super().header() + res.splice( + """ + // CK headers + + #ifdef DEBUG_LOG + #define DEBUG_LOG_TMP DEBUG_LOG + #undef DEBUG_LOG + #else + #define DEBUG_LOG_TMP 0 + #endif + #include "ck/ck.hpp" + #undef DEBUG_LOG + #define DEBUG_LOG DEBUG_LOG_TMP + + #include "ck/utility/data_type.hpp" + #include "ck/library/utility/check_err.hpp" + #include "ck/library/utility/device_memory.hpp" + #include "ck/library/utility/fill.hpp" + #include "ck/library/utility/host_tensor.hpp" + #include "ck/library/utility/host_tensor_generator.hpp" + #include "ck/library/utility/literals.hpp" + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = super().globals() + res.splice( + """ + // CK globals + + template + using S = ck::Sequence; + + template + using Tuple = ck::Tuple; + + using PassThrough = ck::tensor_operation::element_wise::PassThrough; + using Bilinear = ck::tensor_operation::element_wise::Bilinear; + using Scale = ck::tensor_operation::element_wise::Scale; + using ScaleAdd = ck::tensor_operation::element_wise::ScaleAdd; + using MultiplyMultiply = ck::tensor_operation::element_wise::MultiplyMultiply; + + // see "composable_kernel/include/ck/utility/data_type.hpp" + using F8 = ck::f8_t; + using BF8 = ck::bf8_t; + using F16 = ck::half_t; + using F32 = float; + // using F64 = double; + using BF16 = ck::bhalf_t; + using TF32 = ck::tf32_t; + // using I32 = int32_t; + // using I8 = int8_t; + // using I4 = ck::int4_t; + + #if DEBUG_LOG + static constexpr auto kDEBUG_LOG = 1; + #else + static constexpr auto kDEBUG_LOG = 0; + #endif + """ + ) + return res + + def torch_type_to_ck(self, node: IRNode, ptr: str) -> str: + if node is None: + return ptr + else: + return f"({self._TORCH_DTYPE_TO_CK.get(node.get_dtype())}*)({ptr})" + + @override + def get_runtime_arg_info(self) -> list[ArgInfo]: + return [ArgInfo("kBatch", "int32_t")] + + @override + def get_runtime_arg_values(self, **kwargs: Any) -> list[Any]: + """ + Helper method to retrieve runtime args from generate kwargs + """ + return [kwargs[arg.name] for arg in self.get_runtime_arg_info()] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_template.py new file mode 100644 index 0000000000000000000000000000000000000000..70d31d635cc36dca295b1d82066376a1185c4da9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_template.py @@ -0,0 +1,58 @@ +import torch +from torch._inductor.codegen.rocm.rocm_template import ROCmTemplate +from torch._inductor.ir import IRNode +from torch._inductor.utils import IndentedBuffer + + +class CKTileTemplate(ROCmTemplate): + """ + Base class for generating CK templates, has common, i.e. non-gemm-specific, code generation logic + """ + + _TORCH_DTYPE_TO_CK = { + torch.float32: "F32", + torch.float64: "F64", + torch.float16: "F16", + torch.bfloat16: "BF16", + torch.int32: "I32", + torch.int8: "I8", + torch.float8_e4m3fnuz: "F8", # gfx94 + torch.float8_e4m3fn: "F8", # gfx95 + torch.float8_e5m2fnuz: "BF8", # gfx94 + torch.float8_e5m2: "BF8", # gfx95 + } + + ck_dtype_to_size = { + "FP16": 2, + "BF16": 2, + } + + def header(self) -> IndentedBuffer: + res = super().header() + res.splice( + """ + // CK headers + #include "ck_tile/core.hpp" + + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = super().globals() + res.splice( + """ + using F8 = ck_tile::fp8_t; + using BF8 = ck_tile::bf8_t; + using F16 = ck_tile::half_t; + using F32 = float; + using BF16 = ck_tile::bfloat16_t; + """ + ) + return res + + def torch_type_to_ck(self, node: IRNode, ptr: str) -> str: + if node is None: + return ptr + else: + return f"({self._TORCH_DTYPE_TO_CK.get(node.get_dtype())}*)({ptr})" diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..b08ef49ea7aaebe0462d586aac9d962b7ce6ef30 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py @@ -0,0 +1,878 @@ +# mypy: allow-untyped-defs, disable-error-code="attr-defined, valid-type" +import functools +import logging +import random +from collections import defaultdict +from dataclasses import asdict, dataclass +from typing import Any + +import torch +from torch._inductor import config +from torch._inductor.codegen.rocm.ck_tile_template import CKTileTemplate +from torch._inductor.codegen.rocm.rocm_kernel import ROCmTemplateKernel +from torch._inductor.codegen.rocm.rocm_template import ArgInfo +from torch._inductor.ir import Buffer, Layout +from torch.utils._ordered_set import OrderedSet + +from ...utils import IndentedBuffer + + +log = logging.getLogger(__name__) + + +def is_static_int(number): + import sympy + + return isinstance(number, (int, sympy.Integer)) + + +def torch_layout_to_ck_layout(torch_layout): + if torch_layout.stride[-1] == 1: + return "Row" + elif torch_layout.stride[-2] == 1: + return "Col" + else: + return None + + +@dataclass +class CKTileGemmOperation: + layout_a: str + layout_b: str + layout_c: str + + datatype_a: str + datatype_b: str + datatype_c: str + + tile_m: int + tile_n: int + tile_k: int + + warp_m: int + warp_n: int + warp_k: int + + warp_tile_m: int + warp_tile_n: int + warp_tile_k: int + + m_is_padded: str + n_is_padded: str + k_is_padded: str + + pipeline: str + scheduler: str + epilogue: str + + def layout_repr(self): + return f"{self.layout_a[0]}{self.layout_b[0]}{self.layout_c[0]}" + + def dtype_repr(self): + return f"{self.datatype_a}{self.datatype_b}{self.datatype_c}" + + def tile_sizes(self): + return "_".join( + [ + f"{self.tile_m}{self.tile_n}{self.tile_k}", + f"{self.warp_m}{self.warp_n}{self.warp_k}", + f"{self.warp_tile_m}{self.warp_tile_n}{self.warp_tile_k}", + ] + ) + + def name(self): + return "ck_tile_gemm_universal_" + "_".join( + [ + f"{self.layout_repr()}", + f"{self.dtype_repr()}", + f"{self.tile_sizes()}", + f"{self.pipeline}", + f"{self.scheduler}", + f"{self.epilogue}", + ] + ) + + def dict_items(self): + return asdict(self).items() + + +@functools.cache +def ops(): + """ + Generate the supported instance dataclasses + """ + import itertools + + compute_v3_instances = [ + CKTileGemmOperation( + layout_a=layout_a, + layout_b=layout_b, + layout_c=layout_c, + datatype_a=datatype_a, + datatype_b=datatype_b, + datatype_c=datatype_c, + tile_m=tile_m, + tile_n=tile_n, + tile_k=tile_k, + warp_m=warp_m, + warp_n=warp_n, + warp_k=warp_k, + warp_tile_m=warp_tile_m, + warp_tile_n=warp_tile_n, + warp_tile_k=warp_tile_k, + m_is_padded=m_is_padded, + n_is_padded=n_is_padded, + k_is_padded=k_is_padded, + pipeline="CompV3", + scheduler="Intrawave", + epilogue=epilogue, + ) + for (layout_a, layout_b, layout_c) in [ + ("Row", "Row", "Row"), + ("Row", "Col", "Row"), + ] + for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3] + for (tile_m, tile_n, tile_k) in [(256, 256, 32), (256, 256, 64)] + for (warp_m, warp_n, warp_k) in [(2, 2, 1)] + for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)] + for m_is_padded in ["true", "false"] + for n_is_padded in ["true", "false"] + for k_is_padded in ["true", "false"] + for epilogue in ["Default", "CShuffle"] + ] + + compute_v4_instances = [ + CKTileGemmOperation( + layout_a=layout_a, + layout_b=layout_b, + layout_c=layout_c, + datatype_a=datatype_a, + datatype_b=datatype_b, + datatype_c=datatype_c, + tile_m=tile_m, + tile_n=tile_n, + tile_k=tile_k, + warp_m=warp_m, + warp_n=warp_n, + warp_k=warp_k, + warp_tile_m=warp_tile_m, + warp_tile_n=warp_tile_n, + warp_tile_k=warp_tile_k, + m_is_padded=m_is_padded, + n_is_padded=n_is_padded, + k_is_padded=k_is_padded, + pipeline="CompV4", + scheduler="Intrawave", + epilogue=epilogue, + ) + for (layout_a, layout_b, layout_c) in [ + ("Row", "Row", "Row"), + ("Row", "Col", "Row"), + ] + for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3] + for (tile_m, tile_n, tile_k) in [ + (256, 256, 32) + ] # half the tile size since it has double buffering + for (warp_m, warp_n, warp_k) in [(2, 2, 1)] + for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)] + for m_is_padded in ["true", "false"] + for n_is_padded in ["true", "false"] + for k_is_padded in ["true", "false"] + for epilogue in ["Default", "CShuffle"] + ] + + mem_instances = [ + CKTileGemmOperation( + layout_a=layout_a, + layout_b=layout_b, + layout_c=layout_c, + datatype_a=datatype_a, + datatype_b=datatype_b, + datatype_c=datatype_c, + tile_m=tile_m, + tile_n=tile_n, + tile_k=tile_k, + warp_m=warp_m, + warp_n=warp_n, + warp_k=warp_k, + warp_tile_m=warp_tile_m, + warp_tile_n=warp_tile_n, + warp_tile_k=warp_tile_k, + m_is_padded=m_is_padded, + n_is_padded=n_is_padded, + k_is_padded=k_is_padded, + pipeline="Mem", + scheduler=scheduler, + epilogue=epilogue, + ) + for (layout_a, layout_b, layout_c) in [ + ("Row", "Row", "Row"), + ("Row", "Col", "Row"), + ] + for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3] + for (tile_m, tile_n, tile_k) in [(256, 256, 32), (256, 256, 64)] + for (warp_m, warp_n, warp_k) in [(2, 2, 1)] + for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)] + for m_is_padded in ["true", "false"] + for n_is_padded in ["true", "false"] + for k_is_padded in ["true", "false"] + for scheduler in ["Intrawave", "Interwave"] + for epilogue in ["Default", "CShuffle"] + ] + + return list( + itertools.chain(compute_v3_instances, compute_v4_instances, mem_instances) + ) + + +class CKTileGemmTemplate(CKTileTemplate): + """ + This class is used for rendering CK-Tile Universal GEMM kernels + """ + + gemm_template = r"""{{version_comment}} + {{headers}} + {{globals}} + {{instance_definition}} + extern "C" { + PT_EXPORT {{kernel_definition}} { + + using {{instance_namespace}}::BaseGemmPipeline; + using {{instance_namespace}}::TilePartitioner; + + constexpr auto TileK = {{instance_namespace}}::TileK; + constexpr auto kPrefetchStages = BaseGemmPipeline::PrefetchStages; + + const auto BiasTerms = std::array (); + const auto BiasStrides = std::array (); + + auto kargs = ck_tile::UniversalGemmKernelArgs<> { + {X}, + {W}, + BiasTerms, + Y, + M, + N, + K, + {LDA}, + {LDB}, + BiasStrides, + LDC, + kBatch + }; + + if (workspace_size) { + *workspace_size = 0; + return 0; + } + + const ck_tile::index_t k_grain = kBatch * TileK; + const ck_tile::index_t K_split = (K + k_grain - 1) / k_grain * TileK; + const ck_tile::index_t num_loop = TilePartitioner::GetLoopNum(K_split); + const bool has_hot_loop = BaseGemmPipeline::BlockHasHotloop(num_loop); + const ck_tile::TailNumber tail_num = BaseGemmPipeline::GetBlockLoopTailNum(num_loop); + + // run the kernel + const auto Run = [&](const auto has_hot_loop_, const auto tail_number_) { + constexpr bool has_hot_loop_v = has_hot_loop_.value; + constexpr auto tail_number_v = tail_number_.value; + + using Kernel = {{instance_namespace}}::Kernel; + + if (!Kernel::IsSupportedArgument(kargs)) { + // we do our best to statically avoid this case in `filter_op` + throw std::runtime_error("invalid argument"); + } + auto stream_config = ck_tile::stream_config{stream}; + auto grid_size = Kernel::GridSize(M, N, kBatch); + auto block_size = Kernel::BlockSize(); + constexpr auto lds_bytes = 0; + constexpr auto kBlockPerCU = 1; + auto gemm = ck_tile::make_kernel(Kernel{}, grid_size, block_size, lds_bytes, kargs); + ck_tile::launch_kernel(stream_config, gemm); + }; + + BaseGemmPipeline::TailHandler(Run, has_hot_loop, tail_num); + + return 0; + } // kernel definition + } // extern C + """ + + def __init__( + self, + input_nodes: list[Buffer], + layout: Layout, + ) -> None: + super().__init__( + "ck_tile_gemm_template", + input_nodes=input_nodes, + layout=layout, + ) + + def header(self) -> IndentedBuffer: + res = super().header() + res.splice( + """ + // CK GEMM header(s) + + #include "ck_tile/ops/gemm.hpp" + #include "ck_tile/ops/epilogue.hpp" + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = super().globals() + res.splice( + """ + // CK GEMM globals + + using Row = ck_tile::tensor_layout::gemm::RowMajor; + using Col = ck_tile::tensor_layout::gemm::ColumnMajor; + """ + ) + return res + + def check_dtypes(self, op: "CKTileGemmOperation"): + X_dtype, W_dtype, out_dtype = [ + T.get_layout().dtype for T in [*self.input_nodes, self.output_node] + ] + if op.datatype_a != self._TORCH_DTYPE_TO_CK[X_dtype]: + return False + if op.datatype_b != self._TORCH_DTYPE_TO_CK[W_dtype]: + return False + if op.datatype_c != self._TORCH_DTYPE_TO_CK[out_dtype]: + return False + return True + + def check_layouts(self, op: "CKTileGemmOperation"): + X_layout, W_layout, out_layout = [ + torch_layout_to_ck_layout(T.get_layout()) + for T in [*self.input_nodes, self.output_node] + ] + if op.layout_a != X_layout: + return False + if op.layout_b != W_layout: + return False + if op.layout_c != out_layout: + return False + return True + + def get_gemm_problem_size(self): + X_size, W_size = [T.get_layout().size for T in [*self.input_nodes]] + + M, K = X_size + _, N = W_size + + return M, N, K + + def check_block_tiles(self, op: "CKTileGemmOperation"): + """ + The contiguous dimension of a tensor must be divisible by the block tile size + This helper function enforces it for the inputs and the output. + """ + M, N, K = self.get_gemm_problem_size() + + def check(dim_size, tile_size, is_padded): + if ( + is_static_int(dim_size) + and dim_size % tile_size != 0 + and is_padded == "false" + ): + return False + return True + + if op.layout_a == "Row": + # handle in kBatch check + return True + elif op.layout_a == "Col": + if not check(M, op.tile_m, op.m_is_padded): + return False + else: + raise AssertionError(f"Invalid layout {op.layout_a=}") + + if op.layout_b == "Row": + if not check(N, op.tile_n, op.n_is_padded): + return False + elif op.layout_b == "Col": + # handle in kBatch check + return True + else: + raise AssertionError(f"Invalid {op.layout_b=}") + + if op.layout_c == "Row": + if not check(N, op.tile_n, op.n_is_padded): + return False + elif op.layout_c == "Col": + if not check(M, op.tile_m, op.m_is_padded): + return False + else: + raise AssertionError(f"Invalid layout {op.layout_c=}") + + return True + + def check_alignments(self, op: "CKTileGemmOperation"): + """ + The contiguous dimension of a tensor must be divisible by the vector load size. + """ + M, N, K = self.get_gemm_problem_size() + + def max_alignment(contiguous_elements_per_tile, elements_per_thread, ck_dtype): + for vector_load_bytes in (16, 8, 4, 2, 1): + alignment = vector_load_bytes // self.ck_dtype_to_size[ck_dtype] + if ( + alignment > 0 + and contiguous_elements_per_tile % alignment == 0 + and elements_per_thread % alignment == 0 + ): + return alignment + + threads_per_block = ( + op.warp_m * op.warp_n * op.warp_k * self.gfx9_threads_per_warp + ) + a_elements_per_thread = op.tile_m * op.tile_k / threads_per_block + b_elements_per_thread = op.tile_n * op.tile_k / threads_per_block + + if op.layout_a == "Row": + # K is contiguous tensor dimension + a_max_vector_size = max_alignment( + op.tile_k, a_elements_per_thread, op.datatype_a + ) + if is_static_int(K) and K % a_max_vector_size != 0: + return False + elif op.layout_a == "Col": + # M is contiguous tensor dimension + a_max_vector_size = max_alignment( + op.tile_m, a_elements_per_thread, op.datatype_a + ) + if is_static_int(M) and M % a_max_vector_size != 0: + return False + else: + raise AssertionError(f"Invalid layout {op.layout_a=}") + + if op.layout_b == "Row": + # N is contiguous tensor dimension + b_max_vector_size = max_alignment( + op.tile_n, b_elements_per_thread, op.datatype_b + ) + if is_static_int(N) and N % b_max_vector_size != 0: + return False + elif op.layout_b == "Col": + # K is contiguous tensor dimension + b_max_vector_size = max_alignment( + op.tile_k, b_elements_per_thread, op.datatype_b + ) + if is_static_int(K) and K % b_max_vector_size != 0: + return False + else: + raise AssertionError(f"Invalid layout {op.layout_b=}") + + # the `default` epilogue writes C to memory by 1 tensor element + # (divisibility check not necessary) + # the `cshuffle` epilogue writes C to memory by 16 bytes + # (so the contiguous C dimension size must be divisible by the number of tensor elements in 16 bytes) + if op.epilogue == "CShuffle": + if ( + op.layout_c == "Row" + and is_static_int(N) + and N % (16 / self.ck_dtype_to_size[op.datatype_c]) != 0 + ): + return False + + return True + + def check_warp_tiles(self, op: "CKTileGemmOperation"): + if op.tile_m % (op.warp_m * op.warp_tile_m) != 0: + return False + if op.tile_n % (op.warp_n * op.warp_tile_n) != 0: + return False + if op.tile_k % (op.warp_k * op.warp_tile_k) != 0: + return False + return True + + def check_block_tile_size(self, op: "CKTileGemmOperation"): + # assuming LDS size is 64KB + if op.pipeline == "CompV4": + max_block_tile_size = 2**15 + else: + max_block_tile_size = 2**16 + + block_tile_size = ( + self.ck_dtype_to_size[op.datatype_a] * op.tile_m * op.tile_k + + self.ck_dtype_to_size[op.datatype_b] * op.tile_n * op.tile_k + ) + if block_tile_size > max_block_tile_size: + return False + return True + + def filter_op(self, op: "CKTileGemmOperation"): + """ + Determines whether a given op definition is suitable for the current + input / output of the operation that this template implements. + + Filter is based on inputs' dtype, layout and statically inferred size. + + Returns None if the op is not suitable, otherwise returns the op to be used. + """ + if not self.check_dtypes(op): + return None + if not self.check_layouts(op): + return None + if not self.check_block_tiles(op): + return None + if not self.check_alignments(op): + return None + + return op + + def emit_ck_instance(self, op: "CKTileGemmOperation"): + """ + This method is used to generate code which defines the type alias for the generated kernel class + """ + template_definition = r""" + // Gemm operator {{operation_name}} + + namespace {{operation_name}} { + // block tile + constexpr int32_t TileM = {{tile_m}}; + constexpr int32_t TileN = {{tile_n}}; + constexpr int32_t TileK = {{tile_k}}; + // warps per block + constexpr int32_t WarpM = {{warp_m}}; + constexpr int32_t WarpN = {{warp_n}}; + constexpr int32_t WarpK = {{warp_k}}; + // xdl tile + constexpr int32_t WarpTileM = {{warp_tile_m}}; + constexpr int32_t WarpTileN = {{warp_tile_n}}; + constexpr int32_t WarpTileK = {{warp_tile_k}}; + + constexpr bool kPadM = {{m_is_padded}}; + constexpr bool kPadN = {{n_is_padded}}; + constexpr bool kPadK = {{k_is_padded}}; + + using ALayout = {{layout_a}}; + using BLayout = {{layout_b}}; + using CLayout = {{layout_c}}; + + using ADataType = {{datatype_a}}; + using BDataType = {{datatype_b}}; + using CDataType = {{datatype_c}}; + using AccDataType = F32; + + constexpr bool permuteA = false; + constexpr bool permuteB = false; + constexpr bool DoubleSmemBuffer = {{has_double_smem_buffer}}; + constexpr bool TransposeC = false; + + constexpr int kBlockPerCu = 1; + constexpr ck_tile::index_t TilePartitionerGroupNum = 8; + constexpr ck_tile::index_t TilePartitionerM01 = 4; + + using GemmShape = + ck_tile::TileGemmShape, + ck_tile::sequence, + ck_tile::sequence, + permuteA, + permuteB>; + + using TilePartitioner = + ck_tile::GemmSpatiallyLocalTilePartitioner; + + using Traits = + ck_tile::TileGemmTraits; + + using GemmUniversalTraits = + ck_tile::TileGemmUniversalTraits; + + using GemmPipelineProblem = + ck_tile::GemmPipelineProblem; + + {{rendered_scheduler}} + + template + using UniversalGemmProblem = + ck_tile::UniversalGemmPipelineProblem; + + {{rendered_pipeline}} + + {{rendered_epilogue}} + + template + using Kernel = ck_tile::GemmKernel, GemmEpilogue>; + } + +""" + + def render_epilogue(epilogue_type): + if epilogue_type == "Default": + return r""" + using DsDataType = ck_tile::tuple<>; + using DsLayout = ck_tile::tuple<>; + using CDElementwise = ck_tile::element_wise::PassThrough; + + using EpilogueProblem = ck_tile::DefaultGemm2DEpilogueProblem; + using GemmEpilogue = ck_tile::DefaultGemm2DEpilogue; + """ + elif epilogue_type == "CShuffle": + return r""" + using DsDataType = ck_tile::tuple<>; // no bias terms for vanilla GEMM + using DsLayout = ck_tile::tuple<>; + constexpr auto ELayout = CLayout; + using CDEElementWise = ck_tile::element_wise::PassThrough; // no-op + using EpilogueProblem = ck_tile::CShuffleEpilogueProblem; + + using GemmEpilogue = ck_tile::CShuffleEpilogue; + """ + else: + raise AssertionError("Epilogue must be set") + + def render_pipeline(pipeline_type): + return rf""" + using BaseGemmPipeline = ck_tile::BaseGemmPipelineAgBgCr{pipeline_type}; + + template + using GemmPipeline = ck_tile::GemmPipelineAgBgCr{pipeline_type}>; + """ + + def render_scheduler(scheduler_type): + return rf""" + constexpr auto scheduler = ck_tile::GemmPipelineScheduler::{scheduler_type}; + """ + + rendered_definition = self._template_from_string(template_definition).render( + operation_name=op.name(), + **asdict(op), + rendered_scheduler=render_scheduler(op.scheduler), + rendered_pipeline=render_pipeline(op.pipeline), + rendered_epilogue=render_epilogue(op.epilogue), + has_double_smem_buffer=("true" if op.pipeline == "CompV4" else "false"), + ) + return rendered_definition + + def render( # type: ignore[override] + self, kernel: ROCmTemplateKernel, op: "CKTileGemmOperation", **kwargs + ) -> str: + """ + The primary entry point for the code rendering process used in this template. + """ + epilogue_nodes = kwargs.get("epilogue_nodes") + if not (epilogue_nodes is None or 0 == len(epilogue_nodes)): + raise AssertionError("expected no epilogue_nodes for CK tile gemm template") + template_buffer_node = kwargs.get("template_buffer_node") + if template_buffer_node is not None: + self.output_node = template_buffer_node + if 2 != len(self.input_nodes): + raise AssertionError(f"expected 2 input_nodes, got {len(self.input_nodes)}") + X, W = self.input_nodes + Y = self.output_node + + instance_definition = self.emit_ck_instance(op) + + version_comment = rf"""/** +* Generated code for CK inductor backend +* See {type(self).__module__}.{type(self).__qualname__} +* +* Template instance {op} +* +* {torch.__version__=} +* torch.version.git_version={getattr(torch.version, "git_version", "None")} +*/ +""" + + return self._template_from_string(self.gemm_template).render( + headers=self.header().getvalue(), + globals=self.globals().getvalue(), + instance_definition=instance_definition, + kernel_definition=kernel.def_kernel( + inputs=[X, W], # type: ignore[list-item] + outputs=[Y], + names_str="X, W, Y", + size_args=[ + f"int32_t {arg}" for arg in ["M", "N", "K", "LDA", "LDB", "LDC"] + ], + ), + instance_namespace=op.name(), + version_comment=version_comment, + ) + + def gen_ops(self): + """ + Creates a list of `CKTileGemmOperation` instances that match the GEMM operation this template represents. + The instances are guaranteed to have the correct layout, dtype and dimension padding for the GEMM input arguments. + + An instance may invalidate the GEMM configuration at runtime. + Such instances will be assigned +inf runtime by the autotune process. + """ + instances = ops() + if not instances: + raise AssertionError( + "No Composable Kernel Universal GEMM instances found. " + "Please check if the library is installed." + ) + filtered_instances = list(filter(self.filter_op, instances)) + # NB: when using a fixed list order, most likely we will pick the subset of instances + # which are very similar to each other. Stratified sampling ensures coverage of + # different pipeline/epilogue combinations while still randomizing within each stratum. + # Use a local Random instance so we don't mutate the global RNG state shared with + # other inductor code paths. + rng = random.Random(-11) + max_configs = config.rocm.ck_tile_max_profiling_configs + if max_configs: + strata: dict[tuple[str, str], list] = defaultdict(list) + for inst in filtered_instances: + strata[(inst.pipeline, inst.epilogue)].append(inst) + # Shuffle stratum keys so that when len(strata) > max_configs, the strata that + # get represented are not biased by filter/insertion order. + stratum_keys = list(strata.keys()) + rng.shuffle(stratum_keys) + # Distribute the budget across strata as evenly as possible. The first + # `remainder` strata get one extra slot. + per_stratum, remainder = divmod(max_configs, len(stratum_keys)) + chosen_instances: list = [] + for i, key in enumerate(stratum_keys): + quota = per_stratum + (1 if i < remainder else 0) + if quota == 0: + break + group = strata[key] + chosen_instances.extend(rng.sample(group, min(len(group), quota))) + # If some strata were smaller than their quota, fill the slack from the global + # remainder so we still hit max_configs when possible. + shortfall = max_configs - len(chosen_instances) + if shortfall > 0: + chosen_ids = OrderedSet(id(x) for x in chosen_instances) + remaining = [x for x in filtered_instances if id(x) not in chosen_ids] + if remaining: + chosen_instances.extend( + rng.sample(remaining, min(len(remaining), shortfall)) + ) + else: + chosen_instances = filtered_instances + log.debug( + "generated %d ck instances after sample: %s", + len(chosen_instances), + chosen_instances, + ) + return chosen_instances + + @staticmethod + def add_choices( + choices, + layout, + input_nodes, + ): + """ + Add Composable Kernel Universal GEMM instance choices to the auto-tuning list. + """ + template = CKTileGemmTemplate( + input_nodes, + layout, + ) + ops = template.gen_ops() + for op in ops: + for k_batch in template.k_batch_choices(op): + template.maybe_append_choice( + choices, + op=op, + kBatch=k_batch, + ) + + def k_batch_choices(self, op: "CKTileGemmOperation") -> tuple[int, ...]: + """ + Returns a list of k_batch choices for the template. + """ + default_choices = (1, 2, 4, 8, 16, 32) + + def check(dim_size, tile_size, is_padded): + if ( + is_static_int(dim_size) + and dim_size % tile_size != 0 + and is_padded == "false" + ): + return False + return True + + _, _, K, _, _, _ = self.size_args() + if op.layout_a == "Row" or op.layout_b == "Col": + choices = tuple( + filter( + lambda k_batch: check(K, op.tile_k * k_batch, op.k_is_padded), + default_choices, + ) + ) + else: + choices = default_choices + + if op.epilogue == "Default": + choices = (1,) + + return choices + + def size_args(self): + """ + Sizes and strides to be used for the kernel call + """ + X = self.input_nodes[0] + W = self.input_nodes[1] + Y = self.output_node + + M = X.get_size()[0] + K = X.get_size()[1] + N = W.get_size()[1] + LDA = X.get_stride()[0 if X.get_stride()[1] == 1 else 1] + LDB = W.get_stride()[0 if W.get_stride()[1] == 1 else 1] + LDC = Y.get_stride()[0 if Y.get_stride()[1] == 1 else 1] + + return M, N, K, LDA, LDB, LDC + + def get_runtime_arg_info(self) -> list[ArgInfo]: + return [ArgInfo("kBatch", "int32_t")] + + def get_runtime_arg_values(self, **kwargs: Any) -> list[Any]: + # maybe_append_choice kwarg for k_batch must match the name of the argument + arg_names = OrderedSet([arg.name for arg in self.get_runtime_arg_info()]) + if not arg_names.issubset(kwargs): + raise ValueError( + "Missing runtime arguments: " + ", ".join(arg_names - kwargs.keys()) + ) + return [kwargs[k] for k in arg_names] diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_universal_gemm_template.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_universal_gemm_template.py new file mode 100644 index 0000000000000000000000000000000000000000..f383c8252290c93f387d0b16087f32af0af8d666 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/ck_universal_gemm_template.py @@ -0,0 +1,1023 @@ +# mypy: allow-untyped-defs, disable-error-code="attr-defined, valid-type" +import copy +import logging +import math +import random +from collections import namedtuple + +import sympy + +import torch +from torch._inductor import config +from torch._inductor.codegen.cpp_utils import DTYPE_TO_CPP +from torch._inductor.codegen.rocm.ck_template import CKTemplate +from torch._inductor.codegen.rocm.compile_command import rocm_compile_command +from torch._inductor.codegen.rocm.rocm_kernel import ROCmTemplateKernel +from torch._inductor.ir import Buffer, Layout +from torch._inductor.runtime.runtime_utils import next_power_of_2 + +from ...utils import IndentedBuffer, is_dynamic, try_import_ck_lib + + +_, gen_ops_library, gen_ops_preselected, CKGemmOperation = try_import_ck_lib() + + +log = logging.getLogger(__name__) + +# lightweight collection of information about a single op +InductorROCmOp = namedtuple("InductorROCmOp", ["op", "kBatch"]) + +padding_lookup = { + "M": { + "GemmSpecialization::MPadding": True, + "GemmSpecialization::MNPadding": True, + "GemmSpecialization::MKPadding": True, + "GemmSpecialization::MNKPadding": True, + }, + "N": { + "GemmSpecialization::NPadding": True, + "GemmSpecialization::MNPadding": True, + "GemmSpecialization::NKPadding": True, + "GemmSpecialization::MNKPadding": True, + }, + "K": { + "GemmSpecialization::KPadding": True, + "GemmSpecialization::MKPadding": True, + "GemmSpecialization::NKPadding": True, + "GemmSpecialization::MNKPadding": True, + }, +} + + +def is_static_int(number): + return isinstance(number, (int, sympy.Integer)) + + +def torch_layout_to_ck_layout(torch_layout): + if torch_layout.stride[-1] == 1: + return "Row" + elif torch_layout.stride[-2] == 1: + return "Col" + else: + return None + + +class CKGemmTemplate(CKTemplate): + # the JINJA template for rendering CK Universal GEMMs + gemm_template = r"""{{version_comment}} + {{headers}} + {{globals}} + {{instance_definition}} + extern "C" { + PT_EXPORT {{kernel_definition}} { + auto gemm = {{instance_type}} {}; + auto invoker = gemm.MakeInvoker(); + {% if is_batched %} + auto argument = gemm.MakeArgument( + reinterpret_cast(X), + reinterpret_cast(W), + std::array{ {{ds_names}} }, + reinterpret_cast<{{c_element_dtype}}*>(Y), + M, + N, + K, + B, + LDA, + LDB, + std::array{ {{ds_strides}} }, + LDC, + M * K, // batch_stride_A + N * K, // batch_stride_B + std::array{ {{ds_batch_strides}} }, + M * N, // batch_stride_C + {{a_elementwise_op}}, + {{b_elementwise_op}}, + {{epilogue}} // c_elementwise_op + ); + {% else %} + auto argument = gemm.MakeArgument( + reinterpret_cast(X), + reinterpret_cast(W), + std::array{ {{ds_names}} }, + reinterpret_cast<{{c_element_dtype}}*>(Y), + M, + N, + K, + LDA, + LDB, + std::array{ {{ds_strides}} }, + LDC, + kBatch, // kBatch + {{a_elementwise_op}}, + {{b_elementwise_op}}, + {{epilogue}} // c_elementwise_op + ); + {% endif %} + if (!gemm.IsSupportedArgument(argument)) { + // we do our best to statically avoid this case in `filter_op` + std::cerr << "invalid argument for gemm instance " << gemm.GetTypeString() << std::endl; + argument.Print(); + return -23; + } + if (workspace_size) { + *workspace_size = gemm.GetWorkSpaceSize(&argument); + return 0; + } + // run the kernel + #ifdef GENERATE_CK_STANDALONE_RUNNER + const auto stream_config = StreamConfig{ + stream, + /* time kernel */ 1, + /* log level */ 1, + /* n_cold_iter */ 100, + /* n_hot_iter */ 100, + /* flush_l2_cache */ 1, + /* rotate_count */ 5}; + #else + const auto stream_config = StreamConfig{stream, /* time kernel */ false, /* log level */ 0}; + #endif + + const float elapsed_time = invoker.Run(argument, stream_config); + + #ifdef GENERATE_CK_STANDALONE_RUNNER + std::cout << "elapsed time: " << elapsed_time << " ms" << std::endl; + #else + (void)elapsed_time; + #endif + return 0; + } // kernel definition + } // extern C + """ + + standalone_runner_template = r""" + #ifdef GENERATE_CK_STANDALONE_RUNNER + // standalone runner for the generated CK GEMM kernel + + {{inline_utils}} + + extern "C" { + int run_main(int argc, char** argv) { + {% if is_batched %} + const int32_t B = {{B}}; + {% endif %} + const int32_t M = {{M}}; + const int32_t N = {{N}}; + const int32_t K = {{K}}; + const int32_t LDA = {{LDA}}; + const int32_t LDB = {{LDB}}; + const int32_t LDC = {{LDC}}; + const int32_t LDD = {{LDD}}; + const int32_t kBatch = {{kBatch}}; + + using AElementType = {{a_ck_dtype}}; + using BElementType = {{b_ck_dtype}}; + using CElementType = {{c_ck_dtype}}; + {% if has_bias %} + using BiasElementType = {{bias_ck_dtype}}; + {% endif %} + {% if has_scale %} + using ScaleAElementType = {{scale_a_ck_dtype}}; + using ScaleBElementType = {{scale_b_ck_dtype}}; + {% endif %} + + using AArgType = {{a_torch_dtype}}; + using BArgType = {{b_torch_dtype}}; + using CArgType = {{c_torch_dtype}}; + {% if has_bias %} + using BiasArgType = {{bias_torch_dtype}}; + {% endif %} + {% if has_scale %} + using ScaleAArgType = {{scale_a_torch_dtype}}; + using ScaleBArgType = {{scale_b_torch_dtype}}; + {% endif %} + + using ALayout = {{a_layout}}; + using BLayout = {{b_layout}}; + using CLayout = {{c_layout}}; + {% if has_bias %} + using BiasLayout = {{bias_layout}}; + {% endif %} + + {% if is_batched %} + using strides_t = std::array; + auto get_strides = [](int32_t batch_stride, int32_t leading_dimension, auto layout) constexpr -> strides_t { + if constexpr (std::is_same_v) { + return {batch_stride, leading_dimension, 1}; + } + return {batch_stride, 1, leading_dimension}; + }; + auto a_size = strides_t{B, M, K}; + auto a_stride = get_strides(M * K, LDA, ALayout{}); + auto b_size = strides_t{B, N, K}; + auto b_stride = get_strides(N * K, LDB, BLayout{}); + auto c_size = strides_t{B, M, N}; + auto c_stride = get_strides(M * N, LDC, CLayout{}); + {% else %} + using strides_t = std::array; + auto get_strides = [](int32_t leading_dimension, auto layout) constexpr -> strides_t { + if constexpr (std::is_same_v) { + return {leading_dimension, 1}; + } + return {1, leading_dimension}; + }; + auto a_size = strides_t{M, K}; + auto a_stride = get_strides(LDA, ALayout{}); + auto b_size = strides_t{N, K}; + auto b_stride = get_strides(LDB, BLayout{}); + auto c_size = strides_t{M, N}; + auto c_stride = get_strides(LDC, CLayout{}); + {% endif %} + + Tensor a_m_k ( HostTensorDescriptor ( a_size, a_stride ) ); + Tensor b_k_n ( HostTensorDescriptor ( b_size, b_stride ) ); + {% if has_bias %} + Tensor d_m_n ( HostTensorDescriptor ( c_size, get_strides(LDD, BiasLayout{}) ) ); + {% endif %} + {% if has_scale %} + // NB: these are hardcoded + Tensor s_a_m_n ( HostTensorDescriptor ( strides_t{M, N}, get_strides(0, Row{}) )); + Tensor s_b_m_n ( HostTensorDescriptor ( strides_t{M, N}, get_strides(0, Col{}) )); + {% endif %} + + Tensor c_m_n_host ( HostTensorDescriptor ( c_size, c_stride ) ); + Tensor c_m_n_device ( HostTensorDescriptor ( c_size, c_stride ) ); + + a_m_k.GenerateTensorValue(GeneratorTensor_2()); + b_k_n.GenerateTensorValue(GeneratorTensor_2()); + {% if has_bias %} + d_m_n.GenerateTensorValue(GeneratorTensor_2()); + {% endif %} + {% if has_scale %} + s_a_m_n.GenerateTensorValue(GeneratorTensor_2()); + s_b_m_n.GenerateTensorValue(GeneratorTensor_2()); + {% endif %} + DeviceMem a_m_k_device_buf(sizeof(AElementType) * a_m_k.mDesc.GetElementSpaceSize()); + DeviceMem b_k_n_device_buf(sizeof(BElementType) * b_k_n.mDesc.GetElementSpaceSize()); + {% if has_bias %} + DeviceMem d_m_n_device_buf(sizeof(BiasElementType) * d_m_n.mDesc.GetElementSpaceSize()); + {% endif %} + {% if has_scale %} + DeviceMem s_a_m_n_device_buf(sizeof(ScaleAElementType) * s_a_m_n.mDesc.GetElementSpaceSize()); + DeviceMem s_b_m_n_device_buf(sizeof(ScaleBElementType) * s_b_m_n.mDesc.GetElementSpaceSize()); + {% endif %} + DeviceMem c_m_n_device_buf(sizeof(CElementType) * c_m_n_device.mDesc.GetElementSpaceSize()); + + a_m_k_device_buf.ToDevice(a_m_k.mData.data()); + b_k_n_device_buf.ToDevice(b_k_n.mData.data()); + {% if has_bias %} + d_m_n_device_buf.ToDevice(d_m_n.mData.data()); + {% endif %} + {% if has_scale %} + s_a_m_n_device_buf.ToDevice(s_a_m_n.mData.data()); + s_b_m_n_device_buf.ToDevice(s_b_m_n.mData.data()); + {% endif %} + + {{kernel_name}}( + static_cast(a_m_k_device_buf.GetDeviceBuffer()), + static_cast(b_k_n_device_buf.GetDeviceBuffer()), + {% if has_scale %} + static_cast(s_a_m_n_device_buf.GetDeviceBuffer()), + static_cast(s_b_m_n_device_buf.GetDeviceBuffer()), + {% endif %} + {% if has_bias %} + static_cast(d_m_n_device_buf.GetDeviceBuffer()), + {% endif %} + static_cast(c_m_n_device_buf.GetDeviceBuffer()), + {% if is_batched %} + B, + {% endif %} + M, + N, + K, + LDA, + LDB, + LDC, + LDD, + nullptr, // workspace_size + nullptr, // workspace + nullptr); // stream + + hip_check_error(hipDeviceSynchronize()); + + return 0; + } // run_main + } // extern C + + int main(int argc, char** argv) { + return run_main(argc, argv); + } + // compile with: {{compile_cmd}} + #endif // GENERATE_CK_STANDALONE_RUNNER + """ + + def __init__( + self, + input_nodes: list[Buffer], + layout: Layout, + alpha: float, + beta: float, + input_reorder: list[int] | None = None, + ) -> None: + is_batched = len(layout.size) == 3 + name = "ck_batched_gemm_template" if is_batched else "ck_gemm_template" + super().__init__( + name=name, + input_nodes=input_nodes, + layout=layout, + input_reorder=input_reorder, + ) + self.alpha = alpha + self.beta = beta + self.is_batched = is_batched + + def header(self) -> IndentedBuffer: + res = super().header() + if self.is_batched: + res.splice( + """ + // CK GEMM header(s) + + #include "ck/tensor_operation/gpu/device/impl/device_batched_gemm_multiple_d_xdl_cshuffle_v3.hpp" + """ + ) + else: + res.splice( + """ + // CK GEMM header(s) + + #include "ck/tensor_operation/gpu/device/impl/device_gemm_multiple_d_xdl_cshuffle_v3.hpp" + """ + ) + return res + + def globals(self) -> IndentedBuffer: + res = super().globals() + res.splice( + """ + // CK GEMM globals + + using Row = ck::tensor_layout::gemm::RowMajor; + using Col = ck::tensor_layout::gemm::ColumnMajor; + + using BlockGemmPipelineScheduler = ck::BlockGemmPipelineScheduler; + using GemmSpecialization = ck::tensor_operation::device::GemmSpecialization; + using BlockGemmPipelineVersion = ck::BlockGemmPipelineVersion; + + struct MultiplyMultiplyAdd { + template + __host__ __device__ constexpr void + operator()(E& e, const C& c, const D0& d0, const D1& d1, const D2& d2) const { + e = ck::type_convert( + ck::type_convert(c) + * ck::type_convert(d0) + * ck::type_convert(d1) + + ck::type_convert(d2) + ); + } + }; + """ + ) + return res + + def inline_utils(self): + res = IndentedBuffer() + res.splice( + """ + #include "host_tensor.cpp" + #include "device_memory.cpp" + """ + ) + return res + + def _has_padding(self, dimension, gemm_specialization): + # Get the relevant padding map for the given dimension + dimension_padding = padding_lookup.get(dimension, {}) + + # Check if the specialization is in the dimension's padding map + return dimension_padding.get(gemm_specialization, False) + + def filter_op(self, op_info: InductorROCmOp): + """ + Determines whether a given op definition is suitable for the current + input / output of the operation that this template implements. + + Filter is based on inputs' dtype, layout and statically inferred size. + + Returns None if the op is not suitable, otherwise returns the op to be used. + """ + op, kBatch = op_info.op, op_info.kBatch + metas = [T.get_layout() for T in [*self.input_nodes, self.output_node]] + X_meta = metas[0] + W_meta = metas[1] + Y_meta = metas[-1] + # disable the instance if dtypes don't match + if op.a_element_dtype != self._TORCH_DTYPE_TO_CK[X_meta.dtype]: + return None + if op.b_element_dtype != self._TORCH_DTYPE_TO_CK[W_meta.dtype]: + return None + if op.c_element_dtype != self._TORCH_DTYPE_TO_CK[Y_meta.dtype]: + return None + if self.is_blocked_by_tf32_setting(op): + return None + # disable the instance if layouts don't match + if op.a_layout != torch_layout_to_ck_layout(X_meta): + return None + if op.b_layout != torch_layout_to_ck_layout(W_meta): + return None + if op.c_layout != torch_layout_to_ck_layout(Y_meta): + return None + # try to avoid launching the instance with invalid problem size + # see GridwiseGemm_xdl_cshuffle_v3::CheckValidity + + M = X_meta.size[-2] + K = X_meta.size[-1] + N = W_meta.size[-1] + + if is_static_int(M): + if not self._has_padding("M", op.gemm_specialization): + if M % op.m_per_block != 0: + return None + if is_static_int(N): + if not self._has_padding("N", op.gemm_specialization): + if N % op.n_per_block != 0: + return None + if is_static_int(K): + if not self._has_padding("K", op.gemm_specialization): + if K % op.k_per_block != 0: + return None + K_t = kBatch * op.k_per_block + if K % K_t != 0: + return None + else: + # need another kBatch check here + lcm = abs(op.a_k1 * op.b_k1) // math.gcd(op.a_k1, op.b_k1) + K_t = kBatch * lcm + k_read_pad_splited = math.ceil(K / K_t) * lcm + if (k_read_pad_splited * (kBatch - 1)) >= K: + return None + + a_contig_size = ( + K if op.a_layout == "Row" else M if op.a_layout == "Col" else None + ) + if ( + is_static_int(a_contig_size) + and a_contig_size % op.a_block_transfer_src_scalar_per_vector != 0 + ): + return None + b_contig_size = ( + N if op.b_layout == "Row" else K if op.b_layout == "Col" else None + ) + if ( + is_static_int(b_contig_size) + and b_contig_size % op.b_block_transfer_src_scalar_per_vector != 0 + ): + return None + c_contig_size = ( + N if op.c_layout == "Row" else M if op.c_layout == "Col" else None + ) + c_shuffle_block_transfer_scalar_per_vector_n_per_block = ( + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block[0] + if isinstance( + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block, tuple + ) + else op.c_shuffle_block_transfer_scalar_per_vector_n_per_block + ) + if ( + is_static_int(c_contig_size) + and c_contig_size % c_shuffle_block_transfer_scalar_per_vector_n_per_block + != 0 + ): + return None + if not self._check_num_k_loops(op, kBatch): + return None + # TBD disable instances with invalid number of pipeline prefetch stages + # It will avoid compiling a small percentage of unrunnable instances which fail the gemm argument check + + return op + + def _check_num_k_loops(self, op, kBatch): + # Additional splitK scenario check + metas = [T.get_layout() for T in [*self.input_nodes]] + X_meta = metas[0] + W_meta = metas[1] + K = X_meta.size[-1] + if kBatch > 1: + if op.block_gemm_pipeline_version != "BlockGemmPipelineVersion::v1": + try: + prefetch_stages = self._prefetch_stages( + op, + torch.empty((), dtype=X_meta.dtype).element_size(), + torch.empty((), dtype=W_meta.dtype).element_size(), + torch.cuda.get_device_properties(X_meta.device).warp_size, + ) + except Exception as e: + log.debug( + "Failed to prefetch_stages for %s with exception %s", op.name, e + ) + # be conservative here and disable the op + return False + + K_t = op.k_per_block * kBatch + ak0 = (K + K_t - 1) // K_t * (op.k_per_block // op.a_k1) + num_k_loop = ak0 // (op.k_per_block // op.a_k1) + if num_k_loop <= prefetch_stages: + log.debug( + "Op %s is not compatible due to invalid number of pipeline prefetch stages. " + "Parameters: kBatch=%s, block_gemm_pipeline_version=%s, prefetch_stages=%s, num_k_loop=%s", + op.name(), + kBatch, + op.block_gemm_pipeline_version, + prefetch_stages, + num_k_loop, + ) + return False + + return True + + # small helper to figure out the prefetch stages on AMD + def _prefetch_stages(self, op, a_dtype_size, b_dtype_size, warp_size: int = 64): + version_str = op.block_gemm_pipeline_version.split("::")[-1] + try: + version = int(version_str[1:]) # Assuming the format is always 'vX' + except ValueError as e: + raise ValueError(f"Invalid version string: {version_str}") from e + if version not in [1, 2, 3, 4, 5]: + raise ValueError( + f"unknown prefetch stages for {op.block_gemm_pipeline_version}" + ) + # Define the mapping of versions to stages + version_to_stages = {1: 1, 3: 2, 4: 4, 5: 3} + # Get the stages for the given version + stages = version_to_stages.get(version) + if stages is None: + # This means we're at stage 2, and this requires computation + # See github.com/ROCm/composable_kernel/blob/d6a4605/include/ck/tensor_operation/gpu/block/blockwise_gemm_pipeline_xdlops_v2.hpp#L143 + wgp_per_cu = max(4 * warp_size // op.block_size, 1) + full_mem_band_prefetch_stages = math.ceil( + 32768 + / wgp_per_cu + / ( + (op.m_per_block * a_dtype_size + op.n_per_block * b_dtype_size) + * op.k_per_block + ) + ) + stages = min(max(full_mem_band_prefetch_stages, 2), 8) + + return stages + + def emit_ck_instance(self, op: "CKGemmOperation"): + # The Jinja template for generating a C++ type alias *definition* for a Universal GEMM instance + struct_name = ( + "DeviceBatchedGemmMultiD_Xdl_CShuffle_V3" + if self.is_batched + else "DeviceGemmMultiD_Xdl_CShuffle_V3" + ) + template_definition = r""" + // Gemm operator {{operation_name}} + using Operation_{{operation_name}} = + ck::tensor_operation::device::{{struct_name}}< + {{template_params}}>; + +""" + # The Jinja template for generating a C++ type alias *usage* for a Universal GEMM instance + template_type = r""" + Operation_{{operation_name}} +""" + template_params = [] + for field_name, field_value in op.dict_items(): + if isinstance(field_value, tuple): + tuple_elements = ", ".join(map(str, iter(field_value))) + if "ds" in field_name: # element type and layout for bias + arg = f"/* {field_name} */ Tuple<{tuple_elements}>" + else: # tile shape + arg = f"/* {field_name} */ S<{tuple_elements}>" + # pyrefly: ignore [bad-argument-type] + template_params.append(arg) + else: + if field_value is not None: + # pyrefly: ignore [bad-argument-type] + template_params.append(f"/* {field_name} */ {field_value}") + operation_name = op.name().replace("(", "").replace(",", "").replace(")", "") + return self._template_from_string(template_definition).render( + operation_name=operation_name, + template_params=(",\n" + 12 * " ").join(template_params), + struct_name=struct_name, + ), self._template_from_string(template_type).render( + operation_name=operation_name + ) + + def render( # type: ignore[override] + self, + kernel: ROCmTemplateKernel, + op: "CKGemmOperation", + **kwargs, + ) -> str: + """ + The primary entry point for the code rendering process used in this template. + """ + epilogue_nodes = kwargs.get("epilogue_nodes") + if not (epilogue_nodes is None or 0 == len(epilogue_nodes)): + raise AssertionError("expected no epilogue nodes for CK GEMM template") + template_buffer_node = kwargs.get("template_buffer_node") + if template_buffer_node is not None: + self.output_node = template_buffer_node + # input nodes: + # * X, W for matmul + # * X, W, Bias for addmm + # * X, W, inv_scale_x, inv_scale_w for scaled_mm + # * X, W, inv_scale_x, inv_scale_w, Bias for scaled_mm with bias + X, W = self.input_nodes[0], self.input_nodes[1] + Y = self.output_node + Bias = ( + self.input_nodes[2] + if 3 == len(self.input_nodes) + else self.input_nodes[4] + if 5 == len(self.input_nodes) + else None + ) + has_bias = Bias is not None + has_scale = len(self.input_nodes) in (4, 5) + op = copy.deepcopy(op) + + # This parameter is converted into tuple because of change + # from DeviceGemm_Xdl_CShuffleV3 to DeviceGemmMultiD_Xdl_CShuffle_V3. + # The first tuple element corresponds to matmul result... + if not isinstance( + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block, tuple + ): + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block = ( + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block, + ) + + if has_scale: + scale_x = self.input_nodes[2] + scale_w = self.input_nodes[3] + if 1 == scale_x.get_numel() and 1 == scale_w.get_numel(): + # tensorwise scale for both X, W + if has_bias: + op.c_elementwise_op = "ScaleAdd" + else: + op.c_elementwise_op = "Scale" + else: + # rowwise scale for both X, W + if has_bias: + op.c_elementwise_op = "MultiplyMultiplyAdd" + else: + op.c_elementwise_op = "MultiplyMultiply" + op.c_shuffle_dtype = "F32" + op.ds_layouts = ( + torch_layout_to_ck_layout(scale_x.get_layout()), + torch_layout_to_ck_layout(scale_w.get_layout()), + ) + op.ds_element_dtypes = ( + self._TORCH_DTYPE_TO_CK[scale_x.get_layout().dtype], + self._TORCH_DTYPE_TO_CK[scale_w.get_layout().dtype], + ) + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block += (1, 1) + else: + scale_x = None + scale_w = None + + bias_dtype = "" + if Bias is not None: + bias_layout = torch_layout_to_ck_layout(Bias.get_layout()) + bias_dtype = self._TORCH_DTYPE_TO_CK[Bias.get_layout().dtype] + op.ds_layouts += (bias_layout,) + op.ds_element_dtypes += (bias_dtype,) + if not has_scale: + op.c_elementwise_op = "Bilinear" + # c_shuffle_dtype is also used for adding bias to matmul result + # before converting down to the result dtype + op.c_shuffle_dtype = op.acc_dtype + # this parameter needs to be set accordingly to bias stride for correct accumulation + if bias_layout == "Row": + # bias has (N, ) shape + bias_shuffle_block_transfer_scalar_per_vector_n_per_block = ( + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block + ) + elif bias_layout == "Col": + # bias has (M, 1) shape + bias_shuffle_block_transfer_scalar_per_vector_n_per_block = (1,) + else: + raise AssertionError( + "Bias layout is neither row-major nor column-major" + ) + # ...and the second tuple element corresponds to the bias + op.c_shuffle_block_transfer_scalar_per_vector_n_per_block += ( + bias_shuffle_block_transfer_scalar_per_vector_n_per_block + ) + + instance_definition, instance_type = self.emit_ck_instance(op) + + version_comment = rf"""/** +* Generated code for CK inductor backend +* See {type(self).__module__}.{type(self).__qualname__} +* +* Template instance {op} +* +* {torch.__version__=} +* torch.version.git_version={getattr(torch.version, "git_version", "None")} +*/ +""" + epilogue = None + + if op.c_elementwise_op == "Bilinear" and scale_w is None: + epilogue = f"Bilinear {{ {self.alpha}, {self.beta} }}" + + elif op.c_elementwise_op == "Scale": + epilogue = "Scale { (inv_scale_w && inv_scale_x) ? (*inv_scale_w * *inv_scale_x) : 1.0f }" + + elif op.c_elementwise_op == "ScaleAdd": + epilogue = "ScaleAdd { (inv_scale_w && inv_scale_x) ? (*inv_scale_w * *inv_scale_x) : 1.0f }" + + elif op.c_elementwise_op == "MultiplyMultiply": + epilogue = "MultiplyMultiply {}" + + elif op.c_elementwise_op == "MultiplyMultiplyAdd": + epilogue = "MultiplyMultiplyAdd {}" + + elif op.c_elementwise_op == "PassThrough": + epilogue = "PassThrough {}" + + if epilogue is None: + raise AssertionError("CK GEMM epilogue is not set") + + size_arg_strs = ["M", "N", "K", "LDA", "LDB", "LDC", "LDD"] + if self.is_batched: + size_arg_strs.insert(0, "B") + + res = self._template_from_string(self.gemm_template).render( + inline_utils=self.inline_utils(), + headers=self.header().getvalue(), + globals=self.globals().getvalue(), + instance_definition=instance_definition, + kernel_definition=kernel.def_kernel( + inputs=[X, W, scale_x, scale_w, Bias], # type: ignore[list-item] + outputs=[Y], + names_str="X, W, inv_scale_x, inv_scale_w, Bias, Y", + input_reorder=self.input_reorder, + size_args=[f"int32_t {arg}" for arg in size_arg_strs], + ), + instance_type=instance_type, + a_element_dtype=op.a_element_dtype, + b_element_dtype=op.b_element_dtype, + c_element_dtype=op.c_element_dtype, + bias_element_dtype=bias_dtype, + alpha=self.alpha, + beta=self.beta, + a_elementwise_op="PassThrough {}", + b_elementwise_op="PassThrough {}", + epilogue=epilogue, + has_bias=has_bias, + ds_size=1 + if op.c_elementwise_op in ("Bilinear", "ScaleAdd") + else 2 + if op.c_elementwise_op == "MultiplyMultiply" + else 3 + if op.c_elementwise_op == "MultiplyMultiplyAdd" + else 0, + ds_names=", ".join( + ["Bias"] + if op.c_elementwise_op in ("Bilinear", "ScaleAdd") + else ["inv_scale_x", "inv_scale_w"] + if op.c_elementwise_op == "MultiplyMultiply" + else ["inv_scale_x", "inv_scale_w", "Bias"] + if op.c_elementwise_op == "MultiplyMultiplyAdd" + else [] + ), + ds_strides=", ".join( + ["LDD"] + if op.c_elementwise_op in ("Bilinear", "ScaleAdd") + else ["0", "0"] + if op.c_elementwise_op == "MultiplyMultiply" + else ["0", "0", "LDD"] + if op.c_elementwise_op == "MultiplyMultiplyAdd" + else [] + ), + version_comment=version_comment, + is_batched=self.is_batched, + ds_batch_strides=", ".join([]), # FIXME when supporting baddbmm + ) + + if config.rocm.generate_test_runner: + is_static_problem = all(is_static_int(arg) for arg in self.size_args()) + # NOTE: size_arg_strs is defined above + size_arg_vals = ( + self.size_args() + if is_static_problem + else ( + f"std::stoi(argv[{k}])" for k, _ in enumerate(self.size_args(), 1) + ) + ) + size_args = dict(zip(size_arg_strs, size_arg_vals, strict=True)) + runtime_args = dict( + zip( + [a.name for a in self.get_runtime_arg_info()], + self.get_runtime_arg_values(), + ) + ) + runner_code = self._template_from_string( + self.standalone_runner_template + ).render( + inline_utils=self.inline_utils().getvalue(), + kernel_name=kernel.kernel_name, + has_bias=has_bias, + has_scale=has_scale, + is_batched=self.is_batched, + a_ck_dtype=op.a_element_dtype, + b_ck_dtype=op.b_element_dtype, + c_ck_dtype=op.c_element_dtype, + bias_ck_dtype=op.ds_element_dtypes[0] if has_bias else "", + scale_a_ck_dtype=op.ds_element_dtypes[0] + if has_scale and 2 == len(op.ds_element_dtypes) + else "BF16", + scale_b_ck_dtype=op.ds_element_dtypes[1] + if has_scale and 2 == len(op.ds_element_dtypes) + else "BF16", + a_torch_dtype=DTYPE_TO_CPP[X.get_layout().dtype], + b_torch_dtype=DTYPE_TO_CPP[W.get_layout().dtype], + c_torch_dtype=DTYPE_TO_CPP[Y.get_layout().dtype], + bias_torch_dtype=DTYPE_TO_CPP[Bias.get_layout().dtype] + if Bias is not None + else "", + scale_a_torch_dtype=DTYPE_TO_CPP[scale_x.get_layout().dtype] + if scale_x is not None + else "", + scale_b_torch_dtype=DTYPE_TO_CPP[scale_w.get_layout().dtype] + if scale_w is not None + else "", + a_layout=torch_layout_to_ck_layout(X.get_layout()), + b_layout=torch_layout_to_ck_layout(W.get_layout()), + c_layout=torch_layout_to_ck_layout(Y.get_layout()), + bias_layout=torch_layout_to_ck_layout(Bias.get_layout()) + if Bias is not None + else "", + compile_cmd=rocm_compile_command( + [""], "", "exe" + ), + **size_args, + **runtime_args, + ) + res += runner_code + + return res + + def _is_rcr_f16(self): + X_meta, W_meta, Y_meta = ( + T.get_layout() for T in [*self.input_nodes, self.output_node] + ) + X_dtype, W_dtype, Y_dtype = ( + self._TORCH_DTYPE_TO_CK[m.dtype] for m in (X_meta, W_meta, Y_meta) + ) + X_layout, W_layout, Y_layout = ( + torch_layout_to_ck_layout(m) for m in (X_meta, W_meta, Y_meta) + ) + + return ( + X_dtype == "F16" + and W_dtype == "F16" + and Y_dtype == "F16" + and X_layout == "Row" + and W_layout == "Col" + and Y_layout == "Row" + ) + + # helper to calculate a potentially optimal kBatch(es) for a problem + def _get_kBatch(self, op): + # we only set a higher kBatch if K > 16 * the larger of M and N + # this is a hand-tuned heuristic to start + metas = [T.get_layout() for T in [*self.input_nodes]] + X_meta = metas[0] + W_meta = metas[1] + M = X_meta.size[-2] + K = X_meta.size[-1] + N = W_meta.size[-1] + if is_dynamic(*self.input_nodes): + return [1] + if K // max(M, N) < config.rocm.split_k_threshold: + return [1] + # if the user is telling us which kBatches to sweep, just use those + if config.rocm.kBatch_sweep is not None: + return config.rocm.kBatch_sweep + # Calculate the number of blocks needed for each dimension + total_k_blocks = math.ceil(K / op.k_per_block) + # we want to calculate how many blocks we need to fit per CU + cus = torch.cuda.get_device_properties(X_meta.device).multi_processor_count + # again, manual heuristics as much larger kBatch are significantly worse in + # initial testing + kBatch = min(max(next_power_of_2(total_k_blocks // cus), 1), 128) + return [kBatch] + + def gen_ops(self) -> list[InductorROCmOp]: + """ + Creates a list of `CKGemmOperation` instances that match the GEMM operation this template represents. + The instances are guaranteed to have the correct layout, dtype and dimension padding for the GEMM input arguments. + + An instance may invalidate the GEMM configuration at runtime. + Such instances will be assigned +inf runtime by the autotune process. + """ + try: + from ck4inductor.batched_universal_gemm.gen_instances import ( # type: ignore[import] + gen_ops_library as gen_batched_gemm_ops_library, + ) + from ck4inductor.universal_gemm.gen_instances import ( # type: ignore[import] + gen_ops_library as gen_gemm_ops_library, + gen_ops_preselected as gen_gemm_ops_preselected, + ) + except ImportError: + return [] + + generator = None + if self.is_batched: + generator = gen_batched_gemm_ops_library + else: + generator = gen_gemm_ops_library + if config.rocm.use_preselected_instances and self._is_rcr_f16(): + generator = gen_gemm_ops_preselected + + if generator is None: + raise AssertionError("expected a non-None CK GEMM ops generator") + + rops = generator() + ops = [] + for o in rops: + kBatches = self._get_kBatch(o) + for kBatch in kBatches: + # pyrefly: ignore [bad-argument-type] + ops.append(InductorROCmOp(op=o, kBatch=kBatch)) + + filtered_instances = list(filter(lambda op: self.filter_op(op), ops)) + + # NB: when using a fixed list order, most likely we will pick the subset of instances + # which are very similar to each other. Randomizing the choice seems to solve this. + random.seed(-11) + chosen_instances = ( + random.sample( + filtered_instances, + min(len(filtered_instances), config.rocm.ck_max_profiling_configs), + ) + if config.rocm.ck_max_profiling_configs + else filtered_instances + ) + log.debug( + "generated %d ck instances after filter: %s", + len(chosen_instances), + chosen_instances, + ) + return chosen_instances + + @staticmethod + def add_ck_gemm_choices( + choices, + layout, + input_nodes, + alpha=1, + beta=0, + input_reorder=None, + ): + """ + Add Composable Kernel Universal GEMM instance choices to the auto-tuning list. + """ + template = CKGemmTemplate( + input_nodes, + layout, + alpha=alpha, + beta=beta, + input_reorder=input_reorder, + ) + ops = template.gen_ops() + for op in ops: + template.maybe_append_choice( + choices, + op=op.op, + kBatch=op.kBatch, + ) + + def size_args(self): + X = self.input_nodes[0] + W = self.input_nodes[1] + Bias = ( + self.input_nodes[2] + if len(self.input_nodes) == 3 + else self.input_nodes[4] + if len(self.input_nodes) == 5 + else None + ) + Y = self.output_node + + M = X.get_size()[-2] + K = X.get_size()[-1] + N = W.get_size()[-1] + LDA = X.get_stride()[-2 if X.get_stride()[-1] == 1 else -1] + LDB = W.get_stride()[-2 if W.get_stride()[-1] == 1 else -1] + LDC = Y.get_stride()[-2 if Y.get_stride()[-1] == 1 else -1] + LDD = ( + 0 + if (Bias is None or len(Bias.get_size()) == 1) + else Bias.get_stride()[-2 if Bias.get_stride()[-1] == 1 else -1] + ) + if self.is_batched: + B = X.get_size()[0] + return B, M, N, K, LDA, LDB, LDC, LDD + else: + return M, N, K, LDA, LDB, LDC, LDD diff --git a/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/compile_command.py b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/compile_command.py new file mode 100644 index 0000000000000000000000000000000000000000..2aa4494e0aa32a6cfbb75d4a418a2f22b076fa62 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/compile_command.py @@ -0,0 +1,152 @@ +# mypy: allow-untyped-defs +import logging +import os + +from torch._inductor import config +from torch._inductor.utils import is_linux, try_import_ck_lib + + +log = logging.getLogger(__name__) + + +def _rocm_include_paths(dst_file_ext: str) -> list[str]: + from torch.utils import cpp_extension + + rocm_include = ( + os.path.join(config.rocm.rocm_home, "include") + if config.rocm.rocm_home + else cpp_extension._join_rocm_home("include") + ) + + if config.is_fbcode(): + from libfb.py import parutil + + ck_path = parutil.get_dir_path("composable-kernel-headers") + else: + if not config.rocm.ck_dir: + ck_dir, _, _, _ = try_import_ck_lib() + if not ck_dir: + log.warning("Unspecified Composable Kernel directory") + config.rocm.ck_dir = ck_dir + ck_path = config.rocm.ck_dir or cpp_extension._join_rocm_home( + "composable_kernel" + ) + + log.debug("Using ck path %s", ck_path) + + ck_include = os.path.join(ck_path, "include") + ck_library_include = os.path.join(ck_path, "library", "include") + + # CK has to take priority over ROCm include paths + # Since CK is potentially more up-to-date + paths = [ + os.path.realpath(p) for p in (ck_include, ck_library_include, rocm_include) + ] + if dst_file_ext == "exe": + ck_utility_include = os.path.join(ck_path, "library", "src", "utility") + paths.append(os.path.realpath(ck_utility_include)) + return paths + + +def _rocm_lib_options(dst_file_ext: str) -> list[str]: + from torch.utils import cpp_extension + + rocm_lib_dir = ( + os.path.join(config.rocm.rocm_home, "lib") + if config.rocm.rocm_home + else cpp_extension._join_rocm_home("lib") + ) + hip_lib_dir = ( + os.path.join(config.rocm.rocm_home, "hip", "lib") + if config.rocm.rocm_home + else cpp_extension._join_rocm_home("hip", "lib") + ) + + opts = [ + "-include __clang_hip_runtime_wrapper.h", + f"-L{os.path.realpath(rocm_lib_dir)}", + f"-L{os.path.realpath(hip_lib_dir)}", + "-lamdhip64", + ] + if dst_file_ext == "exe": + opts += ["-lpthread", "-lstdc++"] + return opts + + +def _rocm_compiler_options() -> list[str]: + arch_list = config.rocm.arch or ["native"] + gpu_arch_flags = [f"--offload-arch={arch}" for arch in arch_list] + opts = [ + config.rocm.compile_opt_level, + "-x", + "hip", + "-std=c++20", + *gpu_arch_flags, + "-fno-gpu-rdc", + "-fPIC", + "-fvisibility=hidden", + "-mllvm", + "-amdgpu-early-inline-all=true", + "-mllvm", + "-amdgpu-function-calls=false", + "-mllvm", + "-enable-post-misched=0", + ] + if config.rocm.is_debug: + opts += ["-DDEBUG_LOG=1", "-g"] + if config.rocm.save_temps: + opts += ["--save-temps=obj"] + if config.rocm.print_kernel_resource_usage: + opts += ["-Rpass-analysis=kernel-resource-usage"] + if config.rocm.flush_denormals: + opts += ["-fgpu-flush-denormals-to-zero"] + if config.rocm.use_fast_math: + opts += ["-ffast-math"] + return opts + + +def rocm_compiler() -> str | None: + if is_linux(): + if config.rocm.rocm_home: + return os.path.realpath( + os.path.join(config.rocm.rocm_home, "llvm", "bin", "clang") + ) + try: + from torch.utils import cpp_extension + + return os.path.realpath( + cpp_extension._join_rocm_home("llvm", "bin", "clang") + ) + except OSError: + # neither config.rocm.rocm_home nor env variable ROCM_HOME are set + return "clang" + return None + + +def rocm_compile_command( + src_files: list[str], + dst_file: str, + dst_file_ext: str, + extra_args: list[str] | None = None, +) -> str: + include_paths = _rocm_include_paths(dst_file_ext) + lib_options = _rocm_lib_options(dst_file_ext) + compiler_options = _rocm_compiler_options() + compiler = rocm_compiler() + options = ( + compiler_options + + (extra_args or []) + + [f"-I{path}" for path in include_paths] + + lib_options + ) + src_file = " ".join(src_files) + # supported extensions: .o, .so, .exe + if dst_file_ext == "o": + options.append("-c") + elif dst_file_ext == "so": + options.append("-shared") + elif dst_file_ext == "exe": + options.append("-DGENERATE_CK_STANDALONE_RUNNER") + else: + raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!") + return f"{compiler} {' '.join(options)} -o {dst_file} {src_file}" 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