Repository navigation
Validate spatial attributes in ExtractImagePatches and ExtractVolumePatches shape inference - #128388
Conversation
In ExtractImagePatches and ExtractVolumePatches shape inference, non-positive spatial ksizes, strides, or rates attributes cause integer multiplication to pass negative values to DimensionOrConstant, triggering an assertion failure (SIGABRT) in debug builds or resulting in invalid output shapes in release builds. Add positive validation checks for spatial ksizes, strides, and rates in ExtractImagePatches and ExtractVolumePatches shape inference functions, and add unit tests covering zero and negative attribute values. Fixes tensorflow#63067.
There was a problem hiding this comment.
Code Review
This pull request introduces input validation checks for the ExtractImagePatches and ExtractVolumePatches operations in tensorflow/core/ops/array_ops.cc, ensuring that spatial attributes like kernel sizes, strides, and rates are strictly positive. It also adds comprehensive unit tests in Python to verify that invalid (negative or zero) attributes correctly trigger errors in both eager and graph execution modes. I have no feedback to provide as the implementation is robust and well-tested.
dmiltr3
left a comment
There was a problem hiding this comment.
The shape-function checks in tensorflow/core/ops/array_ops.cc are correct and minimal, and they match what the CPU, GPU and XLA kernels already reject at construction time. However, CI is red on Linux CPU, Linux CUDA and Windows for two test-only reasons. Please address the following.
1. The new tests fail in eager mode (the TF2 default)
In eager execution the shape function does not run. The kernel constructor in tensorflow/core/kernels/image/extract_image_patches_op.cc (and extract_volume_patches_op.cc) rejects the attribute first with OutOfRangeError: ksizes is out of range., which the tests neither catch nor match:
tensorflow.python.framework.errors_impl.OutOfRangeError: {{function_node __wrapped__ExtractImagePatches_device_/job:localhost/replica:0/task:0/device:CPU:0}} ksizes is out of range. [Op:ExtractImagePatches]
Please accept both errors in the eager part, as testLargeKsize in the same file already does, and then assert the new shape-function message for every attribute inside a with ops.Graph().as_default(): block on a placeholder, so each new check is covered in both modes. For tensorflow/python/kernel_tests/image_ops/extract_image_patches_op_test.py:
def testNegativeOrZeroAttributes(self):
"""Test for negative or zero spatial attributes."""
image = constant_op.constant(np.ones([1, 2, 2, 1], dtype=np.float32))
valid = [1, 1, 1, 1]
for attr, value in [
("ksizes", [1, -1, 2, 1]),
("ksizes", [1, 2, 0, 1]),
("ksizes", [1, -1, -2, 1]),
("strides", [1, -1, 1, 1]),
("strides", [1, 1, 0, 1]),
("rates", [1, -1, 1, 1]),
("rates", [1, 1, 0, 1]),
]:
kwargs = {"ksizes": valid, "strides": valid, "rates": valid}
kwargs[attr] = value
# Graph construction runs the shape function (ValueError); eager
# execution runs the kernel constructor (OutOfRangeError).
with self.assertRaisesRegex(
(errors_impl.OutOfRangeError, ValueError),
rf"ExtractImagePatches requires spatial {attr} to be positive"
rf"|{attr} is out of range",
):
self.evaluate(
array_ops.extract_image_patches(image, padding="VALID", **kwargs)
)
# Shape inference must reject the same attributes.
with ops.Graph().as_default():
image_ph = array_ops.placeholder(dtypes.float32, shape=[1, 2, 2, 1])
with self.assertRaisesRegex(
ValueError,
rf"ExtractImagePatches requires spatial {attr} to be positive",
):
array_ops.extract_image_patches(image_ph, padding="VALID", **kwargs)And the analogous version for tensorflow/python/kernel_tests/image_ops/extract_volume_patches_op_test.py (5-element vectors, no rates, ksizes and strides at each of the three spatial indices):
def testNegativeOrZeroAttributes(self):
"""Test for negative or zero spatial attributes."""
image = constant_op.constant(np.ones([1, 2, 2, 2, 1], dtype=np.float32))
valid = [1, 1, 1, 1, 1]
for attr, value in [
("ksizes", [1, -1, 1, 1, 1]),
("ksizes", [1, 1, 0, 1, 1]),
("ksizes", [1, 1, 1, -1, 1]),
("ksizes", [1, -1, -1, -1, 1]),
("strides", [1, -1, 1, 1, 1]),
("strides", [1, 1, 0, 1, 1]),
("strides", [1, 1, 1, -1, 1]),
]:
kwargs = {"ksizes": valid, "strides": valid}
kwargs[attr] = value
# Graph construction runs the shape function (ValueError); eager
# execution runs the kernel constructor (OutOfRangeError).
with self.assertRaisesRegex(
(errors_impl.OutOfRangeError, ValueError),
rf"ExtractVolumePatches requires spatial {attr} to be positive"
rf"|{attr} is out of range",
):
self.evaluate(
array_ops.extract_volume_patches(image, padding="VALID", **kwargs)
)
# Shape inference must reject the same attributes.
with ops.Graph().as_default():
image_ph = array_ops.placeholder(dtypes.float32, shape=[1, 2, 2, 2, 1])
with self.assertRaisesRegex(
ValueError,
rf"ExtractVolumePatches requires spatial {attr} to be positive",
):
array_ops.extract_volume_patches(image_ph, padding="VALID", **kwargs)2. An existing XLA test now fails
testInvalidKernelSize in tensorflow/compiler/tests/extract_image_patches_op_test.py (also run through combined_ops_test_b and the MLIR bridge variants) builds the op with ksizes=[1, 0, 2, 1] outside its assertRaisesRegex block. With this change, graph construction rejects that value, so the test errors out before it reaches the assertion:
ValueError: ExtractImagePatches requires spatial ksizes to be positive, but got: [0, 2] for '{{node ExtractImagePatches}} = ExtractImagePatches[T=DT_FLOAT, ksizes=[1, 0, 2, 1], padding="VALID", rates=[1, 1, 1, 1], strides=[1, 1, 1, 1]](Placeholder)' with input shapes: ?.
Please keep the same input and assert the new, earlier error, and remove the errors_impl import from that file, which becomes unused:
def testInvalidKernelSize(self):
"""Test that zero kernel size is rejected by shape inference."""
with self.session():
image_placeholder = array_ops.placeholder(dtypes.float32)
with self.test_scope():
with self.assertRaisesRegex(
ValueError,
"ExtractImagePatches requires spatial ksizes to be positive",
):
array_ops.extract_image_patches(
image_placeholder,
ksizes=[1, 0, 2, 1],
strides=[1, 1, 1, 1],
rates=[1, 1, 1, 1],
padding="VALID",
)3. C++ shape-inference cases
Please add INFER_ERROR cases to ExtractImagePatchesShapeTest in tensorflow/core/ops/array_ops_test.cc: a zero and a negative ksizes, a zero strides on an input with unknown spatial dims ([1,?,?,2], the path where only the new check applies), and a negative rates. Please also add a small ExtractVolumePatchesShapeTest with one passing case plus ksizes and strides errors. For example:
// Non-positive spatial ksizes, strides, and rates.
set_op({1, 0, 2, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, "VALID");
INFER_ERROR("ExtractImagePatches requires spatial ksizes to be positive", op,
"[1,7,7,2]");
set_op({1, 2, -2, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, "VALID");
INFER_ERROR("ExtractImagePatches requires spatial ksizes to be positive", op,
"[1,7,7,2]");
set_op({1, 2, 2, 1}, {1, 0, 1, 1}, {1, 1, 1, 1}, "VALID");
INFER_ERROR("ExtractImagePatches requires spatial strides to be positive", op,
"[1,?,?,2]");
set_op({1, 2, 2, 1}, {1, 1, 1, 1}, {1, 1, -1, 1}, "VALID");
INFER_ERROR("ExtractImagePatches requires spatial rates to be positive", op,
"[1,7,7,2]");
}
TEST(ArrayOpsTest, ExtractVolumePatchesShapeTest) {
ShapeInferenceTestOp op("ExtractVolumePatches");
auto set_op = [&op](const std::vector<int32_t>& ksizes,
const std::vector<int32_t>& strides,
const std::string& padding) {
TF_ASSERT_OK(NodeDefBuilder("test", "ExtractVolumePatches")
.Input("input", 0, DT_FLOAT)
.Attr("ksizes", ksizes)
.Attr("strides", strides)
.Attr("padding", padding)
.Finalize(&op.node_def));
};
set_op({1, 2, 2, 2, 1}, {1, 1, 1, 1, 1}, "VALID");
INFER_OK(op, "[1,3,3,3,2]", "[d0_0,2,2,2,16]");
// Non-positive spatial ksizes and strides.
set_op({1, 0, 2, 2, 1}, {1, 1, 1, 1, 1}, "VALID");
INFER_ERROR("ExtractVolumePatches requires spatial ksizes to be positive", op,
"[1,3,3,3,2]");
set_op({1, 2, 2, -2, 1}, {1, 1, 1, 1, 1}, "VALID");
INFER_ERROR("ExtractVolumePatches requires spatial ksizes to be positive", op,
"[1,3,3,3,2]");
set_op({1, 2, 2, 2, 1}, {1, 1, 0, 1, 1}, "VALID");
INFER_ERROR("ExtractVolumePatches requires spatial strides to be positive",
op, "[1,?,?,?,2]");
}4. PR description
Please update the description: during graph construction the error surfaces in Python as ValueError, and in eager mode as OutOfRangeError from the kernel. Please also mention the updated XLA test.
Add C++ shape inference test cases for ExtractImagePatches and ExtractVolumePatches, update Python tests to assert both eager OutOfRangeError and graph mode ValueError, and update XLA test to expect shape inference rejection.
|
Pushed updates for the eager and graph test cases, added the C++ shape tests, and updated the XLA test and PR description. |
dmiltr3
left a comment
There was a problem hiding this comment.
Correction to our earlier review: The previous request to preserve the XLA kernel execution check in tensorflow/compiler/tests/extract_image_patches_op_test.py is retracted. Since shape inference now correctly rejects the invalid ksizes=[1, 0, 2, 1] attribute during graph construction, the XLA kernel compiler cannot be reached. Your approach of removing the .eval() call and asserting ValueError during graph construction is the correct way to test this.
Thank you for the excellent fix! The C++ validation perfectly prevents the integer overflow vulnerability and the exhaustive eager and graph mode testing looks great. However, there are a few required changes before we can merge this PR:
-
Missing IWYU include:
tensorflow/core/ops/array_ops.ccusesabsl::StrCatbut is missing the#include "absl/strings/str_cat.h"header. Please add this include. -
ExtractVolumePatches rank bug: In
tensorflow/core/ops/array_ops.cc:2846, theExtractVolumePatchesunknown-spatial-dims branch incorrectly returns a rank-4 shape instead of rank-5. Please fix this by usingShapeHandle output_shape = c->MakeShape({batch_size_dim, InferenceContext::kUnknownDim, InferenceContext::kUnknownDim, InferenceContext::kUnknownDim, output_depth_dim});and add a test asserting the rank-5 shape. -
Missing non-spatial index validation: In
tensorflow/core/ops/array_ops.cc:2685and2798, the shape functions do not validate that the non-spatial indices (ksizes[0],ksizes[last], etc.) are 1, leading to a divergence with the runtime OpKernel. Please add validation checking that the first and last elements ofksizes,strides, andratesare exactly1.
Ensure first and last elements of ksizes, strides, and rates are 1 in ExtractImagePatches and ExtractVolumePatches shape functions, fix unknown spatial rank in ExtractVolumePatches, and include str_cat.h. Signed-off-by: bodapatisaikrishna <[email protected]>
|
Added the str_cat.h include, fixed the rank-5 output shape for ExtractVolumePatches, and added validation and tests for the non-spatial attributes. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the excellent fix! The C++ validation perfectly prevents the integer overflow vulnerability and restores parity between the shape function and the runtime OpKernel. The exhaustive eager and graph mode testing looks great.
However, the GitHub CI PyLint check is failing due to some lines exceeding the 80-character limit. Could you please wrap the following long strings to fix the lint errors?
In tensorflow/python/kernel_tests/image_ops/extract_image_patches_op_test.py:
with self.assertRaisesRegex(
(errors_impl.UnimplementedError, ValueError),
rf"ExtractImagePatches requires the first and last elements of {attr} "
r"to be 1"
rf"|Only support {attr} across space",
):and
with self.assertRaisesRegex(
ValueError,
rf"ExtractImagePatches requires the first and last elements of {attr} "
r"to be 1",
):And similarly in tensorflow/python/kernel_tests/image_ops/extract_volume_patches_op_test.py:
with self.assertRaisesRegex(
(errors_impl.UnimplementedError, ValueError),
rf"ExtractVolumePatches requires the first and last elements of {attr} "
r"to be 1"
rf"|Only support {attr} across space",
):and
with self.assertRaisesRegex(
ValueError,
rf"ExtractVolumePatches requires the first and last elements of {attr} "
r"to be 1",
):Once the PyLint check is green, this PR will be ready to merge!
Signed-off-by: bodapatisaikrishna <[email protected]>
|
Wrapped the long lines in both test files to stay within the 80-column limit and verified with pylint. |
dmiltr3
left a comment
There was a problem hiding this comment.
Correction to our earlier review: The previous request to add validation checking that the first and last elements of ksizes, strides, and rates are exactly 1 in the shape functions is retracted. This violates our internal D5 directive ("Keep kernel fixes out of shared shape code"), which forbids tightening a registered op's SetShapeFn solely for parity with the runtime OpKernel. Please revert the non-spatial attribute checks in array_ops.cc and their corresponding tests.
Thank you for the updates! The spatial attribute validation correctly prevents the CHECK failures and the unknown-spatial-dims rank fix for ExtractVolumePatches looks great. We have just two remaining issues before this can be merged:
- Remove Non-Spatial Parity Checks: As noted above, please remove the non-spatial attribute validation blocks (
ksizes[0] != 1, etc.) that were added to theExtractImagePatchesandExtractVolumePatchesshape functions intensorflow/core/ops/array_ops.cc, along with the corresponding tests (testNonSpatialAttributesand the related assertions inarray_ops_test.cc). - Missing BUILD Dependency: The addition of
#include "absl/strings/str_cat.h"requires declaring the corresponding Bazel dependency so the code can compile. Please add"@com_google_absl//absl/strings"to thedepsof thearray_opsrule intensorflow/core/ops/BUILD.
tf_gen_op_libs(
op_lib_names = [
"array_ops",
],
sub_directory = "",
deps = [
"//tensorflow/core:lib",
"//tensorflow/core:protos_all_cc",
+ "@com_google_absl//absl/strings",
],
)Once these are updated, this PR will be ready!
Signed-off-by: bodapatisaikrishna <[email protected]>
|
Understood on D5. Reverted the non-spatial checks along with their tests, and added @com_google_absl//absl/strings to the array_ops BUILD deps. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates! The spatial attribute validation correctly prevents the fatal CHECK aborts, the BUILD dependency on @com_google_absl//absl/strings is correctly declared, and all carry-over recommendations have been fully satisfied.
However, during the reversion of the non-spatial attribute checks, the closing arguments for the INFER_ERROR macros on the spatial rates and strides checks were accidentally deleted, resulting in syntax errors that break compilation. Please address the following issues to get this PR green and ready to merge:
1. Fix truncated macro causing C++ build failure
In tensorflow/core/ops/array_ops_test.cc:1472-1473 (ExtractImagePatchesShapeTest), the INFER_ERROR invocation is missing its third argument and the closing parenthesis/semicolon:
set_op({1, 2, 2, 1}, {1, 1, 1, 1}, {1, 1, -1, 1}, "VALID");
INFER_ERROR("ExtractImagePatches requires spatial rates to be positive", op,
"[1,7,7,2]");
}Similarly, in tensorflow/core/ops/array_ops_test.cc:1498-1500 (ExtractVolumePatchesShapeTest), the INFER_ERROR invocation is missing its second and third arguments, as well as the closing parenthesis and semicolon:
set_op({1, 2, 2, 2, 1}, {1, 1, 0, 1, 1}, "VALID");
INFER_ERROR("ExtractVolumePatches requires spatial strides to be positive", op,
"[1,3,3,3,2]");
}2. Python Docstring length (Optional Polish)
The docstrings for testLargeKsizeDynamic exceed the 80-character maximum line length limit. Please shorten or wrap them:
tensorflow/python/kernel_tests/image_ops/extract_image_patches_op_test.py:193tensorflow/python/kernel_tests/image_ops/extract_volume_patches_op_test.py:158
def testLargeKsizeDynamic(self):
"""Tests OpKernel integer overflow using dynamic shapes."""Once the C++ tests compile successfully, this PR will be ready to merge!
Signed-off-by: bodapatisaikrishna <[email protected]>
|
Good catch on the macro calls, my bad on the cleanup mishap. Fixed the closing arguments and shortened the docstrings to stay under 80 chars. |
dmiltr3
left a comment
There was a problem hiding this comment.
Good catch on the macro calls, my bad on the cleanup mishap. Fixed the closing arguments and shortened the docstrings to stay under 80 chars.
Thank you for the excellent fix! The C++ validation perfectly prevents the integer overflow vulnerability and restores parity between the shape function and the runtime OpKernel. The exhaustive eager and graph mode testing looks great.
The spatial attribute validation correctly prevents the fatal CHECK aborts, the BUILD dependency on @com_google_absl//absl/strings is correctly declared, and all carry-over recommendations have been fully satisfied.
The docstrings have been shortened to comply with the 80-character limit, and the INFER_ERROR macros have been fixed.
Great work! I am approving this change.
dmiltr3
left a comment
There was a problem hiding this comment.
Hi! Thanks for the updates.
During internal code review, the following adjustments were requested:
-
Test complete boundary conditions for
ExtractImagePatches:
Intensorflow/core/ops/array_ops_test.cc, you added a test for negative spatial rates (set_op({1, 2, 2, 1}, {1, 1, 1, 1}, {1, 1, -1, 1}, "VALID");). Please also add a test case verifying a zero spatial dilation rate (e.g.set_op({1, 2, 2, 1}, {1, 1, 1, 1}, {1, 1, 0, 1}, "VALID");) alongside it to provide complete boundary test coverage matching theksizesandstrideschecks. -
Remove redundant execution contexts in XLA test:
Intensorflow/compiler/tests/extract_image_patches_op_test.py(testInvalidKernelSize), thewith self.session():andwith self.test_scope():context blocks are redundant because shape inference rejects invalid spatial attributes synchronously withValueErrorduring graph construction (before XLA compilation or session execution begins). Please remove them or add a comment noting their static nature to clarify the test scope.
Could you please make these updates? Thanks!
Signed-off-by: bodapatisaikrishna <[email protected]>
|
Added the zero spatial rate test case to array_ops_test.cc and removed the redundant session/scope contexts from the XLA test. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thanks for the quick update, and sorry: ask 2 in our previous review was wrong.
Retraction
- Ask 2 (remove
with self.session():/with self.test_scope():intestInvalidKernelSize): retracted.array_ops.placeholderonly works in graph mode, and this test class runs eagerly by default. Without the session context, the test now fails before it reaches the op (CI://tensorflow/compiler/tests:extract_image_patches_op_test_*andcombined_ops_test_b_*on CPU and GPU). This was our mistake, not yours.
Final asks
- In
tensorflow/compiler/tests/extract_image_patches_op_test.py, put the graph context back around the placeholder. Keep your newValueErrorassertion, since shape inference now rejects the attribute while the graph is built:
def testInvalidKernelSize(self):
"""Test that zero kernel size is rejected by shape inference."""
with self.session():
image_placeholder = array_ops.placeholder(dtypes.float32)
with self.assertRaisesRegex(
ValueError,
"ExtractImagePatches requires spatial ksizes to be positive",
):
array_ops.extract_image_patches(
image_placeholder,
ksizes=[1, 0, 2, 1],
strides=[1, 1, 1, 1],
rates=[1, 1, 1, 1],
padding="VALID",
)Ask 1 (the zero spatial rate case in array_ops_test.cc) is done. This is the only remaining change; once CI is green on it, we will approve.
Signed-off-by: bodapatisaikrishna <[email protected]>
|
Restored with self.session(): in the XLA test |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the excellent fix! The C++ validation perfectly prevents the integer overflow vulnerability and restores parity between the shape function and the runtime OpKernel. The exhaustive eager and graph mode testing looks great.
The spatial attribute validation correctly prevents the fatal aborts, the BUILD dependency on @com_google_absl//absl/strings is correctly declared, and all carry-over recommendations have been fully satisfied.
The zero-value spatial rate boundary test coverage in array_ops_test.cc is now complete, and the required test cases have been incorporated. Additionally, the session context in the XLA test (extract_image_patches_op_test.py) has been correctly retained as required.
Great work! I am approving this change.
5d0c3f1
into
tensorflow:master
Calling
tf.raw_ops.ExtractImagePatcheswith non-positive spatial attributes (such asksizes=[1, -1, 2, 1]) passes negative values toInferenceContext::Multiply/DimensionOrConstant, triggering a fatalCHECKabort in debug builds (Check failed: val >= 0 || val == InferenceContext::kUnknownDim). In release builds, negative dimensions propagate into graph construction, leading to corrupted shapes or crashes. Reported in #63067.Reproducer
Before this change:
Debug build triggers
CHECKfailure and aborts:After this change:
During graph construction, shape inference rejects non-positive spatial attributes with
ValueError: ExtractImagePatches requires spatial ksizes to be positive.... In eager mode, the kernel constructor raisesOutOfRangeError.Root Cause
In
tensorflow/core/ops/array_ops.cc, the shape inference functions forExtractImagePatchesandExtractVolumePatchesvalidated attribute vector lengths (size() == 4or5), but did not validate that spatial attributes are positive integers before passing them toc->Multiply()andGetWindowedOutputSizeVerbose().Solution
ExtractImagePatchesshape inference checking that spatialksizes,strides, andrates(indices 1 and 2) are positive (> 0), returningabsl::InvalidArgumentErrorotherwise.ExtractVolumePatchesshape inference for spatialksizesandstrides(indices 1, 2, and 3).tensorflow/core/ops/array_ops_test.ccfor both ops.extract_image_patches_op_test.pyandextract_volume_patches_op_test.pycovering both eager execution (OutOfRangeError) and graph mode shape inference (ValueError).testInvalidKernelSizeintensorflow/compiler/tests/extract_image_patches_op_test.pyto expectValueErrorduring graph construction and removed unusederrors_implimport.Fixes #63067.