|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +# pyre-strict |
| 8 | + |
| 9 | +import logging |
| 10 | +import math |
| 11 | +from typing import Any, Dict, List, Tuple |
| 12 | + |
| 13 | +import torch |
| 14 | +from executorch.exir import memory |
| 15 | + |
| 16 | +from executorch.exir.dialects._ops import ops |
| 17 | +from executorch.exir.tensor import ( |
| 18 | + contiguous_stride_from_shape, |
| 19 | + determine_tensor_dynanism, |
| 20 | + dim_order_from_stride, |
| 21 | + TensorShapeDynamism, |
| 22 | + TensorSpec, |
| 23 | +) |
| 24 | +from torch.fx.passes.infra.pass_base import PassBase, PassResult |
| 25 | + |
| 26 | +logger: logging.Logger = logging.getLogger(__name__) |
| 27 | + |
| 28 | + |
| 29 | +def _is_view_copy(node: torch.fx.Node) -> bool: |
| 30 | + return node.op == "call_function" and node.target in ( |
| 31 | + torch.ops.aten.view_copy.default, |
| 32 | + ops.edge.aten.view_copy.default, |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | +_VIEW_OP = memory.view |
| 37 | + |
| 38 | + |
| 39 | +class _ViewSpec(TensorSpec): |
| 40 | + def __init__(self, base: TensorSpec, shape: List[int]) -> None: |
| 41 | + """ |
| 42 | + A ViewSpec is an immutable TensorSpec that mirrors its base for non-size |
| 43 | + related information. |
| 44 | + """ |
| 45 | + |
| 46 | + if math.prod(base.shape) != math.prod(shape): |
| 47 | + raise Exception( |
| 48 | + f"Cannot create a ViewSpec because the provided shape {shape} is not consistent with the number of elements in the provided base ({math.prod(base.shape)})." |
| 49 | + ) |
| 50 | + |
| 51 | + self._init_setters = [ |
| 52 | + "_frozen", |
| 53 | + "_base", |
| 54 | + "_guards", |
| 55 | + "shape", |
| 56 | + "stride", |
| 57 | + "dim_order", |
| 58 | + "shape_dynamism", |
| 59 | + ] |
| 60 | + self._frozen = False |
| 61 | + self._base = base |
| 62 | + self.shape: List[int] = shape |
| 63 | + self.stride: Tuple[int] = contiguous_stride_from_shape(torch.Size(self.shape)) |
| 64 | + self.dim_order: Tuple[bytes] = dim_order_from_stride(self.stride) |
| 65 | + self.shape_dynamism: TensorShapeDynamism = determine_tensor_dynanism( |
| 66 | + torch.Size(self.shape) |
| 67 | + ) |
| 68 | + |
| 69 | + # This spec gives a view into its base. |
| 70 | + # The base can be modified (e.g., mem_id) and this spec will |
| 71 | + # update accordingly, but certain fields we do not expect to change |
| 72 | + # We create guards for these |
| 73 | + self._guards: Dict[str, Any] = { |
| 74 | + "shape_dynamism": base.shape_dynamism, |
| 75 | + "scalar_type": base.scalar_type, |
| 76 | + "layout": base.layout, |
| 77 | + "is_sparse": base.is_sparse, |
| 78 | + } |
| 79 | + self._frozen = True |
| 80 | + |
| 81 | + def _check_guards(self) -> None: |
| 82 | + for name in self._guards: |
| 83 | + if getattr(self._base, name) != self._guards[name]: |
| 84 | + raise Exception( |
| 85 | + f"The guarded attribute '{name}' has changed value. At creation of the ViewSpec, it was {self._guards[name]}, but it is now {getattr(self._base, name)}." |
| 86 | + ) |
| 87 | + |
| 88 | + def __getattribute__(self, name): # pyre-ignore |
| 89 | + if name in [ |
| 90 | + "_init_setters", |
| 91 | + "_frozen", |
| 92 | + "_base", |
| 93 | + "_guards", |
| 94 | + "_check_guards", |
| 95 | + # Adding debug is needed so that view_spec.debug() shows the right id in |
| 96 | + # its string (if debug is excluded, it shows the id(view_spec._base) instead |
| 97 | + # of id(view_spec)) |
| 98 | + "debug", |
| 99 | + ]: |
| 100 | + return object.__getattribute__(self, name) |
| 101 | + |
| 102 | + # Guard check after freeze |
| 103 | + if self._frozen: |
| 104 | + self._check_guards() |
| 105 | + |
| 106 | + # self._init_setters attributes come from self, others come from base |
| 107 | + if name in self._init_setters: |
| 108 | + return object.__getattribute__(self, name) |
| 109 | + return getattr(self._base, name) |
| 110 | + |
| 111 | + def __setattr__(self, name: str, val) -> None: # pyre-ignore |
| 112 | + if name in ["_init_setters", "_frozen"]: |
| 113 | + object.__setattr__(self, name, val) |
| 114 | + return |
| 115 | + |
| 116 | + # Allow setting during initialization |
| 117 | + if name in self._init_setters and not self._frozen: |
| 118 | + object.__setattr__(self, name, val) |
| 119 | + return |
| 120 | + |
| 121 | + if name in self._init_setters: |
| 122 | + raise Exception( |
| 123 | + f"ViewSpec is immutable. Cannot set the attribute '{name}' after creation." |
| 124 | + ) |
| 125 | + |
| 126 | + raise Exception( |
| 127 | + f"ViewSpec is immutable. To update the non-size related attribute '{name}', update the base." |
| 128 | + ) |
| 129 | + |
| 130 | + |
| 131 | +class ReplaceViewCopyWithViewPass(PassBase): |
| 132 | + def __init__(self) -> None: |
| 133 | + super().__init__() |
| 134 | + |
| 135 | + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: |
| 136 | + """ |
| 137 | + This pass replaces view_copy nodes with view nodes. |
| 138 | +
|
| 139 | + This should be run after the NormalizeViewCopyBasePass. |
| 140 | +
|
| 141 | + During memory planning, view nodes share the same storage as their base. |
| 142 | + """ |
| 143 | + |
| 144 | + n_replaced = 0 |
| 145 | + for module in graph_module.modules(): |
| 146 | + if not isinstance(module, torch.fx.GraphModule): |
| 147 | + continue |
| 148 | + for node in module.graph.nodes: |
| 149 | + if _is_view_copy(node): |
| 150 | + base, _ = node.args |
| 151 | + node.target = _VIEW_OP |
| 152 | + |
| 153 | + # Create spec for the node. |
| 154 | + # _ViewSpec is an immutable TensorSpec gives a view into |
| 155 | + # its base spec for non-size related information. |
| 156 | + |
| 157 | + # the shape is not the same as node.args[1] because node.args[1] |
| 158 | + # can have an inferred sizes (-1). |
| 159 | + shape = node.meta["val"].shape |
| 160 | + node.meta["spec"] = _ViewSpec(base.meta["spec"], shape) |
| 161 | + |
| 162 | + n_replaced += 1 |
| 163 | + |
| 164 | + module.recompile() |
| 165 | + |
| 166 | + logger.debug(f"Replaced {n_replaced} view_copy nodes with {_VIEW_OP} nodes.") |
| 167 | + return PassResult(graph_module, n_replaced > 0) |
| 168 | + |
| 169 | + def ensures(self, graph_module: torch.fx.GraphModule) -> None: |
| 170 | + for module in graph_module.modules(): |
| 171 | + if not isinstance(module, torch.fx.GraphModule): |
| 172 | + continue |
| 173 | + for node in module.graph.nodes: |
| 174 | + assert not _is_view_copy(node) |
| 175 | + if node.op == "call_function" and node.target == _VIEW_OP: |
| 176 | + assert isinstance(node.meta["spec"], _ViewSpec) |
| 177 | + |
| 178 | + def requires(self, graph_module: torch.fx.GraphModule) -> None: |
| 179 | + """ |
| 180 | + This pass should be called after NormalizeViewCopyBasePass. |
| 181 | + We check that all view_copy nodes have been normalized. |
| 182 | + """ |
| 183 | + for module in graph_module.modules(): |
| 184 | + if not isinstance(module, torch.fx.GraphModule): |
| 185 | + continue |
| 186 | + for node in module.graph.nodes: |
| 187 | + if _is_view_copy(node): |
| 188 | + base, size = node.args |
| 189 | + assert not _is_view_copy(base) |
0 commit comments