Skip to content

Commit 46f544a

Browse files
JakeStevensmeta-codesync[bot]
authored andcommitted
Fix negative dimension handling in narrow_copy (#22969)
Summary: Pull Request resolved: #22969 Resolves: #13556 Normalize negative `dim` values before validating `narrow_copy` arguments. This prevents valid negative dimensions from reaching tensor size checks unnormalized and causing a runtime assertion. Adds regression coverage for copying with `dim=-1`. Reviewed By: mergennachin Differential Revision: D121015244
1 parent bb2683b commit 46f544a

2 files changed

Lines changed: 20 additions & 4 deletions

File tree

‎kernels/portable/cpu/op_narrow_copy.cpp‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,16 +25,18 @@ Tensor& narrow_copy_out(
2525
Tensor& out) {
2626
(void)ctx;
2727

28+
ET_KERNEL_CHECK(ctx, dim_is_valid(dim, in.dim()), InvalidArgument, out);
29+
30+
if (dim < 0) {
31+
dim += in.dim();
32+
}
33+
2834
ET_KERNEL_CHECK(
2935
ctx,
3036
check_narrow_copy_args(in, dim, start, length, out),
3137
InvalidArgument,
3238
out);
3339

34-
if (dim < 0) {
35-
dim += in.dim();
36-
}
37-
3840
// @lint-ignore CLANGTIDY facebook-hte-CArray
3941
Tensor::SizesType target_sizes[kTensorDimensionLimit];
4042
size_t target_ndim = 0;

‎kernels/test/op_narrow_copy_test.cpp‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,20 @@ TEST_F(OpNarrowCopyOutTest, AllDtypesSupported) {
6767
#undef TEST_ENTRY
6868
}
6969

70+
TEST_F(OpNarrowCopyOutTest, NegativeDimSupported) {
71+
TensorFactory<ScalarType::Int> tf;
72+
73+
Tensor input = tf.make({2, 3}, {1, 2, 3, 4, 5, 6});
74+
Tensor out = tf.zeros({2, 2});
75+
Tensor expected = tf.make({2, 2}, {2, 3, 5, 6});
76+
77+
Tensor ret =
78+
op_narrow_copy_out(input, /*dim=*/-1, /*start=*/1, /*length=*/2, out);
79+
80+
EXPECT_TENSOR_EQ(ret, out);
81+
EXPECT_TENSOR_EQ(ret, expected);
82+
}
83+
7084
TEST_F(OpNarrowCopyOutTest, EmptyInputSupported) {
7185
TensorFactory<ScalarType::Int> tf;
7286

0 commit comments

Comments
 (0)