Skip to content

Add regression tests for conv2d input and filter ranks - #128598

Merged
copybara-service[bot] merged 8 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/77336-conv2d-invalid-rank-crash
Oct 9, 2026
Merged

copybara-service[bot] merged 8 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/77336-conv2d-invalid-rank-crash

Conversation

@bodapatisaikrishna

@bodapatisaikrishna bodapatisaikrishna commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Passing input or filter tensors with rank < 4 to tf.nn.conv2d originally reported crashes in eager execution (#77336). Existing C++ kernel and shape inference protections already validate these dimensions (ComputeConv2DDimension).

Changes

  • Added regression tests in conv_ops_test.py covering invalid input and filter shapes ([(), (1,), (1, 1), (1, 1, 3)]) across both tf.nn.conv2d and gen_nn_ops.Conv2D.

Fixes #77336.

When inputs or filters with rank < 4 are passed to tf.nn.conv2d in eager
execution, execution proceeds to C++ kernel dimension index lookup where
GetTensorDimIndex triggers a fatal CHECK failure in tensor_format.h,
crashing the process instead of raising a catchable exception.

Validate that input and filter have rank at least 4 in tf.nn.conv2d before
calling the internal op, raising a ValueError with clear rank information.

Fixes tensorflow#77336

Signed-off-by: bodapatisaikrishna <[email protected]>
@google-ml-butler google-ml-butler Bot added the size:S CL Change Size: Small label Oct 7, 2026
@google-ml-butler
google-ml-butler Bot requested a review from cantonios October 7, 2026 16:10
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 7, 2026

@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 and filter rank validation to tf.nn.conv2d, ensuring both have a rank of at least 4 and raising a ValueError otherwise. It also adds corresponding unit tests to verify this behavior. The review feedback suggests simplifying the filter rank extraction and validation logic in tensorflow/python/ops/nn_ops.py to remove redundant checks and improve readability.

Comment thread tensorflow/python/ops/nn_ops.py Outdated
Comment on lines +2677 to +2687
filter_shape = getattr(filter, "shape", None)
filter_ndims = (
getattr(filter_shape, "ndims", -1) if filter_shape is not None else -1
)
if filter_ndims == -1 and filter_shape is not None:
filter_ndims = len(filter_shape)
if filter_ndims is not None and filter_ndims != -1 and filter_ndims < 4:
raise ValueError(
f"`filter.shape.rank` must be at least 4. "
f"Received: filter.shape={filter_shape} with rank {filter_ndims}."
)

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.

medium

The logic for extracting and validating the filter rank is unnecessarily complex and contains redundant checks (such as filter_ndims != -1 in the final condition, which is already handled). We can simplify this to be cleaner, more readable, and consistent with how ndims is processed.

  filter_shape = getattr(filter, "shape", None)
  if filter_shape is not None:
    filter_ndims = getattr(filter_shape, "ndims", -1)
    if filter_ndims == -1:
      filter_ndims = len(filter_shape)
    if filter_ndims is not None and filter_ndims < 4:
      raise ValueError(
          f"`filter.shape.rank` must be at least 4. "
          f"Received: filter.shape={filter_shape} with rank {filter_ndims}."
      )
References
  1. Flag issues only when they affect clarity or long-term maintainability. (link)

@nithyak0204 nithyak0204 self-assigned this Oct 8, 2026
@nithyak0204
nithyak0204 requested a review from a team October 8, 2026 06:28
@nithyak0204 nithyak0204 added prtype:bugfix PR to fix a bug python Pull requests that update Python code labels Oct 8, 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.

The current fix addresses the crash by adding rank validation in the Python tf.nn.conv2d wrapper. However, TensorFlow architectural directives require that input validation (such as shape and rank preconditions) be placed in the C++ OpKernel::Compute or C++ shape functions, not in the Python wrappers.

  1. Incomplete Validation & Bypassed Checks: The Python-level checks in tensorflow/python/ops/nn_ops.py:2671-2686 are bypassed if a user calls tf.raw_ops.Conv2D directly, or if the tensor has a dynamically unknown rank (input.shape.rank is None). In those cases, the invalid input still reaches the C++ backend and triggers the fatal CHECK abort.
  2. Green-Path Performance: Adding Python attribute reflection (getattr, len) on every valid call to tf.nn.conv2d introduces overhead on the eager dispatch fast path.

Please completely remove the added Python-level ValueError checks from tensorflow/python/ops/nn_ops.py. Instead, implement the bounds checking in the C++ kernel (e.g., in Conv2DOp::Compute or before GetTensorDimIndex is invoked) using OP_REQUIRES. This ensures that all execution paths, including raw_ops, SavedModels, and dynamic shapes, are protected.

Additionally, the newly added tests in tensorflow/python/kernel_tests/nn_ops/conv_ops_test.py have lines exceeding the 80-character limit, causing PyLint CI failures. Once the validation is moved to C++, the tests should expect the InvalidArgumentError raised by the kernel, and we should also test raw_ops.Conv2D to ensure the C++ boundary is secure.

Please apply the following update to your tests, which corrects the exception types, fixes the 80-character lint violation, and adds raw op coverage:

<<<<
    # Invalid input or filter rank (< 4) in eager/graph execution.
    with self.assertRaisesRegex(ValueError, "`input.shape.rank` must be at least 4"):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3], dtype=np.float32),
              np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
    with self.assertRaisesRegex(ValueError, "`filter.shape.rank` must be at least 4"):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3, 3], dtype=np.float32),
              np.ones([1, 2, 2], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
====
    # Invalid input or filter rank (< 4) in eager/graph execution.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be at least 4-dimensional|input\.shape\.rank)",
    ):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3], dtype=np.float32),
              np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be at least 4-dimensional|filter\.shape\.rank)",
    ):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3, 3], dtype=np.float32),
              np.ones([1, 2, 2], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )

    # Ensure raw ops are protected by the C++ kernel boundary.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be at least 4-dimensional|input\.shape\.rank)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1, 1, 3], dtype=np.float32),
              filter=np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
