diff --git a/autoparallel/apply_sharding.py b/autoparallel/apply_sharding.py index a18608b4..e3a865cd 100644 --- a/autoparallel/apply_sharding.py +++ b/autoparallel/apply_sharding.py @@ -235,7 +235,7 @@ def _call_getitem(self, args): return [tuple(new_args_0), idx], tgt_spec - def _redistribute_and_adjust_args(self, target, args): + def _redistribute_and_adjust_args(self, target, args, kwargs): node = self._curr_node all_input_nodes = self._get_input_nodes(node) num_input_nodes = len(all_input_nodes) @@ -246,7 +246,10 @@ def _redistribute_and_adjust_args(self, target, args): self.sharding_placement[node].input_specs[c] for c in range(num_input_nodes) ] - flat_args, treespec = tree_flatten(args) + # Tensors are normally positional, but higher-order ops such as + # auto_functionalized_v2 take all of them as kwargs: all_input_nodes + # (and so the specs) follow (args, kwargs) order. + flat_args, treespec = tree_flatten((args, kwargs)) flat_args_t = [x for x in flat_args if isinstance(x, torch.Tensor)] if len(flat_args_t) < len(curr_specs): # HOPs have mixed arg types (tensors, SymInts, etc.). @@ -286,7 +289,8 @@ def _redistribute_and_adjust_args(self, target, args): counter += 1 new_flat_args.append(x) - new_args = list(treespec.unflatten(new_flat_args)) + new_args, new_kwargs = treespec.unflatten(new_flat_args) + new_args = list(new_args) # Localize shape args for factory and view ops. # In static mode, shape args are concrete global values baked into the @@ -329,7 +333,7 @@ def _redistribute_and_adjust_args(self, target, args): ) new_args[0]._spec.shard_order = tgt_spec.shard_order - return new_args, last_tgt_spec + return new_args, new_kwargs, last_tgt_spec def call_function(self, target, args, kwargs): if self._curr_node not in self.sharding_placement: @@ -339,10 +343,13 @@ def call_function(self, target, args, kwargs): if self._curr_node.target == operator.getitem: new_args, tgt_spec = self._call_getitem(args) + new_kwargs = kwargs else: - new_args, tgt_spec = self._redistribute_and_adjust_args(target, args) + new_args, new_kwargs, tgt_spec = self._redistribute_and_adjust_args( + target, args, kwargs + ) - out = super().call_function(target, tuple(new_args), kwargs) + out = super().call_function(target, tuple(new_args), new_kwargs) out = tree_map_only(DTensor, lambda x: x.to_local(), out) return out diff --git a/autoparallel/cost_models/compute_estimation.py b/autoparallel/cost_models/compute_estimation.py index fb0b4f73..c5b2b6fd 100644 --- a/autoparallel/cost_models/compute_estimation.py +++ b/autoparallel/cost_models/compute_estimation.py @@ -3,6 +3,7 @@ # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. +import math from contextlib import contextmanager from dataclasses import dataclass from typing import Dict, Tuple @@ -13,6 +14,7 @@ from torch.utils._pytree import tree_flatten, tree_map_only from torch.utils.flop_counter import FlopCounterMode, register_flop_formula +from autoparallel.shardings.auto_functionalize import is_auto_functionalized_v2 from autoparallel.shardings.propagation_rules import _SHAPE_FACTORY_OPS _cost_model_device_name: str | None = None @@ -587,6 +589,34 @@ def _make_hashable(x): return x +def _auto_functionalized_runtime_cost(node, strategy): + """Memory-bound estimate for an auto_functionalized_v2 node: the wrapped op is an opaque + custom op (no flop formula), so like any such op it costs the time to read its sharded + inputs and write its sharded outputs. An updated base is both an input and an output + (read-modify-write once Inductor re-inplaces the mutation).""" + + def spec_bytes(spec): + shape, _ = _get_sharded_shape_stride(spec) + return math.prod(shape) * spec.tensor_meta.dtype.itemsize + + if strategy is None: + flat = tree_flatten( + ( + tree_map_only(torch.fx.Node, lambda x: x.meta["val"], node.kwargs), + node.meta["val"], + ) + )[0] + nbytes = sum( + x.numel() * x.element_size() for x in flat if isinstance(x, torch.Tensor) + ) + else: + specs = list(strategy.input_specs) + [ + spec for spec in strategy.output_specs if spec is not None + ] + nbytes = sum(spec_bytes(spec) for spec in specs) + return compute_read_write_time(nbytes) + + def estimate_strategy_runtime_cost(node, strategy): """ This function estimates the runtime cost of a given strategy @@ -595,6 +625,9 @@ def estimate_strategy_runtime_cost(node, strategy): inputs according to the strategy. It then uses the device specifications to estimate the runtime cost of the node. """ + if is_auto_functionalized_v2(node): + return _auto_functionalized_runtime_cost(node, strategy) + if _has_zero_cost(node): return 0 diff --git a/autoparallel/graph_passes/graph_utils.py b/autoparallel/graph_passes/graph_utils.py index 434c65c6..42a86f31 100644 --- a/autoparallel/graph_passes/graph_utils.py +++ b/autoparallel/graph_passes/graph_utils.py @@ -440,8 +440,18 @@ def _replace_view_mm_view_with_einsum(gm): def all_input_nodes(node: torch.fx.Node) -> list[torch.fx.Node]: - """Variant of node.all_input_nodes that preserves duplicate nodes.""" - return [x for x in tree_flatten(node.args)[0] if isinstance(x, torch.fx.Node)] + """Variant of node.all_input_nodes that preserves duplicate nodes. + + Nodes are listed in ``(node.args, node.kwargs)`` order, matching the + input order of the node's ``OpSpec.input_specs``. Most ops take their + tensors positionally, but higher-order ops such as + ``auto_functionalized_v2`` take them all as kwargs. + """ + return [ + x + for x in tree_flatten((node.args, node.kwargs))[0] + if isinstance(x, torch.fx.Node) + ] def build_param_derived_set(graph: torch.fx.Graph) -> set[torch.fx.Node]: diff --git a/autoparallel/optimize_sharding.py b/autoparallel/optimize_sharding.py index de396b86..e76d049f 100644 --- a/autoparallel/optimize_sharding.py +++ b/autoparallel/optimize_sharding.py @@ -383,8 +383,18 @@ def build_sharding_metadata(self): user_kwargs = tree_map_only( torch.fx.Node, lambda x: x.meta.get("val"), node.kwargs ) + user_kwarg_strats = tree_map_only( + torch.fx.Node, + lambda x: strats.get(x, x.meta.get("val")), + node.kwargs, + ) strats[node] = get_placement_options_for_node( - self.mesh, node, user_strats, user_args, user_kwargs + self.mesh, + node, + user_strats, + user_args, + user_kwargs, + user_kwarg_strats, ) elif node.op == "output": user_strats = tree_map_only( diff --git a/autoparallel/shardings/auto_functionalize.py b/autoparallel/shardings/auto_functionalize.py new file mode 100644 index 00000000..e747947d --- /dev/null +++ b/autoparallel/shardings/auto_functionalize.py @@ -0,0 +1,329 @@ +# 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. + +"""Sharding support for ``auto_functionalized_v2`` nodes. + +``aot_export_module`` functionalizes a custom op that declares ``mutates_args`` into a +call to the higher-order op ``auto_functionalized_v2`` (see +``torch/_higher_order_ops/auto_functionalize.py``). The node looks like:: + + auto_functionalized_v2(op, =..., __base_index=i, + ..., _all_bases=[base_0, base_1, ...]) + + value = (op returns..., updated base_0, updated base_1, ...) + +so, unlike every other node AutoParallel sees: + +* ``node.args`` is just ``(op,)``; every tensor input is in ``node.kwargs``; +* a *mutated* argument is not an input at all: it is regenerated from ``_all_bases``, and the + node's value carries the updated bases after the op's own returns. + +The wrapped op's sharding rule is the one registered with DTensor (``register_sharding`` / +``register_op_strategy``) for the op's own schema, in which the mutated tensor is an ordinary +argument. This module rebuilds that call from the node, asks the DTensor registry for the +strategy, and maps it back: input specs are laid out in ``all_input_nodes`` order, the op's +returns keep the op's output specs, and each updated base takes the placement its mutated +argument was given. + +Nothing here refers to a particular op's signature: it is derived from the op's schema and +the node's structure, so an op that later turns functional (no mutated arguments, no bases) +goes through the same code. +""" + +import contextlib +import dataclasses +from typing import Any, Iterator, Optional + +import torch +import torch.utils._pytree as pytree +from torch._higher_order_ops.auto_functionalize import ( + AliasViewInfo, + NotView, + get_mutable_args_from_schema, + read_view_information_from_args, +) +from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta +from torch.distributed.tensor._op_schema import ( + OpSchema, + OpSpec, + OpStrategy, + RuntimeSchemaInfo, + TupleStrategy, +) +from torch.distributed.tensor._ops.utils import generate_redistribute_costs +from torch.distributed.tensor.placement_types import Replicate + +from .dtensor_sharding_helpers import get_op_strategy, with_implicit_strategies +from .propagation_rules import _op_rules, remove_invalid_configs + +_BASES = "_all_bases" + +# One input slot of an auto_functionalized_v2 node: a key identifying where the tensor +# sits in the node (("base", i) or (kwarg name,) or (kwarg name, i) for a tensor list). +SlotKey = tuple + + +def is_auto_functionalized_v2(node: torch.fx.Node) -> bool: + return ( + node.op == "call_function" + and node.target is torch.ops.higher_order.auto_functionalized_v2 + ) + + +@dataclasses.dataclass(frozen=True) +class AutoFunctionalizedCall: + """The wrapped op of an ``auto_functionalized_v2`` node, decoded. + + ``op``: the wrapped custom op. ``bases``: the ``_all_bases`` nodes. ``base_of_arg``: + mutated schema argument name -> index into ``bases``. ``replicate_only``: some mutated + argument is a strict view of its base (slice / as_strided), or two mutated arguments + share a base; the base then has a different shape than the argument the op rule is + written for, so the node is only given the all-replicated strategy. + """ + + op: torch._ops.OpOverload + bases: tuple[Any, ...] + base_of_arg: dict[str, int] + replicate_only: bool + + @property + def schema(self) -> torch.FunctionSchema: + return self.op._schema + + +def decode_auto_functionalized_v2(node: torch.fx.Node) -> AutoFunctionalizedCall: + if not is_auto_functionalized_v2(node): + raise ValueError(f"{node} is not an auto_functionalized_v2 node") + op = node.args[0] + if not isinstance(op, torch._ops.OpOverload): + raise NotImplementedError( + f"auto_functionalized_v2 of {op!r}: only OpOverload targets are supported" + ) + if any(isinstance(x, torch.fx.Node) for x in pytree.tree_leaves(node.args)): + raise NotImplementedError( + f"{node}: tensors in auto_functionalized_v2 positional args" + ) + schema = op._schema + kwargs = dict(node.kwargs) + bases = tuple(kwargs.pop(_BASES, ())) + names, types = get_mutable_args_from_schema(schema) + if torch._library.utils.is_out(op): + # out= variant: write-only buffers, described by __size/_stride, no bases. + raise NotImplementedError( + f"auto_functionalized_v2 of out= op {op}: not supported" + ) + for name, typ in zip(names, types): + if torch._library.utils.is_tensorlist_like_type(typ): + raise NotImplementedError( + f"{op}: mutated tensor-list argument {name!r} is not supported" + ) + view_info = read_view_information_from_args(names, types, kwargs, list(bases)) + base_of_arg: dict[str, int] = {} + replicate_only = False + for name in names: + info = view_info[name] + if info is None: # Optional[Tensor] passed as None + continue + if not isinstance(info, (NotView, AliasViewInfo)): + replicate_only = True + base_of_arg[name] = info.base_index + if len(set(base_of_arg.values())) != len(base_of_arg): + replicate_only = True + return AutoFunctionalizedCall(op, bases, base_of_arg, replicate_only) + + +def _is_strategy(x: Any) -> bool: + return isinstance(x, OpStrategy) + + +def input_slots(kwarg_specs: dict[str, Any]) -> list[tuple[SlotKey, OpStrategy]]: + """The tensor inputs of the node, in ``all_input_nodes`` order, with their producers' + strategies. ``kwarg_specs`` is ``node.kwargs`` with every node that the solver tracks + replaced by its ``OpStrategy``.""" + slots: list[tuple[SlotKey, OpStrategy]] = [] + for name, value in kwarg_specs.items(): + if isinstance(value, (list, tuple)): + for i, x in enumerate(value): + if _is_strategy(x): + key: SlotKey = ("base", i) if name == _BASES else (name, i) + slots.append((key, x)) + elif _is_strategy(value): + slots.append(((name,), value)) + return slots + + +def _tensor_meta(t: Any) -> Optional[TensorMeta]: + if not isinstance(t, torch.Tensor): + return None + return TensorMeta(t.shape, t.stride(), t.dtype) + + +def _slot_key_of_arg(call: AutoFunctionalizedCall, name: str) -> SlotKey: + if name in call.base_of_arg: + return ("base", call.base_of_arg[name]) + return (name,) + + +def _inner_op_schema( + call: AutoFunctionalizedCall, + kwarg_specs: dict[str, Any], + user_kwargs: dict[str, Any], +) -> tuple[OpSchema, list[SlotKey]]: + """The call ``op(*args, **kwargs)`` the node wraps, with strategies for tensors, and + the slot of every tensor input in the order DTensor lists them in ``input_specs``. + """ + args: list[Any] = [] + kwargs: dict[str, Any] = {} + slots: list[SlotKey] = [] + needs_pytree = False + for arg in call.schema.arguments: + name = arg.name + value: Any + if name in call.base_of_arg: + i = call.base_of_arg[name] + value = kwarg_specs[_BASES][i] + slots.append(("base", i)) + elif name in kwarg_specs: + value = kwarg_specs[name] + if isinstance(value, (list, tuple)) and any(_is_strategy(x) for x in value): + value = TupleStrategy(tuple(value)) + needs_pytree = True + slots.extend((name, i) for i in range(len(value.children))) + elif _is_strategy(value): + slots.append((name,)) + else: + value = user_kwargs[name] + elif arg.has_default_value(): + value = arg.default_value + else: + # A mutated Optional[Tensor] passed as None, or an arg AOT left out. + value = None + if arg.kwarg_only: + kwargs[name] = value + else: + args.append(value) + schema = OpSchema( + call.op, tuple(args), kwargs, RuntimeSchemaInfo(needs_pytree=needs_pytree) + ) + return schema, slots + + +def _as_spec_list(output_specs: Any) -> list[Optional[DTensorSpec]]: + if output_specs is None: + return [] + if isinstance(output_specs, DTensorSpec): + return [output_specs] + return list(output_specs) + + +@contextlib.contextmanager +def _not_inplace_for_strategy() -> Iterator[None]: + """Make ``OpSchema.is_inplace_op`` false while a strategy is generated. + + DTensor calls an op "in place" by its name (a trailing ``_``) and then drops every + strategy whose placement for the first argument differs from the placement that argument + *currently has*: eager DTensor cannot redistribute an operand it is about to overwrite. + Inside ``auto_functionalized_v2`` the mutation is functional (the mutated tensor is a + base, copied or re-inplaced later), and the solver, not the runtime, chooses the + placement of every input, so that restriction would only discard valid strategies. + """ + original = OpSchema.is_inplace_op + OpSchema.is_inplace_op = lambda self: False # type: ignore[method-assign] + try: + yield + finally: + OpSchema.is_inplace_op = original # type: ignore[method-assign] + + +def get_auto_functionalized_placement_option( + mesh, node: torch.fx.Node, kwarg_specs: dict[str, Any], user_kwargs: dict[str, Any] +) -> OpStrategy: + """OpStrategy of an ``auto_functionalized_v2`` node. + + Outputs: the wrapped op's returns, then one entry per updated base (the node's value is + ``(*op returns, *updated bases)``), each updated base placed like the mutated argument it + is regenerated into. The mutation is therefore placement-preserving by construction. + """ + call = decode_auto_functionalized_v2(node) + slots = input_slots(kwarg_specs) + val = node.meta["val"] + n_bases = len(call.bases) + n_returns = len(val) - n_bases + base_metas = [_tensor_meta(b.meta["val"]) for b in call.bases] + ret_metas = [_tensor_meta(v) for v in val[:n_returns]] + + def make( + in_specs: dict[SlotKey, DTensorSpec], ret_specs: list[Optional[DTensorSpec]] + ) -> OpSpec: + outs: list[Optional[DTensorSpec]] = [] + for j, meta in enumerate(ret_metas): + spec = ret_specs[j] if j < len(ret_specs) else None + if meta is None: + outs.append(None) + continue + if spec is None: + spec = DTensorSpec(mesh, (Replicate(),) * mesh.ndim) + outs.append(DTensorSpec(mesh, spec.placements, tensor_meta=meta)) + for i, meta in enumerate(base_metas): + src = in_specs[("base", i)] + outs.append(DTensorSpec(mesh, src.placements, tensor_meta=meta)) + ordered_in = [in_specs[key] for key, _ in slots] + return OpSpec( + output_specs=tuple(outs), + input_specs=tuple(ordered_in), + redistribute_cost=[ + generate_redistribute_costs(strategy, spec) + for (_, strategy), spec in zip(slots, ordered_in) + ], + ) + + if call.replicate_only: + replicated = (Replicate(),) * mesh.ndim + in_specs = { + key: DTensorSpec( + mesh, + replicated, + tensor_meta=strategy.strategies[0].output_spec.tensor_meta, + ) + for key, strategy in slots + } + return OpStrategy([make(in_specs, [])]) + + op_schema, inner_slots = _inner_op_schema(call, kwarg_specs, user_kwargs) + with _not_inplace_for_strategy(): + if call.op in _op_rules: + inner = _op_rules[call.op](mesh, op_schema) + else: + with with_implicit_strategies(): + inner = get_op_strategy(call.op, op_schema) + if isinstance(inner, TupleStrategy) or not isinstance(inner, OpStrategy): + raise NotImplementedError(f"{call.op}: strategy of type {type(inner)}") + + slot_strategy = dict(slots) + strategies = [] + for s in inner.strategies: + if s.input_specs is None or len(s.input_specs) != len(inner_slots): + raise NotImplementedError( + f"{call.op}: strategy has {None if s.input_specs is None else len(s.input_specs)} " + f"input specs for {len(inner_slots)} tensor inputs" + ) + in_specs = {} + for key, spec in zip(inner_slots, s.input_specs): + if spec.tensor_meta is None: + spec = DTensorSpec( + mesh, + spec.placements, + tensor_meta=slot_strategy[key] + .strategies[0] + .output_spec.tensor_meta, + ) + in_specs[key] = spec + strategies.append(make(in_specs, _as_spec_list(s.output_specs))) + out = remove_invalid_configs(OpStrategy(strategies), mesh) + if not out.strategies: + raise RuntimeError( + f"{node}: no valid sharding of {call.op} for mesh shape {tuple(mesh.shape)}" + ) + return out diff --git a/autoparallel/shardings/ordered_sharding.py b/autoparallel/shardings/ordered_sharding.py index ada59193..97fa1b76 100644 --- a/autoparallel/shardings/ordered_sharding.py +++ b/autoparallel/shardings/ordered_sharding.py @@ -18,7 +18,8 @@ Replicate, Shard, ) -from torch.utils._pytree import tree_flatten + +from autoparallel.graph_passes.graph_utils import all_input_nodes as _all_input_nodes # Supported placement patterns for the ordered sharding optimization _PARAM_PLACEMENT = (Shard(0), Shard(0)) @@ -110,9 +111,7 @@ def get_redistributed_input_placements( placements, for the inputs that need to be redistributed. """ # use this instead of node.all_input_nodes as it handles repeated nodes - all_input_nodes = [ - x for x in tree_flatten(node.args)[0] if isinstance(x, torch.fx.Node) - ] + all_input_nodes = _all_input_nodes(node) num_input_nodes = len(all_input_nodes) curr_specs: list[Union[DTensorSpec, tuple[Optional[DTensorSpec], ...], None]] = [ sharding_placement[n].output_specs for n in all_input_nodes diff --git a/autoparallel/shardings/placement_options.py b/autoparallel/shardings/placement_options.py index 47974b18..45369e3a 100644 --- a/autoparallel/shardings/placement_options.py +++ b/autoparallel/shardings/placement_options.py @@ -30,6 +30,10 @@ from autoparallel.shardings.propagation_rules import generate_dummy_redistribute_costs +from .auto_functionalize import ( + get_auto_functionalized_placement_option, + is_auto_functionalized_v2, +) from .dtensor_sharding_helpers import get_op_strategy, with_implicit_strategies from .propagation_rules import _op_rules, remove_invalid_configs @@ -309,9 +313,11 @@ def get_placement_options(mesh, op, specs, user_args, user_kwargs): op, tuple(_fingerprint_arg(s) for s in specs), tuple(_fingerprint_arg(a) for a in user_args), - tuple(_fingerprint_arg(v) for v in user_kwargs.values()) - if user_kwargs - else (), + ( + tuple(_fingerprint_arg(v) for v in user_kwargs.values()) + if user_kwargs + else () + ), ) hash(cache_key) # fail fast if key contains unhashable types (e.g. SymInts) except TypeError: @@ -684,7 +690,16 @@ def tensor_placement(t, placement): return OpStrategy(strategies) -def get_placement_options_for_node(mesh, node, specs, user_args, user_kwargs): +def get_placement_options_for_node( + mesh, node, specs, user_args, user_kwargs, kwarg_specs=None +): + """``specs`` / ``kwarg_specs`` are ``node.args`` / ``node.kwargs`` with each producer + node replaced by its OpStrategy; ``user_args`` / ``user_kwargs`` by its example value. + """ + if is_auto_functionalized_v2(node): + return get_auto_functionalized_placement_option( + mesh, node, kwarg_specs or {}, user_kwargs + ) if local_map_kwargs := node.meta.get("local_map_kwargs", {}): assert not user_kwargs return get_local_map_placement_option( diff --git a/tests/test_auto_functionalize.py b/tests/test_auto_functionalize.py new file mode 100644 index 00000000..61e9dfa7 --- /dev/null +++ b/tests/test_auto_functionalize.py @@ -0,0 +1,538 @@ +# 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. + +"""``auto_functionalized_v2`` nodes: custom ops with ``mutates_args``. + +``aot_export_module`` turns such a call into ``auto_functionalized_v2(op, **kwargs)``, where +every tensor is a kwarg and a mutated argument is a base in ``_all_bases``. These tests run +one-op graphs through the solver on a fake process group, and through the apply path on a +real (gloo, CPU) group, comparing with the eager op. +""" + +import os +import socket + +import pytest +import torch +import torch.distributed as dist +import torch.multiprocessing as mp +from torch._functorch._aot_autograd.descriptors import PlainAOTInput, PlainAOTOutput +from torch._functorch.aot_autograd import aot_export_module +from torch._subclasses.fake_tensor import FakeTensorMode +from torch.distributed.device_mesh import DeviceMesh, init_device_mesh +from torch.distributed.tensor.experimental import register_sharding +from torch.distributed.tensor.placement_types import Replicate, Shard + +from autoparallel.api import AutoParallel +from autoparallel.apply_sharding import ( + _build_physical_placements, + _lower_to_parallel_graph, + _make_local_args, +) +from autoparallel.cost_models.compute_estimation import ( + estimate_strategy_runtime_cost, + override_cost_model_device_name, +) +from autoparallel.graph_passes.graph_utils import all_input_nodes +from autoparallel.optimize_sharding import ShardingOptimizer +from autoparallel.shardings.auto_functionalize import ( + decode_auto_functionalized_v2, + is_auto_functionalized_v2, +) +from autoparallel.shardings.placement_options import reset_placement_options_cache + +# --------------------------------------------------------------------------- +# Toy mutating ops. Each has a registered DTensor rule (``register_sharding``); the +# rules are the thing the solver must pick up through the HOP. +# --------------------------------------------------------------------------- + + +@torch.library.custom_op("ap_af_test::rowop", mutates_args=("buf",)) +def rowop(x: torch.Tensor, buf: torch.Tensor, alpha: float) -> torch.Tensor: + """``buf += alpha * x``; returns ``2 * x``. Pointwise, so any dim may be sharded.""" + buf.add_(x * alpha) + return x * 2 + + +@rowop.register_fake +def _rowop_fake(x, buf, alpha): + return torch.empty_like(x) + + +@torch.library.custom_op("ap_af_test::rowop_", mutates_args=("buf",)) +def rowop_inplace_named( + x: torch.Tensor, buf: torch.Tensor, alpha: float +) -> torch.Tensor: + """``rowop`` under a name DTensor treats as an in-place op (trailing underscore).""" + buf.add_(x * alpha) + return x * 2 + + +@rowop_inplace_named.register_fake +def _rowop_inplace_named_fake(x, buf, alpha): + return torch.empty_like(x) + + +@torch.library.custom_op("ap_af_test::pick", mutates_args=("ids", "alpha")) +def pick(scores: torch.Tensor, ids: torch.Tensor, alpha: torch.Tensor) -> None: + """Row-wise arg-max into two mutated outputs, returning nothing (like the router ops).""" + top, idx = scores.max(dim=-1, keepdim=True) + ids.copy_(idx) + alpha.copy_(top) + + +@pick.register_fake +def _pick_fake(scores, ids, alpha) -> None: + return None + + +@register_sharding(torch.ops.ap_af_test.rowop.default) +@register_sharding(torch.ops.ap_af_test.rowop_.default) +def _rowop_rule(x, buf, alpha): + options = [([Shard(d)], [Shard(d), Shard(d), None]) for d in range(x.ndim)] + options.append(([Replicate()], [Replicate(), Replicate(), None])) + return options + + +@register_sharding(torch.ops.ap_af_test.pick.default) +def _pick_rule(scores, ids, alpha): + # Rows are independent; the reduced dim (-1) may not be sharded. No outputs. + return [([], [Shard(0), Shard(0), Shard(0)]), ([], [Replicate()] * 3)] + + +class OneOp(torch.nn.Module): + def __init__(self, op): + super().__init__() + self.op = op + + def forward(self, x, buf): + y = self.op(x, buf, 0.5) + return (y,) + + +class Pick(torch.nn.Module): + def forward(self, scores, ids, alpha): + torch.ops.ap_af_test.pick(scores, ids, alpha) + return (ids * 1, alpha * 1) + + +ROWOP = torch.ops.ap_af_test.rowop +ROWOP_UNDERSCORE = torch.ops.ap_af_test.rowop_ + + +def _export(module, *inputs): + """One-op graph of ``module`` as the step compiler would capture it.""" + fake_mode = FakeTensorMode(allow_non_fake_inputs=True) + # As the step compiler captures: triton_ops stay opaque nodes, and a mutating one becomes + # auto_functionalized_v2 instead of being decomposed into its kernel launch. + with fake_mode, torch._functorch.config.patch(decompose_custom_triton_ops=False): + fakes = tuple(torch.empty_like(t) for t in inputs) + gm, _ = aot_export_module(module, fakes, trace_joint=False) + for i, node in enumerate(gm.graph.find_nodes(op="placeholder")): + node.meta["desc"] = PlainAOTInput(idx=i) + output = gm.graph.find_nodes(op="output")[0] + output.meta["desc"] = [PlainAOTOutput(idx=i) for i in range(len(output.args[0]))] + return gm, fake_mode + + +def _af_node(gm): + (node,) = [n for n in gm.graph.nodes if is_auto_functionalized_v2(n)] + return node + + +def _optimizer(gm, fake_mode, mesh): + reset_placement_options_cache() + with override_cost_model_device_name("NVIDIA H200"), fake_mode: + return ShardingOptimizer(gm, mesh) + + +@pytest.fixture +def mesh_1d(): + return DeviceMesh("cpu", torch.arange(4), mesh_dim_names=("dp",)) + + +@pytest.fixture +def mesh_2d(): + return DeviceMesh("cpu", torch.arange(8).reshape(2, 4), mesh_dim_names=("dp", "tp")) + + +def _placements(spec): + return tuple(spec.placements) + + +# --------------------------------------------------------------------------- +# Graph structure +# --------------------------------------------------------------------------- + + +def test_node_structure_and_decode(): + gm, _ = _export(OneOp(ROWOP), torch.randn(8, 4), torch.zeros(8, 4)) + node = _af_node(gm) + assert node.args == (ROWOP.default,) + assert "x" in node.kwargs and "_all_bases" in node.kwargs + + call = decode_auto_functionalized_v2(node) + assert call.op == ROWOP.default + assert call.base_of_arg == {"buf": 0} + assert not call.replicate_only + assert len(call.bases) == 1 + + +def test_all_input_nodes_reads_kwargs(): + gm, _ = _export(OneOp(ROWOP), torch.randn(8, 4), torch.zeros(8, 4)) + node = _af_node(gm) + x, buf = gm.graph.find_nodes(op="placeholder") + # Duplicates preserved, kwargs order: x, then _all_bases. + assert all_input_nodes(node) == [x, buf] + + +class SliceMutation(torch.nn.Module): + def forward(self, x, buf): + y = torch.ops.ap_af_test.rowop(x[:, :2], buf[:, :2], 0.5) + return (y,) + + +def test_view_of_base_is_replicate_only(): + gm, _ = _export(SliceMutation(), torch.randn(8, 4), torch.zeros(8, 4)) + assert decode_auto_functionalized_v2(_af_node(gm)).replicate_only + + +# --------------------------------------------------------------------------- +# Strategies and the solve +# --------------------------------------------------------------------------- + + +def _node_strategies(optimizer, node): + return optimizer.strats[optimizer._normalize_node(node)].strategies + + +@pytest.mark.parametrize( + "op", [ROWOP, ROWOP_UNDERSCORE], ids=["plain", "inplace_named"] +) +def test_strategies_are_the_registered_rule(mesh_1d, op): + gm, fake_mode = _export(OneOp(op), torch.randn(64, 8), torch.zeros(64, 8)) + opt = _optimizer(gm, fake_mode, mesh_1d) + strategies = _node_strategies(opt, _af_node(gm)) + + got = {tuple(_placements(s) for s in strat.input_specs) for strat in strategies} + want = { + ((Shard(0),), (Shard(0),)), + ((Shard(1),), (Shard(1),)), + ((Replicate(),), (Replicate(),)), + } + assert got == want + for strat in strategies: + x_spec, buf_spec = strat.input_specs + ret_spec, base_spec = strat.output_specs + # (op return, updated base): the base is placed like the mutated argument. + assert _placements(ret_spec) == _placements(x_spec) + assert _placements(base_spec) == _placements(buf_spec) + assert base_spec.tensor_meta.shape == torch.Size([64, 8]) + assert len(strat.redistribute_cost) == 2 + + +def test_no_return_op_with_two_mutated_args(mesh_1d): + gm, fake_mode = _export( + Pick(), + torch.randn(64, 16), + torch.zeros(64, 1, dtype=torch.int64), + torch.zeros(64, 1), + ) + opt = _optimizer(gm, fake_mode, mesh_1d) + node = _af_node(gm) + assert decode_auto_functionalized_v2(node).base_of_arg == {"ids": 0, "alpha": 1} + for strat in _node_strategies(opt, node): + # value = (None, updated ids, updated alpha) + assert len(strat.output_specs) == 3 + assert strat.output_specs[0] is None + scores, ids, alpha = strat.input_specs + assert _placements(strat.output_specs[1]) == _placements(ids) + assert _placements(strat.output_specs[2]) == _placements(alpha) + assert strat.output_specs[1].tensor_meta.dtype == torch.int64 + + +def test_unregistered_op_falls_back_to_replicate(mesh_1d): + @torch.library.custom_op("ap_af_test::norule", mutates_args=("buf",)) + def norule(x: torch.Tensor, buf: torch.Tensor) -> None: + buf.add_(x) + + @norule.register_fake + def _(x, buf) -> None: + return None + + class M(torch.nn.Module): + def forward(self, x, buf): + torch.ops.ap_af_test.norule(x, buf) + return (buf * 1,) + + gm, fake_mode = _export(M(), torch.randn(64, 8), torch.zeros(64, 8)) + opt = _optimizer(gm, fake_mode, mesh_1d) + (strat,) = _node_strategies(opt, _af_node(gm)) + assert all(_placements(s) == (Replicate(),) for s in strat.input_specs) + + +def test_view_of_base_gets_only_the_replicated_strategy(mesh_1d): + gm, fake_mode = _export(SliceMutation(), torch.randn(64, 8), torch.zeros(64, 8)) + opt = _optimizer(gm, fake_mode, mesh_1d) + (strat,) = _node_strategies(opt, _af_node(gm)) + assert all(_placements(s) == (Replicate(),) for s in strat.input_specs) + assert all(_placements(s) == (Replicate(),) for s in strat.output_specs) + + +def test_solve_picks_registered_sharding(mesh_1d): + gm, fake_mode = _export( + OneOp(ROWOP), torch.randn(4096, 1024), torch.zeros(4096, 1024) + ) + opt = _optimizer(gm, fake_mode, mesh_1d) + opt.add_sharded_input_constraint([(Shard(0),), (Shard(0),)]) + opt.add_sharded_output_constraint([(Shard(0),), (Shard(0),)]) + with override_cost_model_device_name("NVIDIA H200"), fake_mode: + sol = opt.get_solution() + spec = sol[_af_node(gm)] + assert [_placements(s) for s in spec.input_specs] == [(Shard(0),), (Shard(0),)] + assert [_placements(s) for s in spec.output_specs] == [(Shard(0),), (Shard(0),)] + + +def test_solve_on_two_mesh_dims(mesh_2d): + gm, fake_mode = _export( + OneOp(ROWOP), torch.randn(4096, 1024), torch.zeros(4096, 1024) + ) + opt = _optimizer(gm, fake_mode, mesh_2d) + opt.add_sharded_input_constraint([(Shard(0), Shard(1)), (Shard(0), Shard(1))]) + with override_cost_model_device_name("NVIDIA H200"), fake_mode: + sol = opt.get_solution() + spec = sol[_af_node(gm)] + assert [_placements(s) for s in spec.input_specs] == [(Shard(0), Shard(1))] * 2 + + +class ScaleRowsFn(torch.autograd.Function): + """A mutating op cannot carry an autograd formula, so training code wraps it.""" + + @staticmethod + def forward(ctx, x, buf): + return torch.ops.ap_af_test.rowop(x, buf, 0.5) + + @staticmethod + def backward(ctx, grad): + return grad * 2, None + + +class WithMutatingOp(torch.nn.Module): + def __init__(self, dim, rows): + super().__init__() + self.lin = torch.nn.Linear(dim, dim, bias=False) + self.register_buffer("state", torch.zeros(rows, dim)) + + def forward(self, x): + return ScaleRowsFn.apply(self.lin(x), self.state) + self.state + + +def test_autoparallel_end_to_end_with_a_mutating_op(mesh_1d): + """The whole pipeline: joint trace (forward + backward), solve, apply.""" + rows, dim = 4096, 1024 + with torch.device("meta"): + model = WithMutatingOp(dim, rows) + + def input_fn(): + return torch.randn(rows, dim, requires_grad=True) + + reset_placement_options_cache() + with override_cost_model_device_name("NVIDIA H200"): + with AutoParallel(model, input_fn, mesh_1d, repeated_subgraphs=False) as autop: + autop.add_input_constraints([(Shard(0),)]) + autop.add_output_constraints([(Shard(0),)]) + sol = autop.optimize_placement() + (node,) = [n for n in autop.gm.graph.nodes if is_auto_functionalized_v2(n)] + chosen = sol[autop.sharding_optimizer._concrete_to_orig.get(node, node)] + # Sharded rows end to end: no all-gather around the op. + assert [_placements(s) for s in chosen.input_specs] == [(Shard(0),)] * 2 + autop.apply_placement(sol) + applied = [ + n for n in autop.parallel_gm.graph.nodes if is_auto_functionalized_v2(n) + ] + assert applied, "the applied graph keeps the functionalized op" + # The op runs on the local shard: rows / 4. + assert all(n.meta["val"][0].shape == (rows // 4, dim) for n in applied) + + +# --------------------------------------------------------------------------- +# Cost model +# --------------------------------------------------------------------------- + + +def test_cost_scales_with_sharding(mesh_1d): + gm, fake_mode = _export( + OneOp(ROWOP), torch.randn(65536, 1024), torch.zeros(65536, 1024) + ) + opt = _optimizer(gm, fake_mode, mesh_1d) + node = _af_node(gm) + by_input = { + _placements(strat.input_specs[0]): strat + for strat in _node_strategies(opt, node) + } + with override_cost_model_device_name("NVIDIA H200"): + sharded = estimate_strategy_runtime_cost(node, by_input[(Shard(0),)]) + replicated = estimate_strategy_runtime_cost(node, by_input[(Replicate(),)]) + unsharded = estimate_strategy_runtime_cost(node, None) + assert 0 < sharded < replicated + # reads x and the base, writes the return and the base: 4 tensors + assert replicated == pytest.approx(unsharded, rel=1e-6) + assert replicated == pytest.approx(4 * sharded, rel=0.05) + + +# --------------------------------------------------------------------------- +# Apply, against the eager op, on a real process group +# --------------------------------------------------------------------------- + + +def free_port(): + with socket.socket() as s: + s.bind(("", 0)) + return s.getsockname()[1] + + +def solve_and_run(module, inputs, rank, world_size, input_placements, device_type): + """Solve + apply the one-op graph of ``module`` on this rank. + + Returns the parallel graph's local outputs, their placements, the solution, the graph + and this rank's local inputs. + """ + mesh = init_device_mesh(device_type, (world_size,), mesh_dim_names=("dp",)) + gm, fake_mode = _export(module, *inputs) + reset_placement_options_cache() + with override_cost_model_device_name("NVIDIA H200"), fake_mode: + opt = ShardingOptimizer(gm, mesh) + opt.add_sharded_input_constraint([(p,) for p in input_placements]) + sol = opt.get_solution() + physical = _build_physical_placements(sol, {}) + local_args = _make_local_args(gm, physical) + with torch._functorch.config.patch(decompose_custom_triton_ops=False): + parallel_gm = _lower_to_parallel_graph(gm, sol, local_args) + + def shard(t, p): + if p.is_shard(): + return t.chunk(world_size, p.dim)[rank].contiguous() + return t.clone() + + local_inputs = [shard(t, p) for t, p in zip(inputs, input_placements)] + # Some kernels settle over their first launches (autotuning): record the second run. + parallel_gm(*[t.clone() for t in local_inputs]) + outs = parallel_gm(*[t.clone() for t in local_inputs]) + out_node = gm.graph.find_nodes(op="output")[0] + out_placements = [sol[n].output_specs.placements[0] for n in out_node.args[0]] + return outs, out_placements, sol, gm, local_inputs + + +def check_chosen_rule(sol, gm, input_placements): + """The registered rule was chosen (not the replicated fallback), and agrees with the + placements the inputs were constrained to.""" + chosen = [_placements(s) for s in sol[_af_node(gm)].input_specs] + if len(set(input_placements)) == 1: + assert chosen == [(p,) for p in input_placements], chosen + else: + # The rule ties the operands together: the solver redistributes some of them. + assert len(set(chosen)) == 1, chosen + + +def check_against_local_eager( + module, + mutated, + local_inputs, + outs, + out_placements, + rank, + skip_mutated=False, + tol=None, +): + """The applied graph, on this rank's shards, equals the eager op on those shards. + + Valid whenever the op's rule makes a per-shard call equal to the shard of the global + call; that is what a registered rule asserts. The graph returns the mutated inputs + first, then the module's outputs. + """ + ref_inputs = [t.clone() for t in local_inputs] + ref_outs = module(*ref_inputs) + expected = [ref_inputs[i] for i in mutated] + list(ref_outs) + assert len(outs) == len(expected), (len(outs), len(expected)) + first = len(mutated) if skip_mutated else 0 + for out, exp in zip(outs[first:], expected[first:]): + torch.testing.assert_close(out, exp, **(tol or {})) + + +def _toy_rowop(op): + def case(): + return OneOp(op), (torch.randn(8, 6), torch.randn(8, 6)), [1] + + return case + + +def _toy_pick(): + scores = torch.randn(8, 6) + return ( + Pick(), + (scores, torch.zeros(8, 1, dtype=torch.int64), torch.zeros(8, 1)), + [1, 2], + ) + + +def _worker(rank, world_size, port, case_name, input_placements): + os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT=str(port)) + dist.init_process_group("gloo", rank=rank, world_size=world_size) + try: + case = { + "rowop": _toy_rowop(ROWOP), + "rowop_": _toy_rowop(ROWOP_UNDERSCORE), + "pick": _toy_pick, + }[case_name] + torch.manual_seed(0) + module, inputs, mutated = case() + outs, out_placements, sol, gm, local_inputs = solve_and_run( + module, inputs, rank, world_size, input_placements, "cpu" + ) + check_chosen_rule(sol, gm, input_placements) + if len(set(input_placements)) == 1: + # (Mismatched operands have no per-shard eager call; the global check covers them.) + check_against_local_eager( + module, mutated, local_inputs, outs, out_placements, rank + ) + + # The toy rules are also true globally: the output is the shard of the eager result. + ref_inputs = [t.clone() for t in inputs] + expected = [*(ref_inputs[i] for i in mutated), *module(*ref_inputs)] + for out, exp, plc in zip(outs, expected, out_placements): + exp_local = exp.chunk(world_size, plc.dim)[rank] if plc.is_shard() else exp + torch.testing.assert_close(out, exp_local) + finally: + dist.destroy_process_group() + + +def _spawn(case_name, world_size, input_placements): + mp.spawn( + _worker, + args=(world_size, free_port(), case_name, input_placements), + nprocs=world_size, + join=True, + ) + + +@pytest.mark.parametrize("world_size", [2, 4]) +@pytest.mark.parametrize("case_name", ["rowop", "rowop_"]) +def test_apply_matches_eager_rowop(case_name, world_size): + _spawn(case_name, world_size, (Shard(0), Shard(0))) + + +def test_apply_matches_eager_rowop_sharded_on_dim1(): + _spawn("rowop", 2, (Shard(1), Shard(1))) + + +def test_apply_redistributes_a_misplaced_base(): + # x row-sharded, buf column-sharded: the op's rule needs them to agree, so apply must + # redistribute a kwarg/base it finds in kwargs, not only positional args. + _spawn("rowop", 2, (Shard(0), Shard(1))) + + +@pytest.mark.parametrize("world_size", [2, 4]) +def test_apply_matches_eager_no_return_two_mutated(world_size): + _spawn("pick", world_size, (Shard(0), Shard(0), Shard(0)))