|
| 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, Optional, Tuple |
| 12 | + |
| 13 | +import torch |
| 14 | + |
| 15 | +from executorch.exir import memory |
| 16 | +from executorch.exir.dialects._ops import ops |
| 17 | +from executorch.exir.memory_planning import is_op_memory_planned |
| 18 | +from executorch.exir.tensor import ( |
| 19 | + contiguous_stride_from_shape, |
| 20 | + determine_tensor_dynanism, |
| 21 | + dim_order_from_stride, |
| 22 | + TensorShapeDynamism, |
| 23 | + TensorSpec, |
| 24 | +) |
| 25 | +from torch.export.exported_program import ExportedProgram |
| 26 | +from torch.fx.passes.infra.pass_base import PassBase, PassResult |
| 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 | +class _MemoryViewSpec(TensorSpec): |
| 37 | + def __init__(self, base: TensorSpec, shape: List[int]) -> None: |
| 38 | + """ |
| 39 | + A MemoryViewSpec is an immutable TensorSpec that mirrors its base for non-size |
| 40 | + related information. |
| 41 | + """ |
| 42 | + |
| 43 | + if math.prod(base.shape) != math.prod(shape): |
| 44 | + raise Exception( |
| 45 | + f"Cannot create a MemoryViewSpec because the provided shape {shape} is not consistent with the number of elements in the provided base ({math.prod(base.shape)})." |
| 46 | + ) |
| 47 | + |
| 48 | + if not base.is_static_shape_tensor: |
| 49 | + raise Exception( |
| 50 | + "Cannot create a MemoryViewSpec because the provided base is not a static shape tensor." |
| 51 | + ) |
| 52 | + |
| 53 | + self._init_setters = [ |
| 54 | + "_frozen", |
| 55 | + "_base", |
| 56 | + "_guards", |
| 57 | + "shape", |
| 58 | + "stride", |
| 59 | + "dim_order", |
| 60 | + "shape_dynamism", |
| 61 | + ] |
| 62 | + self._frozen = False |
| 63 | + self._base = base |
| 64 | + self.shape: List[int] = shape |
| 65 | + self.stride: Tuple[int] = contiguous_stride_from_shape(torch.Size(self.shape)) |
| 66 | + self.dim_order: Tuple[bytes] = dim_order_from_stride(self.stride) |
| 67 | + self.shape_dynamism: TensorShapeDynamism = determine_tensor_dynanism( |
| 68 | + torch.Size(self.shape) |
| 69 | + ) |
| 70 | + |
| 71 | + # This spec gives a view into its base. |
| 72 | + # The base can be modified (e.g., mem_id) and this spec will |
| 73 | + # update accordingly, but certain fields we do not expect to change |
| 74 | + # We create guards for these |
| 75 | + self._guards: Dict[str, Any] = { |
| 76 | + "shape_dynamism": base.shape_dynamism, |
| 77 | + "scalar_type": base.scalar_type, |
| 78 | + "layout": base.layout, |
| 79 | + "is_sparse": base.is_sparse, |
| 80 | + } |
| 81 | + self._frozen = True |
| 82 | + |
| 83 | + def _check_guards(self) -> None: |
| 84 | + for name in self._guards: |
| 85 | + if getattr(self._base, name) != self._guards[name]: |
| 86 | + raise Exception( |
| 87 | + f"The guarded attribute '{name}' has changed value. At creation of the MemoryViewSpec, it was {self._guards[name]}, but it is now {getattr(self._base, name)}." |
| 88 | + ) |
| 89 | + |
| 90 | + def __getattribute__(self, name): # pyre-ignore |
| 91 | + if name in [ |
| 92 | + "_init_setters", |
| 93 | + "_frozen", |
| 94 | + "_base", |
| 95 | + "_guards", |
| 96 | + "_check_guards", |
| 97 | + # Adding debug is needed so that view_spec.debug() shows the right id in |
| 98 | + # its string (if debug is excluded, it shows the id(view_spec._base) instead |
| 99 | + # of id(view_spec)) |
| 100 | + "debug", |
| 101 | + ]: |
| 102 | + return object.__getattribute__(self, name) |
| 103 | + |
| 104 | + # Guard check after freeze |
| 105 | + if self._frozen: |
| 106 | + self._check_guards() |
| 107 | + |
| 108 | + # self._init_setters attributes come from self, others come from base |
| 109 | + if name in self._init_setters: |
| 110 | + return object.__getattribute__(self, name) |
| 111 | + return getattr(self._base, name) |
| 112 | + |
| 113 | + def __setattr__(self, name: str, val) -> None: # pyre-ignore |
| 114 | + if name in ["_init_setters", "_frozen"]: |
| 115 | + object.__setattr__(self, name, val) |
| 116 | + return |
| 117 | + |
| 118 | + # Allow setting during initialization |
| 119 | + if name in self._init_setters and not self._frozen: |
| 120 | + object.__setattr__(self, name, val) |
| 121 | + return |
| 122 | + |
| 123 | + if name in self._init_setters: |
| 124 | + raise Exception( |
| 125 | + f"MemoryViewSpec is immutable. Cannot set the attribute '{name}' after creation." |
| 126 | + ) |
| 127 | + |
| 128 | + raise Exception( |
| 129 | + f"MemoryViewSpec is immutable. To update the non-size related attribute '{name}', update the base." |
| 130 | + ) |
| 131 | + |
| 132 | + |
| 133 | +class ReplaceViewCopyWithMemoryViewPass(PassBase): |
| 134 | + def __init__(self) -> None: |
| 135 | + super().__init__() |
| 136 | + self._program: Optional[ExportedProgram] = None |
| 137 | + |
| 138 | + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: |
| 139 | + """ |
| 140 | + This pass replaces all static, memory-planned view_copy nodes with special |
| 141 | + memory.view nodes. |
| 142 | +
|
| 143 | + This should be run after the NormalizeViewCopyBasePass. |
| 144 | +
|
| 145 | + During memory planning, memory.view nodes share the same storage as their base. |
| 146 | +
|
| 147 | + During emission, memory.view nodes are not emitted as operators, but are instead |
| 148 | + directly emitted as evalues. They share the same allocation_info/storage as their |
| 149 | + base. |
| 150 | + """ |
| 151 | + |
| 152 | + n_replaced = 0 |
| 153 | + for module in graph_module.modules(): |
| 154 | + if not isinstance(module, torch.fx.GraphModule): |
| 155 | + continue |
| 156 | + for node in module.graph.nodes: |
| 157 | + if self._is_replaceable_view_copy(node): |
| 158 | + base, shape = node.args |
| 159 | + node.target = memory.view |
| 160 | + |
| 161 | + # Create spec for the node. |
| 162 | + # _MemoryViewSpec is an immutable TensorSpec gives a view into |
| 163 | + # its base spec for non-size related information. |
| 164 | + node.meta["spec"] = _MemoryViewSpec(base.meta["spec"], shape) |
| 165 | + |
| 166 | + n_replaced += 1 |
| 167 | + |
| 168 | + module.recompile() |
| 169 | + |
| 170 | + logging.debug(f"Replaced {n_replaced} view_copy nodes with memory.view nodes.") |
| 171 | + return PassResult(graph_module, n_replaced > 0) |
| 172 | + |
| 173 | + def ensures(self, graph_module: torch.fx.GraphModule) -> None: |
| 174 | + for module in graph_module.modules(): |
| 175 | + if not isinstance(module, torch.fx.GraphModule): |
| 176 | + continue |
| 177 | + for node in module.graph.nodes: |
| 178 | + assert not self._is_replaceable_view_copy(node) |
| 179 | + if node.op == "call_function" and node.target == memory.view: |
| 180 | + assert isinstance(node.meta["spec"], _MemoryViewSpec) |
| 181 | + |
| 182 | + def requires(self, graph_module: torch.fx.GraphModule) -> None: |
| 183 | + """ |
| 184 | + This pass should be called after NormalizeViewCopyBasePass. |
| 185 | + We check that all view_copy nodes have been normalized. |
| 186 | + """ |
| 187 | + for module in graph_module.modules(): |
| 188 | + if not isinstance(module, torch.fx.GraphModule): |
| 189 | + continue |
| 190 | + for node in module.graph.nodes: |
| 191 | + if _is_view_copy(node): |
| 192 | + base, size = node.args |
| 193 | + assert not _is_view_copy(base) |
| 194 | + |
| 195 | + def set_program(self, program: ExportedProgram) -> None: |
| 196 | + self._program = program |
| 197 | + |
| 198 | + def _is_replaceable_view_copy(self, node: torch.fx.Node) -> bool: |
| 199 | + if not _is_view_copy(node): |
| 200 | + return False |
| 201 | + |
| 202 | + base = node.args[0] |
| 203 | + assert isinstance(base, torch.fx.Node) |
| 204 | + |
| 205 | + is_base_memory_planned = False # until proven otherwise |
| 206 | + if base.op == "call_function": |
| 207 | + is_base_memory_planned = is_op_memory_planned(base) |
| 208 | + |
| 209 | + if base.op == "placeholder": |
| 210 | + # For now, we only assume placeholder parameters are memory planned. |
| 211 | + # We cautiously assume that general user inputs and buffers are not memory planned. |
| 212 | + # Memory planning for user inputs can be turned off, see |
| 213 | + # https://github.com/pytorch/executorch/blob/main/exir/passes/memory_planning_pass.py#L32 |
| 214 | + assert isinstance(self._program, ExportedProgram) |
| 215 | + if base.name in self._program.graph_signature.inputs_to_parameters: |
| 216 | + is_base_memory_planned = True |
| 217 | + |
| 218 | + return is_base_memory_planned and node.meta["spec"].is_static_shape_tensor |
0 commit comments