diff --git a/autoparallel/apply_sharding.py b/autoparallel/apply_sharding.py index a18608b4..a317efe1 100644 --- a/autoparallel/apply_sharding.py +++ b/autoparallel/apply_sharding.py @@ -21,11 +21,13 @@ from torch.distributed.tensor import DTensor from torch.distributed.tensor._dtensor_spec import DTensorSpec, ShardOrderEntry from torch.distributed.tensor._redistribute import use_min_cost_redistribution_plan +from torch.distributed.tensor._utils import compute_local_stride from torch.distributed.tensor.placement_types import Partial, Replicate, Shard # noqa from torch.fx.experimental.proxy_tensor import make_fx from torch.utils._pytree import tree_flatten, tree_map_only from .graph_passes.graph_utils import all_input_nodes, cleanup_graph +from .shardings.dtensor_sharding_helpers import get_shape_and_stride_arg_indices from .shardings.ordered_sharding import ( compute_optimal_placement_order_for_parameters, ordered_redistribute_local_tensor, @@ -301,6 +303,21 @@ def _redistribute_and_adjust_args(self, target, args): elif self.dynamic and target in _VIEW_OPS: spec = self.sharding_placement[node].output_specs new_args[1] = _localize_shape_arg(node, new_args[1], spec) + elif target not in _VIEW_OPS: + # Other ops that take their output size as an argument, such as + # slice_backward, the upsample backward ops and new_empty_strided: + # localize it as DTensor would. + indices = get_shape_and_stride_arg_indices(target) + spec = self.sharding_placement[node].output_specs + if indices is not None and any(p.is_shard() for p in spec.placements): + shape_idx, stride_idx = indices + local_shape = _localize_shape_arg(node, new_args[shape_idx], spec) + new_args[shape_idx] = local_shape + if stride_idx is not None: + global_stride = _concretize_shape(node.meta["val"].stride()) + new_args[stride_idx] = list( + compute_local_stride(global_stride, local_shape) + ) # In static mode, view ops use DTensor wrapping to convert global # shape args to local (DTensor handles the global→local conversion diff --git a/autoparallel/cost_models/compute_estimation.py b/autoparallel/cost_models/compute_estimation.py index fb0b4f73..e05ca6b2 100644 --- a/autoparallel/cost_models/compute_estimation.py +++ b/autoparallel/cost_models/compute_estimation.py @@ -9,10 +9,15 @@ import torch from torch._subclasses.fake_tensor import unset_fake_temporarily +from torch.distributed.tensor._dtensor_spec import DTensorSpec +from torch.distributed.tensor._utils import compute_local_stride from torch.utils._mode_utils import no_dispatch from torch.utils._pytree import tree_flatten, tree_map_only from torch.utils.flop_counter import FlopCounterMode, register_flop_formula +from autoparallel.shardings.dtensor_sharding_helpers import ( + get_shape_and_stride_arg_indices, +) from autoparallel.shardings.propagation_rules import _SHAPE_FACTORY_OPS _cost_model_device_name: str | None = None @@ -493,6 +498,25 @@ def _shard_args_for_node(node, strategy=None, rand_init=False): counter += 1 new_flat_args.append(x) args = treespec.unflatten(new_flat_args) + + # Ops that take their global output size as an argument would otherwise + # be run on the sharded inputs with the global size. + indices = get_shape_and_stride_arg_indices(node.target) + output_spec = strategy.output_specs + if ( + indices is not None + and isinstance(output_spec, DTensorSpec) + and any(p.is_shard() for p in output_spec.placements) + ): + shape_idx, stride_idx = indices + sizes, _ = _get_sharded_shape_stride(output_spec) + args = list(args) + args[shape_idx] = sizes + if stride_idx is not None: + args[stride_idx] = list( + compute_local_stride(output_spec.tensor_meta.stride, sizes) + ) + args = tuple(args) return args, kwargs diff --git a/autoparallel/shardings/dtensor_sharding_helpers.py b/autoparallel/shardings/dtensor_sharding_helpers.py index b2ec50de..eda22eb4 100644 --- a/autoparallel/shardings/dtensor_sharding_helpers.py +++ b/autoparallel/shardings/dtensor_sharding_helpers.py @@ -48,6 +48,27 @@ replicate_op_strategy = torch.distributed.tensor._ops.utils.replicate_op_strategy +def get_shape_and_stride_arg_indices( + op, +) -> Optional[tuple[int, Optional[int]]]: + """Return the positions of ``op``'s global output size and stride args. + + Some ops take the size of their output as an argument, such as + ``slice_backward``'s ``input_sizes``, the upsample backward ops' + ``input_size`` and ``new_empty_strided``'s ``size`` and ``stride``. When + such an op's output is sharded, DTensor rewrites these arguments from the + global to the local output (``ShardingPropagator._adjust_shape_and_stride_args``). + AutoParallel runs ops on local tensors without DTensor's dispatch, so it + has to apply the same rewrite. Returns ``(shape_idx, stride_idx)``, with + ``stride_idx`` ``None`` for ops without a stride argument, or ``None`` for + ops DTensor does not rewrite. + """ + idx = propagator.op_to_shape_and_stride_idx.get(op) + if idx is None or isinstance(idx, tuple): + return idx + return idx, None + + # TODO: remove and refer to # https://github.com/pytorch/pytorch/blob/9c107606629de6383f55e3b48b42e594d23407b1/test/distributed/tensor/test_op_strategy.py#L446 # once the function is moved outside of the test folder in upstream diff --git a/tests/test_apply_sharding.py b/tests/test_apply_sharding.py index 30d4220d..153e4dcb 100644 --- a/tests/test_apply_sharding.py +++ b/tests/test_apply_sharding.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 pytest import torch from torch.distributed.device_mesh import DeviceMesh from torch.distributed.tensor._dtensor_spec import ( @@ -17,6 +18,8 @@ from autoparallel.apply_sharding import _compute_shard_order, _lower_to_parallel_graph from autoparallel.shardings.ordered_sharding import ordered_redistribute_local_tensor +aten = torch.ops.aten + class TestComputeShardOrder: def test_sorted_order(self): @@ -219,6 +222,53 @@ def chain(x): torch.testing.assert_close(local_tensor.grad, reference_input.grad[:2]) +@pytest.mark.parametrize( + "op,input_shape,args", + [ + (aten.slice_backward.default, (4, 3), ([4, 6], 1, 0, 3, 1)), + (aten.select_backward.default, (4,), ([4, 5], 1, 2)), + ( + aten._upsample_bilinear2d_aa_backward.default, + (4, 3, 2, 2), + ([2, 2], [4, 3, 4, 4], False, None, None), + ), + ], +) +def test_static_shape_arg_is_localized_for_sharded_output(op, input_shape, args): + # These ops take their global output size as an argument; lowered on a + # Shard(0) local tensor, they must produce the local output. + def chain(x): + return op(x, *args) + + reference_input = torch.randn(input_shape) + reference_output = chain(reference_input) + + gm = make_fx(chain)(reference_input) + placements = _shard0_placements(gm) + local_tensor = reference_input[:2].clone() + parallel_gm = _lower_to_parallel_graph( + gm, placements, [local_tensor], param_placement_order={} + ) + + torch.testing.assert_close(parallel_gm(local_tensor), reference_output[:2]) + + +def test_static_new_empty_strided_is_localized_for_sharded_output(): + def chain(x): + return x.new_empty_strided((4, 3), (1, 4)).fill_(1.0) + + gm = make_fx(chain)(torch.randn(4, 3)) + placements = _shard0_placements(gm) + local_tensor = torch.randn(2, 3) + parallel_gm = _lower_to_parallel_graph( + gm, placements, [local_tensor], param_placement_order={} + ) + actual = parallel_gm(local_tensor) + + torch.testing.assert_close(actual, torch.ones(2, 3)) + assert actual.stride() == (1, 2) + + class TestOrderedRedistributeFusion: """Test that ordered_redistribute_local_tensor fuses multi-dim collectives into single flat-mesh operations when possible.""" diff --git a/tests/test_compute_estimation.py b/tests/test_compute_estimation.py index 572c6091..68990e74 100644 --- a/tests/test_compute_estimation.py +++ b/tests/test_compute_estimation.py @@ -108,6 +108,59 @@ def cost(placement): assert cost(Shard(0)) < cost(Replicate()) +@pytest.mark.parametrize( + "op,make_args,grad_shape,output_shape", + [ + ( + torch.ops.aten.slice_backward.default, + lambda grad, size: (grad, size, 1, 0, 2048, 1), + [4096, 2048], + [4096, 4096], + ), + ( + torch.ops.aten._upsample_bilinear2d_aa_backward.default, + lambda grad, size: (grad, [64, 64], size, False, None, None), + [512, 16, 64, 64], + [512, 16, 128, 128], + ), + ], +) +def test_sharded_output_size_arg_is_priced_at_local_size( + monkeypatch, op, make_args, grad_shape, output_shape +): + # slice_backward's input_sizes and upsample backward's input_size are the + # global output size: a Shard(0) strategy must run the op at local size. + h100 = next(limit for limit in DEVICE_LIMITS if limit.name == "H100") + monkeypatch.setattr(compute_estimation, "_get_device_limit", lambda: h100) + + def node(grad_shape, output_shape): + graph = torch.fx.Graph() + grad = graph.placeholder("grad") + grad.meta["val"] = torch.empty(grad_shape, device="meta") + out = graph.call_function(op, make_args(grad, output_shape)) + out.meta["val"] = torch.empty(output_shape, device="meta") + return out + + mesh = DeviceMesh("cpu", list(range(8)), _init_backend=False) + + def shard0(shape): + stride = torch.empty(shape, device="meta").stride() + tensor_meta = TensorMeta(torch.Size(shape), stride, torch.float32) + return DTensorSpec(mesh, (Shard(0),), tensor_meta=tensor_meta) + + strategy = OpSpec( + output_specs=shard0(output_shape), input_specs=[shard0(grad_shape)] + ) + local_grad_shape = [grad_shape[0] // 8, *grad_shape[1:]] + local_output_shape = [output_shape[0] // 8, *output_shape[1:]] + + assert estimate_strategy_runtime_cost( + node(grad_shape, output_shape), strategy + ) == estimate_strategy_runtime_cost( + node(local_grad_shape, local_output_shape), None + ) + + def _metadata_only_cost_nodes(): shape = [4096, 16384] graph = torch.fx.Graph()