diff --git a/paddle/phi/kernels/impl/crop_kernel_impl.h b/paddle/phi/kernels/impl/crop_kernel_impl.h index d3cb672104d6792a6dedffb4e4da293d16fa4f1f..5aa951d4da09d69a949a932aa2af1499c148c445 100644 --- a/paddle/phi/kernels/impl/crop_kernel_impl.h +++ b/paddle/phi/kernels/impl/crop_kernel_impl.h @@ -100,6 +100,16 @@ void CropTensorFunction(const Context& dev_ctx, out->Resize(out_dims); dev_ctx.template Alloc(out); for (size_t i = 0; i < offsets_vec.size(); ++i) { + PADDLE_ENFORCE_GE( + offsets_vec[i], + 0, + errors::InvalidArgument("The offsets (%d) of the %uth elements of" + " Op(crop_tensor) " + "should be greater than or " + "equal to 0.", + offsets_vec[i], + i)); + PADDLE_ENFORCE_LE(offsets_vec[i] + shape_vec[i], x_dims[i], errors::InvalidArgument( diff --git a/python/paddle/fluid/tests/unittests/test_crop_op.py b/python/paddle/fluid/tests/unittests/test_crop_op.py index 1050fb0ad5c57399cc2ed391f00dd81e538f2e9f..f5886edc3350ceca33f8084f0a9d4a740e88a376 100644 --- a/python/paddle/fluid/tests/unittests/test_crop_op.py +++ b/python/paddle/fluid/tests/unittests/test_crop_op.py @@ -149,6 +149,13 @@ class TestCropNoneShape(unittest.TestCase): self.assertEqual(crop.shape, (3, 6, 6)) +class TestCropError(unittest.TestCase): + def test_neg_offset_error(self): + with self.assertRaises(ValueError): + x = fluid.data(name='input2', shape=[1], dtype="float32") + out = paddle.crop(x, offsets=[-1]) + + if __name__ == '__main__': paddle.enable_static() unittest.main()