>>>>

Move rank validation from python wrapper into Conv2DOp kernel boundary
to prevent crashes on raw ops and dynamic shapes, and update tests.

Signed-off-by: bodapatisaikrishna <[email protected]>
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

moved the rank checks to the C++ kernel boundary and removed the Python validation. Updated the tests with the raw op coverage and fixed the line lengths.

@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 review mistakenly asked for OP_REQUIRES rank checks to be added directly to Conv2DOp::Compute. However, ComputeConv2DDimension already enforces the exact same checks prior to any dimension queries, safely returning an error. Adding redundant logic violates the Minimal-Diff Alternative directive. Please completely revert the changes made to tensorflow/core/kernels/conv_ops_impl.h.

Thank you for the updates! The Python-level overhead has been successfully removed, and the C++ backend remains fully protected. However, there are a couple of remaining issues to address:

  1. Redundant C++ Rank Validation: The new OP_REQUIRES checks added to Conv2DOp::Compute are redundant. The helper ComputeConv2DDimension (invoked at line 681) already strictly validates input.dims() and filter.dims() before making any dimension queries and returns an InvalidArgumentError which is caught by OP_REQUIRES_OK. Please revert the additions in tensorflow/core/kernels/conv_ops_impl.h to restore minimal-diff principles.
  2. Incomplete Regex Causes Graph-Mode Test Failure: The negative tests for invalid ranks currently fail in graph mode. During graph construction, the static shape inference function (Conv2DShapeImpl) triggers the failure earlier than the runtime kernel and throws "Shape must be rank 4 but is rank 3...", which does not match the current regular expression. The regex needs to be expanded to match the shape inference exception as well, while removing the dead alternations for the old Python checks.

Please apply the following update to your tests to fix the regex and add a symmetric test for raw_ops.Conv2D with an invalid filter tensor:

<<<<
    # Invalid input or filter rank (< 4) in eager/graph execution.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be (at least )?4-dimensional|input\.shape\.rank)",
    ):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3], dtype=np.float32),
              np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be (at least )?4-dimensional|filter\.shape\.rank)",
    ):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3, 3], dtype=np.float32),
              np.ones([1, 2, 2], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )

    # Ensure raw ops are protected by the C++ kernel boundary.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be (at least )?4-dimensional|input\.shape\.rank)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1, 1, 3], dtype=np.float32),
              filter=np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )

    # Filter dimensions must be greater than 0.
====
    # Invalid input or filter rank (< 4) in eager/graph execution.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be (at least )?4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3], dtype=np.float32),
              np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be (at least )?4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3, 3], dtype=np.float32),
              np.ones([1, 2, 2], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )

    # Ensure raw ops are protected by the C++ kernel boundary.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be (at least )?4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1, 1, 3], dtype=np.float32),
              filter=np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be (at least )?4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1, 1, 3, 3], dtype=np.float32),
              filter=np.ones([1, 2, 2], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )

    # Filter dimensions must be greater than 0.
