|
| 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 unittest |
| 10 | + |
| 11 | +import torch |
| 12 | +import torch.nn as nn |
| 13 | +import torchao |
| 14 | +from executorch.backends.cadence.aot.remove_ops import RemoveBNTrackingMutationsPass |
| 15 | +from executorch.exir import to_edge |
| 16 | +from torch.export.graph_signature import InputKind, OutputKind |
| 17 | +from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e |
| 18 | + |
| 19 | + |
| 20 | +class SimpleBNModel(nn.Module): |
| 21 | + def __init__(self) -> None: |
| 22 | + super().__init__() |
| 23 | + self.conv = nn.Conv1d(3, 8, kernel_size=3, padding=1) |
| 24 | + self.bn = nn.BatchNorm1d(8) |
| 25 | + |
| 26 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 27 | + return torch.relu(self.bn(self.conv(x))) |
| 28 | + |
| 29 | + |
| 30 | +class MultiBNModel(nn.Module): |
| 31 | + def __init__(self) -> None: |
| 32 | + super().__init__() |
| 33 | + self.conv1 = nn.Conv1d(3, 8, kernel_size=3, padding=1) |
| 34 | + self.bn1 = nn.BatchNorm1d(8) |
| 35 | + self.conv2 = nn.Conv1d(8, 16, kernel_size=3, padding=1) |
| 36 | + self.bn2 = nn.BatchNorm1d(16) |
| 37 | + self.fc = nn.Linear(16, 4) |
| 38 | + |
| 39 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 40 | + x = torch.relu(self.bn1(self.conv1(x))) |
| 41 | + x = torch.relu(self.bn2(self.conv2(x))) |
| 42 | + x = x.mean(dim=-1) |
| 43 | + return self.fc(x) |
| 44 | + |
| 45 | + |
| 46 | +class ReadBNTrackingModel(nn.Module): |
| 47 | + def __init__(self) -> None: |
| 48 | + super().__init__() |
| 49 | + self.bn = nn.BatchNorm1d(3) |
| 50 | + |
| 51 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 52 | + num_batches_tracked = self.bn.num_batches_tracked |
| 53 | + assert num_batches_tracked is not None |
| 54 | + return self.bn(x) + num_batches_tracked.to(dtype=x.dtype) |
| 55 | + |
| 56 | + |
| 57 | +def _qat_export_to_edge( |
| 58 | + model: nn.Module, |
| 59 | + example_input: tuple[torch.Tensor, ...], |
| 60 | +) -> torch.export.ExportedProgram: |
| 61 | + """Simulate the QAT export path that produces BN tracking mutations. |
| 62 | +
|
| 63 | + QAT models are traced in training mode (model.train()), then converted |
| 64 | + back to eval via move_exported_model_to_eval(). run_decompositions() |
| 65 | + in to_edge() then re-introduces num_batches_tracked mutations. |
| 66 | + """ |
| 67 | + from executorch.backends.cadence.aot.quantizer.quantizer import ( |
| 68 | + CadenceFusedConvReluQuantizer, |
| 69 | + ) |
| 70 | + |
| 71 | + model.train() |
| 72 | + captured = torch.export.export(model, example_input, strict=False).module() |
| 73 | + prepared = prepare_pt2e(captured, CadenceFusedConvReluQuantizer(is_qat=True)) |
| 74 | + |
| 75 | + for _ in range(3): |
| 76 | + prepared(*example_input) |
| 77 | + |
| 78 | + torchao.quantization.pt2e.move_exported_model_to_eval(prepared) |
| 79 | + converted = convert_pt2e(prepared) |
| 80 | + |
| 81 | + exported = torch.export.export(converted, example_input) |
| 82 | + edge = to_edge(exported) |
| 83 | + return edge.exported_program() |
| 84 | + |
| 85 | + |
| 86 | +class RemoveBNTrackingMutationsTest(unittest.TestCase): |
| 87 | + def _get_nbt_mutations(self, ep: torch.export.ExportedProgram) -> dict[str, str]: |
| 88 | + return { |
| 89 | + k: v |
| 90 | + for k, v in ep.graph_signature.buffers_to_mutate.items() |
| 91 | + if "num_batches_tracked" in v |
| 92 | + } |
| 93 | + |
| 94 | + def _get_nbt_placeholders(self, ep: torch.export.ExportedProgram) -> list[str]: |
| 95 | + placeholders: list[str] = [] |
| 96 | + for n in ep.graph_module.graph.nodes: |
| 97 | + if ( |
| 98 | + n.op == "placeholder" |
| 99 | + and isinstance(n.target, str) |
| 100 | + and "num_batches_tracked" in n.target |
| 101 | + ): |
| 102 | + placeholders.append(n.target) |
| 103 | + return placeholders |
| 104 | + |
| 105 | + def _get_nbt_input_specs(self, ep: torch.export.ExportedProgram) -> list[str]: |
| 106 | + input_specs: list[str] = [] |
| 107 | + for s in ep.graph_signature.input_specs: |
| 108 | + if ( |
| 109 | + s.kind == InputKind.BUFFER |
| 110 | + and s.target is not None |
| 111 | + and "num_batches_tracked" in s.target |
| 112 | + ): |
| 113 | + input_specs.append(s.target) |
| 114 | + return input_specs |
| 115 | + |
| 116 | + def _run_remove_pass_on_qat_model( |
| 117 | + self, |
| 118 | + model: nn.Module, |
| 119 | + example_input: tuple[torch.Tensor, ...], |
| 120 | + ) -> torch.export.ExportedProgram: |
| 121 | + edge_ep = _qat_export_to_edge(model, example_input) |
| 122 | + nbt = self._get_nbt_mutations(edge_ep) |
| 123 | + self.assertGreater( |
| 124 | + len(nbt), 0, "expected pre-pass num_batches_tracked mutations" |
| 125 | + ) |
| 126 | + |
| 127 | + result = RemoveBNTrackingMutationsPass()(edge_ep) |
| 128 | + self.assertTrue(result.modified) |
| 129 | + return result.exported_program |
| 130 | + |
| 131 | + def test_single_bn_no_tracking_mutations(self) -> None: |
| 132 | + model = SimpleBNModel() |
| 133 | + edge_ep = self._run_remove_pass_on_qat_model(model, (torch.randn(1, 3, 32),)) |
| 134 | + nbt = self._get_nbt_mutations(edge_ep) |
| 135 | + self.assertEqual(len(nbt), 0, f"num_batches_tracked mutations present: {nbt}") |
| 136 | + |
| 137 | + def test_multi_bn_no_tracking_mutations(self) -> None: |
| 138 | + model = MultiBNModel() |
| 139 | + edge_ep = self._run_remove_pass_on_qat_model(model, (torch.randn(1, 3, 32),)) |
| 140 | + nbt = self._get_nbt_mutations(edge_ep) |
| 141 | + self.assertEqual(len(nbt), 0, f"num_batches_tracked mutations present: {nbt}") |
| 142 | + |
| 143 | + def test_no_nbt_output_specs(self) -> None: |
| 144 | + model = MultiBNModel() |
| 145 | + edge_ep = self._run_remove_pass_on_qat_model(model, (torch.randn(1, 3, 32),)) |
| 146 | + nbt_specs = [ |
| 147 | + s |
| 148 | + for s in edge_ep.graph_signature.output_specs |
| 149 | + if s.kind == OutputKind.BUFFER_MUTATION |
| 150 | + and s.target is not None |
| 151 | + and "num_batches_tracked" in s.target |
| 152 | + ] |
| 153 | + self.assertEqual( |
| 154 | + len(nbt_specs), 0, f"num_batches_tracked output specs present: {nbt_specs}" |
| 155 | + ) |
| 156 | + |
| 157 | + def test_no_nbt_input_placeholders(self) -> None: |
| 158 | + """All num_batches_tracked input placeholders should be removed.""" |
| 159 | + model = MultiBNModel() |
| 160 | + edge_ep = self._run_remove_pass_on_qat_model(model, (torch.randn(1, 3, 32),)) |
| 161 | + nbt_placeholders = self._get_nbt_placeholders(edge_ep) |
| 162 | + self.assertEqual( |
| 163 | + len(nbt_placeholders), |
| 164 | + 0, |
| 165 | + f"num_batches_tracked placeholders still present: {nbt_placeholders}", |
| 166 | + ) |
| 167 | + |
| 168 | + def test_no_nbt_input_specs(self) -> None: |
| 169 | + """No input_specs for num_batches_tracked buffers should remain.""" |
| 170 | + model = MultiBNModel() |
| 171 | + edge_ep = self._run_remove_pass_on_qat_model(model, (torch.randn(1, 3, 32),)) |
| 172 | + nbt_input_specs = self._get_nbt_input_specs(edge_ep) |
| 173 | + self.assertEqual( |
| 174 | + len(nbt_input_specs), |
| 175 | + 0, |
| 176 | + f"num_batches_tracked input specs still present: {nbt_input_specs}", |
| 177 | + ) |
| 178 | + |
| 179 | + def test_live_nbt_input_spec_preserved(self) -> None: |
| 180 | + model = ReadBNTrackingModel() |
| 181 | + edge_ep = self._run_remove_pass_on_qat_model(model, (torch.randn(1, 3, 32),)) |
| 182 | + |
| 183 | + nbt_placeholders = self._get_nbt_placeholders(edge_ep) |
| 184 | + nbt_input_specs = self._get_nbt_input_specs(edge_ep) |
| 185 | + self.assertGreater( |
| 186 | + len(nbt_placeholders), |
| 187 | + 0, |
| 188 | + "expected live num_batches_tracked placeholder to remain", |
| 189 | + ) |
| 190 | + self.assertEqual(len(nbt_placeholders), len(nbt_input_specs)) |
| 191 | + |
| 192 | + def test_no_bn_model_unaffected(self) -> None: |
| 193 | + class NoBNModel(nn.Module): |
| 194 | + def __init__(self) -> None: |
| 195 | + super().__init__() |
| 196 | + self.linear = nn.Linear(8, 4) |
| 197 | + |
| 198 | + def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 199 | + return self.linear(x) |
| 200 | + |
| 201 | + model = NoBNModel() |
| 202 | + model.eval() |
| 203 | + ep = torch.export.export(model, (torch.randn(1, 8),)) |
| 204 | + edge_ep = to_edge(ep).exported_program() |
| 205 | + result = RemoveBNTrackingMutationsPass()(edge_ep) |
| 206 | + self.assertFalse(result.modified) |
| 207 | + self.assertEqual( |
| 208 | + len(result.exported_program.graph_signature.buffers_to_mutate), 0 |
| 209 | + ) |
0 commit comments