Repository navigation
Add regression tests for conv2d input and filter ranks - #128598
copybara-service[bot] merged 8 commits into
Conversation
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]>
There was a problem hiding this comment.
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.
| 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}." | ||
| ) |
There was a problem hiding this comment.
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
- Flag issues only when they affect clarity or long-term maintainability. (link)
Signed-off-by: bodapatisaikrishna <[email protected]>
dmiltr3
left a comment
There was a problem hiding this comment.
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.
- Incomplete Validation & Bypassed Checks: The Python-level checks in
tensorflow/python/ops/nn_ops.py:2671-2686are bypassed if a user callstf.raw_ops.Conv2Ddirectly, 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 fatalCHECKabort. - Green-Path Performance: Adding Python attribute reflection (
getattr,len) on every valid call totf.nn.conv2dintroduces 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]>
|
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
left a comment
There was a problem hiding this comment.
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:
- Redundant C++ Rank Validation: The new
OP_REQUIRESchecks added toConv2DOp::Computeare redundant. The helperComputeConv2DDimension(invoked at line 681) already strictly validatesinput.dims()andfilter.dims()before making any dimension queries and returns anInvalidArgumentErrorwhich is caught byOP_REQUIRES_OK. Please revert the additions intensorflow/core/kernels/conv_ops_impl.hto restore minimal-diff principles. - 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.
>>>>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]>
|
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. |
dmiltr3
left a comment
There was a problem hiding this comment.
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",
)
)
>>>>Remove dead alternation from regex to strictly match the C++ kernel error and graph mode shape inference error. Signed-off-by: bodapatisaikrishna <[email protected]>
|
Cleaned up the regex to remove (at least )? and match the exact kernel and shape inference errors. |
dmiltr3
left a comment
There was a problem hiding this comment.
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 hardcodesrank 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 tois 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]>
|
Updated the regex across all 4 test cases to is rank \d+. |
dmiltr3
left a comment
There was a problem hiding this comment.
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.
>>>>|
Added the scalar and rank-1 raw op cases. |
dmiltr3
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Thank you for the updates. We have a few final suggestions for the tests:
-
Test Consolidation: The added test cases repeat the same
assertRaisesRegexblock 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 bothnn_ops.conv2dandgen_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 ...
-
Redundant Alias: In
conv_ops_test.pyat line 50, please removeraw_ops = gen_nn_opsand referencegen_nn_ops.Conv2Ddirectly inside the tests, asgen_nn_opsis already imported at line 35. -
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!
Signed-off-by: bodapatisaikrishna <[email protected]>
|
Refactored the tests into a parameterized loop, removed the alias, and updated the PR description. Thanks! |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates! The final requests have been addressed and all tests are passing. Approving.
db9c333
into
tensorflow:master
Passing input or filter tensors with rank < 4 to
tf.nn.conv2doriginally reported crashes in eager execution (#77336). Existing C++ kernel and shape inference protections already validate these dimensions (ComputeConv2DDimension).Changes
conv_ops_test.pycovering invalid input and filter shapes ([(), (1,), (1, 1), (1, 1, 3)]) across bothtf.nn.conv2dandgen_nn_ops.Conv2D.Fixes #77336.