>>>>

@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Oct 8, 2026
Revert OP_REQUIRES checks from Conv2DOp::Compute since ComputeConv2DDimension
already enforces required dimensions, and update tests to cover graph mode
shape inference and raw_ops filter rank validation.

Signed-off-by: bodapatisaikrishna <[email protected]>
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Reverted the kernel changes in conv_ops_impl.h and updated the test regex to catch the graph-mode shape inference error. Also added the raw op check for invalid filter rank.

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Oct 8, 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.

Thank you for the updates! The changes successfully implement robust test coverage for invalid input and filter ranks in tf.nn.conv2d and raw_ops.Conv2D, correctly match both eager exceptions and graph-resumed shape inference errors, and cleanly revert the redundant checks.

There is one minor cleanup: the exception regex still contains the dead (at least )? python alternation from the reverted Python-level checks. Since the C++ kernel throws exactly "convolution input must be 4-dimensional" without "at least", we can remove that alternation.

Please apply the following update to your tests to clean up the regex:

<<<<
    # Invalid input or filter rank (< 4) in eager/graph execution.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be (at least )?4-dimensional|"
        r"Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3], dtype=np.float32),
              np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be (at least )?4-dimensional|"
        r"Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3, 3], dtype=np.float32),
              np.ones([1, 2, 2], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )

    # Ensure raw ops are protected by the C++ kernel boundary.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be (at least )?4-dimensional|"
        r"Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1, 1, 3], dtype=np.float32),
              filter=np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be (at least )?4-dimensional|"
        r"Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1, 1, 3, 3], dtype=np.float32),
              filter=np.ones([1, 2, 2], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
====
    # Invalid input or filter rank (< 4) in eager/graph execution.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3], dtype=np.float32),
              np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          nn_ops.conv2d(
              np.ones([1, 1, 3, 3], dtype=np.float32),
              np.ones([1, 2, 2], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )

    # Ensure raw ops are protected by the C++ kernel boundary.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1, 1, 3], dtype=np.float32),
              filter=np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1, 1, 3, 3], dtype=np.float32),
              filter=np.ones([1, 2, 2], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
>>>>

@nithyak0204 nithyak0204 added the stat:awaiting response Status - Awaiting response from author label Oct 8, 2026
Remove dead alternation from regex to strictly match the C++ kernel error
and graph mode shape inference error.

Signed-off-by: bodapatisaikrishna <[email protected]>
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Cleaned up the regex to remove (at least )? and match the exact kernel and shape inference errors.

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Oct 8, 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.

Correction to our earlier review: In previous review rounds, we provided test snippets that hardcoded the regex to match exactly is rank 3 (r"(must be 4-dimensional|Shape must be rank 4 but is rank 3)"). This was a mistake and violates our directive for robust negative testing. We must not hardcode the rank in the regex to 3, because inputs of rank 0, 1, or 2 will throw a different number (e.g., "Shape must be rank 4 but is rank 2"), which would cause the test to fail falsely. We retract the previous snippet's exact match requirement.

P1: Brittle Negative-Test Regex

  • File: tensorflow/python/kernel_tests/nn_ops/conv_ops_test.py:3138-3178
  • Rationale: The exception regex r"(must be 4-dimensional|Shape must be rank 4 but is rank 3)" explicitly hardcodes rank 3. If this test (or a future variant) is executed with a rank-2 or rank-1 tensor, the shape inference error will say "Shape must be rank 4 but is rank 2", causing the test assertion to fail and breaking the build. Please generalize the regex to is rank \d+ so it matches any invalid rank.

Please replace all 4 instances of the regex across the test block with the generalized version:

<<<<
    # Invalid input or filter rank (< 4) in eager/graph execution.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
====
    # Invalid input or filter rank (< 4) in eager/graph execution.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank \d+)",
    ):
>>>>
<<<<
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
====
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank \d+)",
    ):
>>>>
<<<<
    # Ensure raw ops are protected by the C++ kernel boundary.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
====
    # Ensure raw ops are protected by the C++ kernel boundary.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank \d+)",
    ):
>>>>
<<<<
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank 3)",
    ):
====
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank \d+)",
    ):
>>>>

Update regex to match any invalid rank in graph-mode shape inference.

Signed-off-by: bodapatisaikrishna <[email protected]>
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Updated the regex across all 4 test cases to is rank \d+.

@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 changes successfully use the robust r"(must be 4-dimensional|Shape must be rank 4 but is rank \d+)" regex, providing safe and robust error matching.

