Skip to content

Validate spatial attributes in ExtractImagePatches and ExtractVolumePatches shape inference - #128388

Merged
copybara-service[bot] merged 8 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/63067-extract-image-patches-shape-validation
Oct 7, 2026
Merged

copybara-service[bot] merged 8 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/63067-extract-image-patches-shape-validation

Conversation

@bodapatisaikrishna

@bodapatisaikrishna bodapatisaikrishna commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Calling tf.raw_ops.ExtractImagePatches with non-positive spatial attributes (such as ksizes=[1, -1, 2, 1]) passes negative values to InferenceContext::Multiply / DimensionOrConstant, triggering a fatal CHECK abort 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

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

# Spatial ksizes contains negative value
tf.raw_ops.ExtractImagePatches(
    images=tf.random.normal([1, 1, 1, 1]),
    ksizes=[1, -1, 2, 1],
    strides=[1, 1, 1, 1],
    rates=[1, 1, 1, 1],
    padding="VALID",
)

Before this change:
Debug build triggers CHECK failure and aborts:

F ./tensorflow/core/framework/shape_inference.h:891] Check failed: val >= 0 || val == InferenceContext::kUnknownDim
Dimension must be non-negative or equal to InferenceContext::kUnknownDim but got -2
Aborted (core dumped)

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 raises OutOfRangeError.

Root Cause

In tensorflow/core/ops/array_ops.cc, the shape inference functions for ExtractImagePatches and ExtractVolumePatches validated attribute vector lengths (size() == 4 or 5), but did not validate that spatial attributes are positive integers before passing them to c->Multiply() and GetWindowedOutputSizeVerbose().

Solution

  • Added explicit validation in ExtractImagePatches shape inference checking that spatial ksizes, strides, and rates (indices 1 and 2) are positive (> 0), returning absl::InvalidArgumentError otherwise.
  • Added corresponding checks in ExtractVolumePatches shape inference for spatial ksizes and strides (indices 1, 2, and 3).
  • Added C++ shape inference test cases in tensorflow/core/ops/array_ops_test.cc for both ops.
  • Added unit tests in extract_image_patches_op_test.py and extract_volume_patches_op_test.py covering both eager execution (OutOfRangeError) and graph mode shape inference (ValueError).
  • Updated XLA test testInvalidKernelSize in tensorflow/compiler/tests/extract_image_patches_op_test.py to expect ValueError during graph construction and removed unused errors_impl import.

Fixes #63067.

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@nithyak0204 nithyak0204 self-assigned this Oct 5, 2026
@nithyak0204
nithyak0204 requested a review from a team October 5, 2026 04:18
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 5, 2026
@nithyak0204 nithyak0204 added the prtype:bugfix PR to fix a bug label Oct 5, 2026
@dmiltr3
dmiltr3 self-requested a review October 5, 2026 06:17

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Pushed updates for the eager and graph test cases, added the C++ shape tests, and updated the XLA test and PR description.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  1. Missing IWYU include: tensorflow/core/ops/array_ops.cc uses absl::StrCat but is missing the #include "absl/strings/str_cat.h" header. Please add this include.

  2. ExtractVolumePatches rank bug: In tensorflow/core/ops/array_ops.cc:2846, the ExtractVolumePatches unknown-spatial-dims branch incorrectly returns a rank-4 shape instead of rank-5. Please fix this by using ShapeHandle 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.

  3. Missing non-spatial index validation: In tensorflow/core/ops/array_ops.cc:2685 and 2798, 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 of ksizes, strides, and rates are exactly 1.

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]>
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

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 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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!

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Wrapped the long lines in both test files to stay within the 80-column limit and verified with pylint.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  1. Remove Non-Spatial Parity Checks: As noted above, please remove the non-spatial attribute validation blocks (ksizes[0] != 1, etc.) that were added to the ExtractImagePatches and ExtractVolumePatches shape functions in tensorflow/core/ops/array_ops.cc, along with the corresponding tests (testNonSpatialAttributes and the related assertions in array_ops_test.cc).
  2. 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 the deps of the array_ops rule in tensorflow/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!

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

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 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:193
  • tensorflow/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!

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

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 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Oct 6, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hi! Thanks for the updates.

During internal code review, the following adjustments were requested:

  1. Test complete boundary conditions for ExtractImagePatches:
    In tensorflow/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 the ksizes and strides checks.

  2. Remove redundant execution contexts in XLA test:
    In tensorflow/compiler/tests/extract_image_patches_op_test.py (testInvalidKernelSize), the with self.session(): and with self.test_scope(): context blocks are redundant because shape inference rejects invalid spatial attributes synchronously with ValueError during 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!

@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Oct 6, 2026
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Added the zero spatial rate test case to array_ops_test.cc and removed the redundant session/scope contexts from the XLA test.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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(): in testInvalidKernelSize): retracted. array_ops.placeholder only 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_* and combined_ops_test_b_* on CPU and GPU). This was our mistake, not yours.

Final asks

  1. In tensorflow/compiler/tests/extract_image_patches_op_test.py, put the graph context back around the placeholder. Keep your new ValueError assertion, 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.

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Restored with self.session(): in the XLA test

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@google-ml-butler google-ml-butler Bot added the ready to pull PR ready for merge process label Oct 7, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Oct 7, 2026
@copybara-service
copybara-service Bot merged commit 5d0c3f1 into tensorflow:master Oct 7, 2026
15 of 16 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

prtype:bugfix PR to fix a bug ready to pull PR ready for merge process size:M CL Change Size: Medium

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

tf.raw_ops.ExtractImagePatches: Assertion failure in shape inference step

3 participants