Skip to content

Add pass to replace some ops with channels last variants.#20788

Open
MartinPavella wants to merge 3 commits into
pytorch:mainfrom
nxp-upstream:nxg01483/EIEX-992-create-tocontiguouschannelslastpass
Open

Add pass to replace some ops with channels last variants.#20788
MartinPavella wants to merge 3 commits into
pytorch:mainfrom
nxp-upstream:nxg01483/EIEX-992-create-tocontiguouschannelslastpass

Conversation

@MartinPavella

Copy link
Copy Markdown
Collaborator

Summary

Add a transformation pass to replace some operators with their channels last variant. Currently only convolution and avg_pool2d are implemented, as those are the only operators with a channels last variant. In the future, the pass can be easily extended to support more operators.

Test plan

Tested by pytest backends/transforms/test/test_replace_ops_with_channels_last_variants.py.

@MartinPavella MartinPavella self-assigned this Jul 8, 2026
@MartinPavella MartinPavella added the python Pull requests that update python code label Jul 8, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/20788

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 New Failure, 2 Unrelated Failures

As of commit 7e23e2d with merge base a19d1ba (image):

NEW FAILURE - The following job has failed:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

BROKEN TRUNK - The following job failed but was present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Jul 8, 2026
@linux-foundation-easycla

linux-foundation-easycla Bot commented Jul 8, 2026

Copy link
Copy Markdown

CLA Not Signed

@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your change should be included in the release notes (i.e. would users of this library care about this change?), please use a label starting with release notes:. This helps us keep track and include your important work in the next release notes.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "release notes: none"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@MartinPavella

Copy link
Copy Markdown
Collaborator Author

@AdrianLundell this is the first part of #20094. I am planning on introducing the second part (a pass which makes the graph contiguous) separately.

@JakeStevens
JakeStevens requested a review from mcremon-meta July 13, 2026 16:16
_NHWC_TO_NCHW_PERM: list[int] = [0, 3, 1, 2]


def _requires_rank(rank: int) -> Callable[[torch.fx.Node], bool]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not allow (CHW,) -> (HWC) as well?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, I missed that use case.
I will make the relevant changes.

@MartinPavella MartinPavella Jul 17, 2026

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For convolution, unsqueeze and squeeze operators are inserted during lowering to edge, which explicitly add/remove the batch size of 1, and the exisitng code with 4D permutations works correctly.
For avg_pool2d, this doesn't happen.

I have decided to update this pass to also insert the [un]squeeze for implicit batch cases, which should solve all related issues while remaining consistent with convolution.

@AdrianLundell

Copy link
Copy Markdown
Collaborator

Great to see the collaboration on this, just one question!

@rascani rascani left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add BUCK support in the targets.bzl?

      runtime.python_library(
          name = "replace_ops_with_channels_last_variants",
          srcs = [
              "replace_ops_with_channels_last_variants.py",
          ],
          visibility = [
              "//executorch/backends/...",
          ],
          deps = [
              "//caffe2:torch",
              ":channels_last_ops",
              "//executorch/exir:pass_base",
          ],
      )

      runtime.python_test(
          name = "test_replace_ops_with_channels_last_variants",
          srcs = [
              "test/test_replace_ops_with_channels_last_variants.py",
          ],
          deps = [
              "//caffe2:torch",
              ":channels_last_ops",
              ":replace_ops_with_channels_last_variants",
              "//executorch/exir:lib",
              "fbsource//third-party/pypi/pytest:pytest",
          ],
      )

Comment thread backends/transforms/replace_ops_with_channels_last_variants.py Outdated

args = list(node.args)

with graph.inserting_before(node):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might want to consider using the super().call_operator() style of rewrites, which eliminates having to deal with meta & graph cleanup. Not a blocker though.

      def call(self, graph_module: torch.fx.GraphModule) -> PassResult:
          self._modified = False
          result = super().call(graph_module)
          return PassResult(result.graph_module, self._modified)

      def call_operator(self, op, args, kwargs, meta: NodeMetadata) -> ProxyValue:
          spec = self.op_map.get(op)
          if spec is None:
              return super().call_operator(op, args, kwargs, meta)

          val = meta["val"]
          contiguous_dim_order = tuple(range(len(val.shape)))
          if val.dim_order() != contiguous_dim_order or (
              spec.filter_fn is not None and not spec.filter_fn(val)
          ):
              return super().call_operator(op, args, kwargs, meta)

          new_args = list(args)
          for idx in spec.input_indices:
              new_args[idx] = super().call_operator(
                  exir_ops.edge.channels_last.permute_copy.default,
                  (new_args[idx], _NCHW_TO_NHWC_PERM),
                  {},
                  meta,
              )

          nhwc_out = super().call_operator(spec.target, tuple(new_args), kwargs, meta)

          self._modified = True
          return super().call_operator(
              exir_ops.edge.channels_last.permute_copy.default,
              (nhwc_out, _NHWC_TO_NCHW_PERM),
              {},
              meta,
          )

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the suggestion. After consideration, I prefer your solution. I have updated the implementation.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: When I tried to add support for max_pool2d_with_indices, I realized that the call_operator() style won't work. This is because permute and squeeze operators must be added after the getitem nodes of the max_pool2d_with_indices, so the resulting sugbraph would have multiple distinct outputs (which as far as I can tell is incompatible with the call_operator() pass style).

Therefore, I have switched back to the original approach.

@MartinPavella

Copy link
Copy Markdown
Collaborator Author

Implemented changes based on reviews.
I plan on updating this PR once more to add support for the new channels last ops recently added by R. J.: #20775

When replacing aten.avg_pool2d` with `channels_last.avg_pool2d`, some attributes of the aten operator can be left out, and must be replaced by default values. This can either be done in the "to channels last" transformation pass, or in the definition of the operator. Adding the default attributes of the aten operator to the channels_last operator seems cleaner to me.
The pass currently supports `convolution` and `avg_pool2d`, as those are the only 2 operators with a channels last variant. The pass can be easily extended to more ops in the future.
@MartinPavella
MartinPavella force-pushed the nxg01483/EIEX-992-create-tocontiguouschannelslastpass branch from 7a3b692 to 7e23e2d Compare July 21, 2026 07:33

@AdrianLundell AdrianLundell left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, it is a bit unfortunate that there are these arbitrary differences between ops which must be handled everywhere but not much to do about it.

@rascani

rascani commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

@MartinPavella - Would you mind taking care of the EasyCLA? This is part of the migration of ExecuTorch to the PyTorch/Linux Foundation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. python Pull requests that update python code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants