|
| 1 | +# Copyright 2026 Arm Limited and/or its affiliates. |
| 2 | +# |
| 3 | +# This source code is licensed under the BSD-style license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | + |
| 6 | +import copy |
| 7 | +from dataclasses import dataclass |
| 8 | +from typing import Callable |
| 9 | + |
| 10 | +import pytest |
| 11 | +import torch |
| 12 | +import torch.nn.functional as F |
| 13 | +from executorch.backends.arm.quantizer import ( |
| 14 | + get_symmetric_quantization_config, |
| 15 | + TOSAQuantizer, |
| 16 | +) |
| 17 | +from executorch.backends.arm.tosa import TosaSpecification |
| 18 | +from executorch.exir.passes import ToDevicePass |
| 19 | +from torch._subclasses.fake_tensor import FakeTensor |
| 20 | +from torchao.quantization.pt2e import move_exported_model_to_eval |
| 21 | +from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_qat_pt2e |
| 22 | + |
| 23 | + |
| 24 | +class AddAlpha(torch.nn.Module): |
| 25 | + def forward(self, x, y): |
| 26 | + return torch.add(x, y, alpha=2.0) |
| 27 | + |
| 28 | + |
| 29 | +class SubAlpha(torch.nn.Module): |
| 30 | + def forward(self, x, y): |
| 31 | + return torch.sub(x, y, alpha=2.0) |
| 32 | + |
| 33 | + |
| 34 | +class SliceScatter(torch.nn.Module): |
| 35 | + def forward(self, x, src): |
| 36 | + return torch.slice_scatter(x, src, dim=1, start=0, end=4, step=2) |
| 37 | + |
| 38 | + |
| 39 | +class MeanDim(torch.nn.Module): |
| 40 | + def forward(self, x): |
| 41 | + return torch.mean(x, dim=(1,), keepdim=True) |
| 42 | + |
| 43 | + |
| 44 | +class MeanDefault(torch.nn.Module): |
| 45 | + def forward(self, x): |
| 46 | + return torch.mean(x) |
| 47 | + |
| 48 | + |
| 49 | +class VarCorrection(torch.nn.Module): |
| 50 | + def forward(self, x): |
| 51 | + return torch.var(x, dim=(2, 3), correction=1, keepdim=True) |
| 52 | + |
| 53 | + |
| 54 | +class VarDim(torch.nn.Module): |
| 55 | + def forward(self, x): |
| 56 | + return torch.ops.aten.var.dim(x, [2, 3], 1, True) |
| 57 | + |
| 58 | + |
| 59 | +class DivTensorMode(torch.nn.Module): |
| 60 | + def forward(self, x, y): |
| 61 | + return torch.div(x, y, rounding_mode="trunc") |
| 62 | + |
| 63 | + |
| 64 | +class LeakyRelu(torch.nn.Module): |
| 65 | + def forward(self, x): |
| 66 | + return F.leaky_relu(x, negative_slope=0.2) |
| 67 | + |
| 68 | + |
| 69 | +class AvgPool2d(torch.nn.Module): |
| 70 | + def forward(self, x): |
| 71 | + return F.avg_pool2d(x, kernel_size=2, stride=1, padding=1) |
| 72 | + |
| 73 | + |
| 74 | +class LayerNorm(torch.nn.Module): |
| 75 | + def __init__(self): |
| 76 | + super().__init__() |
| 77 | + self.layer_norm = torch.nn.LayerNorm(4, elementwise_affine=False) |
| 78 | + |
| 79 | + def forward(self, x): |
| 80 | + return self.layer_norm(x) |
| 81 | + |
| 82 | + |
| 83 | +class GroupNorm(torch.nn.Module): |
| 84 | + def __init__(self): |
| 85 | + super().__init__() |
| 86 | + self.group_norm = torch.nn.GroupNorm(2, 4, affine=False) |
| 87 | + |
| 88 | + def forward(self, x): |
| 89 | + return self.group_norm(x) |
| 90 | + |
| 91 | + |
| 92 | +@dataclass(frozen=True) |
| 93 | +class MetaRetraceCase: |
| 94 | + name: str |
| 95 | + module_factory: Callable[[], torch.nn.Module] |
| 96 | + inputs_factory: Callable[[], tuple[torch.Tensor, ...]] |
| 97 | + aten_op: str |
| 98 | + |
| 99 | + |
| 100 | +_TEST_CASES = [ |
| 101 | + MetaRetraceCase( |
| 102 | + "add_alpha", |
| 103 | + AddAlpha, |
| 104 | + lambda: (torch.randn(2, 3), torch.randn(2, 3)), |
| 105 | + "aten.add.Tensor", |
| 106 | + ), |
| 107 | + MetaRetraceCase( |
| 108 | + "sub_alpha", |
| 109 | + SubAlpha, |
| 110 | + lambda: (torch.randn(2, 3), torch.randn(2, 3)), |
| 111 | + "aten.sub.Tensor", |
| 112 | + ), |
| 113 | + MetaRetraceCase( |
| 114 | + "slice_scatter", |
| 115 | + SliceScatter, |
| 116 | + lambda: (torch.randn(2, 4), torch.randn(2, 2)), |
| 117 | + "aten.slice_scatter.default", |
| 118 | + ), |
| 119 | + MetaRetraceCase( |
| 120 | + "mean_dim", |
| 121 | + MeanDim, |
| 122 | + lambda: (torch.randn(2, 3, 4),), |
| 123 | + "aten.mean.dim", |
| 124 | + ), |
| 125 | + MetaRetraceCase( |
| 126 | + "mean_default", |
| 127 | + MeanDefault, |
| 128 | + lambda: (torch.randn(2, 3, 4),), |
| 129 | + "aten.mean.default", |
| 130 | + ), |
| 131 | + MetaRetraceCase( |
| 132 | + "var_correction", |
| 133 | + VarCorrection, |
| 134 | + lambda: (torch.randn(2, 3, 4, 4),), |
| 135 | + "aten.var.correction", |
| 136 | + ), |
| 137 | + MetaRetraceCase( |
| 138 | + "var_dim", |
| 139 | + VarDim, |
| 140 | + lambda: (torch.randn(2, 3, 4, 4),), |
| 141 | + "aten.var.dim", |
| 142 | + ), |
| 143 | + MetaRetraceCase( |
| 144 | + "div_tensor_mode", |
| 145 | + DivTensorMode, |
| 146 | + lambda: (torch.randn(2, 3), torch.randn(2, 3) + 1.0), |
| 147 | + "aten.div.Tensor_mode", |
| 148 | + ), |
| 149 | + MetaRetraceCase( |
| 150 | + "leaky_relu", |
| 151 | + LeakyRelu, |
| 152 | + lambda: (torch.randn(2, 3),), |
| 153 | + "aten.leaky_relu.default", |
| 154 | + ), |
| 155 | + MetaRetraceCase( |
| 156 | + "avg_pool2d", |
| 157 | + AvgPool2d, |
| 158 | + lambda: (torch.randn(1, 3, 4, 4),), |
| 159 | + "aten.avg_pool2d.default", |
| 160 | + ), |
| 161 | + MetaRetraceCase( |
| 162 | + "layer_norm", |
| 163 | + LayerNorm, |
| 164 | + lambda: (torch.randn(2, 3, 4),), |
| 165 | + "aten.layer_norm.default", |
| 166 | + ), |
| 167 | + MetaRetraceCase( |
| 168 | + "group_norm", |
| 169 | + GroupNorm, |
| 170 | + lambda: (torch.randn(2, 4, 3, 3),), |
| 171 | + "aten.group_norm.default", |
| 172 | + ), |
| 173 | +] |
| 174 | + |
| 175 | + |
| 176 | +def _make_quantizer() -> TOSAQuantizer: |
| 177 | + quantizer = TOSAQuantizer(TosaSpecification.create_from_string("TOSA-1.0+INT")) |
| 178 | + quantizer.set_global(get_symmetric_quantization_config(is_per_channel=False)) |
| 179 | + return quantizer |
| 180 | + |
| 181 | + |
| 182 | +def _iter_fake_tensors(meta_val): |
| 183 | + if isinstance(meta_val, FakeTensor): |
| 184 | + yield meta_val |
| 185 | + return |
| 186 | + |
| 187 | + if isinstance(meta_val, (list, tuple)): |
| 188 | + for item in meta_val: |
| 189 | + yield from _iter_fake_tensors(item) |
| 190 | + |
| 191 | + |
| 192 | +def _to_meta_inputs( |
| 193 | + example_inputs: tuple[torch.Tensor, ...], |
| 194 | +) -> tuple[torch.Tensor, ...]: |
| 195 | + return tuple(inp.to(device="meta") for inp in example_inputs) |
| 196 | + |
| 197 | + |
| 198 | +@pytest.mark.parametrize("case", _TEST_CASES, ids=[case.name for case in _TEST_CASES]) |
| 199 | +def test_post_quant_device_switch_no_target(case: MetaRetraceCase) -> None: |
| 200 | + """This test tests that moving a model to another device after quantiation |
| 201 | + works. |
| 202 | + """ |
| 203 | + module = case.module_factory().train() |
| 204 | + example_inputs = case.inputs_factory() |
| 205 | + |
| 206 | + # Quantize module |
| 207 | + exported = torch.export.export(module, example_inputs, strict=True) |
| 208 | + prepared = prepare_qat_pt2e(copy.deepcopy(exported.graph_module), _make_quantizer()) |
| 209 | + prepared(*example_inputs) |
| 210 | + prepared = move_exported_model_to_eval(prepared) |
| 211 | + quantized_module = convert_pt2e(prepared) |
| 212 | + |
| 213 | + # Move and test running the model with other device. |
| 214 | + meta_inputs = _to_meta_inputs(example_inputs) |
| 215 | + meta_module = ToDevicePass("meta")(quantized_module).graph_module |
| 216 | + meta_module(*meta_inputs) |
| 217 | + |
| 218 | + # Retrace module using meta device to check all fake tensors are moved. |
| 219 | + meta_module = torch.export.export(meta_module, meta_inputs, strict=True) |
| 220 | + |
| 221 | + # Validate transformation. |
| 222 | + fake_tensor_devices = [ |
| 223 | + (str(fake_tensor.device), str(node)) |
| 224 | + for node in meta_module.graph.nodes |
| 225 | + for fake_tensor in _iter_fake_tensors(node.meta.get("val")) |
| 226 | + ] |
| 227 | + |
| 228 | + assert fake_tensor_devices, "Expected traced graph to contain FakeTensor metadata" |
| 229 | + assert all(device == "meta" for device, _ in fake_tensor_devices), ( |
| 230 | + "Expected all traced FakeTensors to use the meta device, got " |
| 231 | + f"{fake_tensor_devices}" |
| 232 | + ) |
0 commit comments