Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions autoparallel/apply_sharding.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.).
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand Down
33 changes: 33 additions & 0 deletions autoparallel/cost_models/compute_estimation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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

Expand Down
14 changes: 12 additions & 2 deletions autoparallel/graph_passes/graph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
12 changes: 11 additions & 1 deletion autoparallel/optimize_sharding.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading