Skip to content

Commit b0e7c33

Browse files
committed
Merge pull request #10545 from aizu-m:transpose-rank-mismatch
PiperOrigin-RevId: 936133220
2 parents a27ef62 + a9c1b09 commit b0e7c33

2 files changed

Lines changed: 36 additions & 1 deletion

File tree

src/subgraph/static-transpose.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,15 @@ static enum xnn_status reshape_transpose_operator(
7474
assert(output_id < num_values);
7575

7676
const size_t num_dims = opdata->shape1.num_dims;
77-
assert(input->shape.num_dims == num_dims);
77+
if (input->shape.num_dims != num_dims) {
78+
xnn_log_error(
79+
"failed to reshape %s operator with input ID #%" PRIu32
80+
": number of input dimensions (%zu) does not match the number of "
81+
"permutation dimensions (%zu)",
82+
xnn_node_type_to_string(xnn_node_type_static_transpose), input_id,
83+
input->shape.num_dims, num_dims);
84+
return xnn_status_invalid_parameter;
85+
}
7886

7987
switch (opdata->operator_objects[0]->type) {
8088
case xnn_operator_type_transpose_nd_x16: {

test/subgraph/static-transpose.cc

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,31 @@ INSTANTIATE_TEST_SUITE_P(Transpose, TransposeQU8, rank_params);
8585
INSTANTIATE_TEST_SUITE_P(Transpose, TransposeF16, rank_params);
8686
INSTANTIATE_TEST_SUITE_P(Transpose, TransposeF32, rank_params);
8787

88+
#ifndef XNNPACK_USE_YNNPACK
89+
TEST(Transpose, reshape_rejects_input_rank_mismatch) {
90+
ASSERT_EQ(xnn_status_success, xnn_initialize(nullptr /* allocator */));
91+
92+
// The permutation fixes the operator rank at define time. An external input
93+
// may be reshaped to a different rank at runtime; the reshape must reject the
94+
// mismatch instead of transposing with a stale dimension count and reading
95+
// past the input buffer.
96+
const std::vector<size_t> perm = {2, 0, 1};
97+
SubgraphTester subgraph(2);
98+
subgraph.AddInputTensor(3, xnn_datatype_fp32, 0)
99+
.AddOutputTensor(3, xnn_datatype_fp32, 1)
100+
.AddTranspose(perm, 0, 1);
101+
if (subgraph.CreateRuntime() == xnn_status_unsupported_hardware) {
102+
GTEST_SKIP();
103+
}
104+
105+
std::vector<float> data(6, 0.0f);
106+
subgraph.ReshapeExternalTensor(std::vector<size_t>({2, 3}), data.data(), 0)
107+
.ReshapeRuntime();
108+
EXPECT_EQ(subgraph.Status(), xnn_status_invalid_parameter);
109+
}
110+
#else
111+
// In YNNPACK transpose can add or remove dimensions, so a rank mismatch is not
112+
// an error.
113+
#endif // XNNPACK_USE_YNNPACK
114+
88115
} // namespace xnnpack

0 commit comments

Comments
 (0)