However, there is one remaining finding regarding test coverage completeness requested in the previous review round.

P1: Missing test matrix completeness (scalar and rank-1 edge cases)

  • File: tensorflow/python/kernel_tests/nn_ops/conv_ops_test.py:3176-3188
  • Rationale: To guarantee that the static shape inference code and kernel entry routines safely error out before making any invalid dimension indexing assumptions, we must test the extreme boundaries of the rank checks. The current suite verifies rank-3, but we still need negative tests for scalar (rank-0) and rank-1 tensors.

Please apply the following snippet to add the missing scalar and rank-1 coverage before the zero-element filter test:

<<<<
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank \d+)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1, 1, 3, 3], dtype=np.float32),
              filter=np.ones([1, 2, 2], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )

    # Filter dimensions must be greater than 0.
====
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank \d+)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1, 1, 3, 3], dtype=np.float32),
              filter=np.ones([1, 2, 2], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )

    # Ensure scalar and rank-1 inputs fail safely.
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank \d+)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1], dtype=np.float32),
              filter=np.ones([1, 2, 2, 1], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )
    with self.assertRaisesRegex(
        (ValueError, errors_impl.InvalidArgumentError),
        r"(must be 4-dimensional|Shape must be rank 4 but is rank \d+)",
    ):
      self.evaluate(
          raw_ops.Conv2D(
              input=np.ones([1, 1, 3, 3], dtype=np.float32),
              filter=np.ones([], dtype=np.float32),
              strides=[1, 1, 1, 1],
              padding="VALID",
          )
      )

    # Filter dimensions must be greater than 0.
>>>>

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Added the scalar and rank-1 raw op cases.

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

This pull request correctly adds robust negative test coverage for rank validation in 2D convolution ops without introducing redundant validation overhead. By relying on the existing C++ kernel boundaries and static shape inference, the changes enforce the correct invariants while keeping the eager dispatch fast-path clean. The exception matching is also robust across both eager and graph modes.

The changes look great. Thank you!

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

Thank you for the updates. We have a few final suggestions for the tests:

  1. Test Consolidation: The added test cases repeat the same assertRaisesRegex block 6 times while leaving test coverage asymmetric (e.g. rank-1 is tested on input but scalar on filter). Consider refactoring this into a compact parameterized loop over invalid shapes [(), (1,), (1, 1), (1, 1, 3)] for both nn_ops.conv2d and gen_nn_ops.Conv2D. This eliminates boilerplate and provides symmetric coverage. Example:

    invalid_shapes = [(), (1,), (1, 1), (1, 1, 3)]
    for op in (nn_ops.conv2d, gen_nn_ops.Conv2D):
      for bad_shape in invalid_shapes:
        with self.assertRaisesRegex(
            (ValueError, errors_impl.InvalidArgumentError),
            r"(must be 4-dimensional|Shape must be rank 4 but is rank \d+)",
        ):
          # ... test input=bad_shape ...
          # ... test filter=bad_shape ...
  2. Redundant Alias: In conv_ops_test.py at line 50, please remove raw_ops = gen_nn_ops and reference gen_nn_ops.Conv2D directly inside the tests, as gen_nn_ops is already imported at line 35.

  3. PR Description: Since the Python-side validation checks were reverted and this is now a test-only change, please update the PR description to reflect that it adds regression tests for the existing C++ kernel protections.

Please let us know once these updates are applied so we can proceed with merging. Thanks!

@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Oct 9, 2026
@bodapatisaikrishna bodapatisaikrishna changed the title Validate input and filter ranks in tf.nn.conv2d Add regression tests for conv2d input and filter ranks Oct 9, 2026
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Refactored the tests into a parameterized loop, removed the alias, and updated the PR description. Thanks!

@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 final requests have been addressed and all tests are passing. Approving.

@google-ml-butler google-ml-butler Bot added the ready to pull PR ready for merge process label Oct 9, 2026
@nithyak0204 nithyak0204 removed the kokoro:force-run Tests on submitted change label Oct 9, 2026
@copybara-service
copybara-service Bot merged commit db9c333 into tensorflow:master Oct 9, 2026
14 of 16 checks passed
bodapatisaikrishna added a commit to bodapatisaikrishna/bodapatisaikrishna that referenced this pull request Oct 9, 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 python Pull requests that update Python code ready to pull PR ready for merge process size:S CL Change Size: Small

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

tf.nn.conv2d terminates process with invalid input shape instead of raising an exception

3 participants