to_edge_transform_and_lower ignores some ops_to_not_decompose requests: multi-output ops, and non-core ops without a decomposition

Abierto Apto para principiantes
#25,620 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
66/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python, pytorch
Área
compilers

Línea de trabajo

Ambas rutas de preservación viven en exir/program/_program.py: empieza en _remove_invalid_ops_for_not_decompose (~L1089) para la comprobación de aliasing, luego lee la rama check_op_support=None que consulta la tabla de descomposición predeterminada (~L1205). Ejecuta primero el reproductor del cuerpo del issue para confirmar que aminmax se divide y que sort.stable lanza SpecViolationError, luego aplica las dos correcciones y vuelve a ejecutarlo para que el particionador vea aten.aminmax.default y aten.sort.stable. Hecho significa que ambos casos llegan al particionador y que las pruebas de lowering de exir existentes siguen pasando.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

module: exir

to_edge_transform_and_lower ignores some of the ops a partitioner asks to keep through ops_to_not_decompose. There are two cases, one on each preservation path in exir/program/_program.py.

1. With check_op_support, ops with more than one output are treated as aliasing. _remove_invalid_ops_for_not_decompose drops an op when native_schema.aliased_return_names() != [None]. For an op with two outputs that don't alias, such as aminmax or sort, that list is [None, None]. The request is dropped with "This request is ignored because it aliases output", and the op is decomposed before the partitioner sees it.

2. With check_op_support=None, a non-core op that has no decomposition fails the Core ATen check. On this path a requested op is only added to the preserved set if it appears in the default decomposition table. aten.sort.stable has no decomposition, so it is never added, and lowering fails with SpecViolationError: Operator torch._ops.aten.sort.stable is not in Core ATen opset before the partitioner runs. This is why torch.sort(x, stable=True) can't be delegated to MLX: #25364 registers aten.sort.stable, and its tests fail at export. torch.argsort(x, stable=True) works, because argsort.stable is in the table.

Repro with a partitioner that records the ops it is shown:

import torch
from executorch.exir import to_edge_transform_and_lower
from executorch.exir.backend.partitioner import (
    DelegationSpec,
    Partitioner,
    PartitionResult,
)


class RecordingPartitioner(Partitioner):
    """Requests preservation of `op` and records the ops it is shown."""

    def __init__(self, op, check_op_support):
        super().__init__()
        self.delegation_spec = DelegationSpec("NoBackend", [])
        self.op = op
        self.check_op_support = check_op_support
        self.seen = None

    def ops_to_not_decompose(self, ep):
        return [self.op], self.check_op_support

    def partition(self, ep):
        self.seen = sorted(
            {
                n.target.__name__
                for n in ep.graph.nodes
                if n.op == "call_function" and hasattr(n.target, "__name__")
            }
        )
        return PartitionResult(tagged_exported_program=ep, partition_tags={})


class Aminmax(torch.nn.Module):
    def forward(self, x):
        return torch.aminmax(x, dim=-1)


class StableSort(torch.nn.Module):
    def forward(self, x):
        return torch.sort(x, stable=True)


cases = [
    # check_op_support given -> EDGE_DO_NOT_DECOMP path
    ("aminmax, check_op_support given", Aminmax(), torch.ops.aten.aminmax.default, lambda n: True),
    # check_op_support None -> decomposition-table path
    ("sort.stable, check_op_support=None", StableSort(), torch.ops.aten.sort.stable, None),
]
for name, model, op, check in cases:
    part = RecordingPartitioner(op, check)
    ep = torch.export.export(model, (torch.randn(3, 4),))
    try:
        to_edge_transform_and_lower(ep, partitioner=[part])
        error = ""
    except Exception as e:
        error = f"; then {type(e).__name__}: {str(e).strip().splitlines()[0][:80]}"
    print(f"{name}: partitioner saw {part.seen}{error}")

On main:

aminmax, check_op_support given: partitioner saw ['aten.amax.default', 'aten.amin.default']
sort.stable, check_op_support=None: partitioner saw None; then SpecViolationError: Operator torch._ops.aten.sort.stable is not in Core ATen opset ...

These two changes fix both cases locally:

-            if native_schema.aliased_return_names() != [None]:
+            if any(name is not None for name in native_schema.aliased_return_names()):
                     for op in curr_ops_no_decomp:
-                        if table.pop(op, None) is not None:
+                        if (
+                            table.pop(op, None) is not None
+                            or torch.Tag.core not in op.tags
+                        ):
                             ops_needing_preservation.append(op)

With them, the partitioner sees aten.aminmax.default and aten.sort.stable. The repro then stops at "was not decomposed or delegated", which is expected because it delegates nothing. With the second change and aten.sort.stable registered in the MLX sort handler, torch.sort(x, stable=True) is fully delegated to MLX and matches eager, including the order of equal values.

Environment: main at ec5937f865 (exir/program/_program.py is identical to the tree I ran), Apple M2 Ultra, macOS 27.2, Python 3.13, PyTorch 2.14.0.

Found while reviewing #25364, and verified with help from Claude Code.

cc @JacobSzwejbka @angelayi

Lenguaje dominante
Python
Estrellas
5.2k
Forks
1.3k
Merge medio
1 d 14 h
PR fusionados (30 d)
678

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de pytorch/executorch

Todos los issues de pytorch/executorch

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.