|
1 | | -# Copyright 2024-2025 NXP |
| 1 | +# Copyright 2024-2026 NXP |
2 | 2 | # |
3 | 3 | # This source code is licensed under the BSD-style license found in the |
4 | 4 | # LICENSE file in the root directory of this source tree. |
5 | 5 |
|
| 6 | +import logging |
| 7 | + |
6 | 8 | import torch |
7 | 9 |
|
8 | 10 | from executorch.exir.dialects._ops import ops as exir_ops |
|
19 | 21 | exir_ops.edge.quantized_decomposed.dequantize_per_tensor.default, |
20 | 22 | ] |
21 | 23 |
|
| 24 | +# A set of operators which could possibly be no-ops in certain conditions. The operators in this set will be proclaimed |
| 25 | +# as no-ops (and potentially not delegated), if their input and output tensors are equal (when run on random data). |
| 26 | +no_op_candidates = { |
| 27 | + exir_ops.edge.aten.add.Tensor, |
| 28 | + exir_ops.edge.aten.mul.Tensor, |
| 29 | + exir_ops.edge.aten.sub.Tensor, |
| 30 | +} |
| 31 | + |
22 | 32 |
|
23 | 33 | def input_tensor(node: Node, input_index: int) -> torch.Tensor: |
24 | 34 | if len(node.all_input_nodes) <= input_index: |
@@ -220,3 +230,127 @@ def get_non_qdq_parent(node: Node, input_index: int = 0) -> Node | None: |
220 | 230 | return None |
221 | 231 |
|
222 | 232 | return quant_node.args[0] |
| 233 | + |
| 234 | + |
| 235 | +def try_get_dequantized_data( |
| 236 | + dequantize_node: Node, parameters_mapping: dict[str, Parameter] |
| 237 | +) -> Parameter | None: |
| 238 | + """Get the dequantized data from the following pattern. The dequantization formula is `r = (q - Z) * S`, where `q` |
| 239 | + represents the static quantized data. |
| 240 | +
|
| 241 | + ┌─────────────────────────┐ |
| 242 | + │ <static_quantized_data> │ |
| 243 | + └────────────┬────────────┘ |
| 244 | + │ |
| 245 | + ┌─────▼──────┐ |
| 246 | + │ Dequantize │ |
| 247 | + └─────┬──────┘ |
| 248 | + ▼ |
| 249 | +
|
| 250 | +
|
| 251 | + :param dequantize_node: The Dequantize node from the pattern, which dequantizes the static quantized data. |
| 252 | + :param parameters_mapping: Dict mapping tensor names to their static data. Should be inferred from the |
| 253 | + `state_dict` attribute of an edge program. |
| 254 | + :return: The dequantized static parameter, or `None` if the data is not available. |
| 255 | + """ |
| 256 | + if not _is_dequantize(dequantize_node): |
| 257 | + return None |
| 258 | + |
| 259 | + if not node_is_static_tensor(param := dequantize_node.args[0], parameters_mapping): |
| 260 | + return None |
| 261 | + |
| 262 | + # The pattern is correct. Dequantize the static data and return it. |
| 263 | + scale, zp = get_quantization_parameters_for(dequantize_node) |
| 264 | + quantized_data = parameters_mapping[param.name] |
| 265 | + |
| 266 | + dequantized_data = (quantized_data - zp) * scale |
| 267 | + return dequantized_data |
| 268 | + |
| 269 | + |
| 270 | +def is_no_op_on_neutron(node: Node, parameters_mapping: dict[str, Parameter]) -> bool: |
| 271 | + """Check if a node is a no-op operation from the perspective of Neutron.""" |
| 272 | + if node.op != "call_function": |
| 273 | + raise ValueError( |
| 274 | + f"is_no_op_on_neutron(): Expected call_function node, got {node.op}." |
| 275 | + ) |
| 276 | + |
| 277 | + if node.target in [ |
| 278 | + exir_ops.edge.aten.view_copy.default, |
| 279 | + exir_ops.edge.dim_order_ops._clone_dim_order.default, |
| 280 | + exir_ops.edge.aten.clone.default, |
| 281 | + ]: |
| 282 | + # Known operators which are always no-ops on Neutron. |
| 283 | + return True |
| 284 | + |
| 285 | + if node.target == exir_ops.edge.aten.cat.default and len(node.args[0]) == 1: |
| 286 | + # Concatenation with 1 input is a no-op. |
| 287 | + return True |
| 288 | + |
| 289 | + # For any other operators, run them with random data and see if the output is identical to the input. |
| 290 | + torch.manual_seed(42) |
| 291 | + # noinspection PyBroadException |
| 292 | + try: |
| 293 | + input_data = None |
| 294 | + args_with_random_data = [] |
| 295 | + for arg in node.args: |
| 296 | + match arg: |
| 297 | + case Node(): |
| 298 | + # `arg` is either another operator, a model input, or a static parameter. |
| 299 | + |
| 300 | + if ( |
| 301 | + data := try_get_dequantized_data(arg, parameters_mapping) |
| 302 | + ) is not None: |
| 303 | + # The `arg` is a static parameter. Use it's actual static data during the no-op test. |
| 304 | + args_with_random_data.append(data) |
| 305 | + |
| 306 | + else: |
| 307 | + # The `arg` is a compute node or a model input. Replace it with random data for the no-op test. |
| 308 | + if input_data is not None: |
| 309 | + # Some random input data for `node` has already been stored, which means that the node has |
| 310 | + # more than 1 dynamic input node. Therefore, it cannot be a no-op. |
| 311 | + return False |
| 312 | + |
| 313 | + # Generate the random data. Use the range [-5, 5) to avoid proclaiming operations like Relu as |
| 314 | + # no-ops. |
| 315 | + val = arg.meta["val"] |
| 316 | + input_data = torch.rand(val.shape, dtype=val.dtype) * 10 - 5 |
| 317 | + args_with_random_data.append(input_data) |
| 318 | + |
| 319 | + case list(): |
| 320 | + # Lists of input nodes are not supported to keep the code simple. It is not crucial to support this |
| 321 | + # case as the affected operators are either not supported on Neutron, or are extremely unlikely to |
| 322 | + # be no-ops (e.g. GRU). One exception is `aten.cat`, which is explicitly supported above. |
| 323 | + return False |
| 324 | + |
| 325 | + case _: |
| 326 | + # Generic argument (value). Not an input from a previous node. Store it in the arguments for the |
| 327 | + # no-op test. |
| 328 | + args_with_random_data.append(arg) |
| 329 | + |
| 330 | + # Run the operator with the random data. If the input equals the output, the node is considered a no-op. |
| 331 | + output_data = node.target(*args_with_random_data) |
| 332 | + |
| 333 | + val = node.meta["val"] |
| 334 | + if ( |
| 335 | + output_data.dtype == val.dtype |
| 336 | + and output_data.shape == val.shape |
| 337 | + and torch.all(input_data == output_data) |
| 338 | + ): |
| 339 | + # The operator preserves the shape, data type, and data. Therefore, it is a no-op from the perspective of |
| 340 | + # Neutron. |
| 341 | + if node.target in no_op_candidates: |
| 342 | + return True |
| 343 | + else: |
| 344 | + logging.info( |
| 345 | + f"Found the operator `{node.target}`, which appears to be a no-op, but is not in the " |
| 346 | + "known no-op list. Please report this issue." |
| 347 | + ) |
| 348 | + return False |
| 349 | + |
| 350 | + else: |
| 351 | + # Type, shape, or data doesn't match. |
| 352 | + return False |
| 353 | + |
| 354 | + except Exception: |
| 355 | + # If execution fails, assume it's not a no-op. |
| 356 | + return False |
0 commit comments