Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion backends/xnnpack/operators/op_permute.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,21 @@ def define_node(
self.define_nodes_tensor_inputs_outputs(node, xnn_graph, vals_to_ids)

# input
input_id = vals_to_ids[get_input_node(node, 0)]
input_node = get_input_node(node, 0)
input_id = vals_to_ids[input_node]

# output
output_id = vals_to_ids[node]

# permutation
input_rank = input_node.meta["val"].dim()
permute_order = cast(List[int], node.args[1])

# Handle negative dimensions by converting them to positive indices
permute_order = [
(dim + input_rank) if dim < 0 else dim for dim in permute_order
Copy link
Contributor

Choose a reason for hiding this comment

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

is it possible that dim + input_rank is still negative?

Copy link
Member Author

@GregoryComer GregoryComer Sep 11, 2025

Choose a reason for hiding this comment

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

Good question. I just tried in eager mode, and it seems to enforce that dims are in the range of [-rank, rank-1] inclusive.

>>> temp = torch.randn(1,2,3,4,5)
>>> temp.permute(-9, 2, 3, 4, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: Dimension out of range (expected to be in range of [-5, 4], but got -9)

]

# change permute order if under channels last
is_channels_last = node.meta.get(
ChannelsLastTaggedReshapePass.XNN_NHWC_NODE, False
Expand Down
14 changes: 14 additions & 0 deletions backends/xnnpack/test/ops/test_permute.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,20 @@ def test_fp32_permute(self):
inputs = (torch.randn(1, 1, 4, 4),)
self._test_permute(inputs)

def test_fp32_permute_negative_dim(self):
inputs = (torch.randn(1, 1, 4, 4),)
(
Tester(self.Permute([0, -2, -1, 1]), inputs)
.export()
.check_count({"torch.ops.aten.permute.default": 1})
.to_edge_transform_and_lower()
.check_count({"torch.ops.higher_order.executorch_call_delegate": 1})
.check_not(["executorch_exir_dialects_edge__ops_aten_permute_copy_default"])
.to_executorch()
.serialize()
.run_method_and_compare_outputs()
)

def test_fp32_permute_copy(self):
inputs = (torch.randn(1, 1, 4, 4),)
(
Expand Down
Loading