Repository navigation
fix: validate input rank before reading dims in LSTMBlockCell kernels - #124034
copybara-service[bot] merged 5 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces input tensor rank validation checks in both LSTMBlockCellOp and LSTMBlockCellGradOp to prevent process crashes caused by out-of-bounds dimension accesses on invalid-rank inputs. It also adds corresponding regression tests in Python. The review feedback suggests adding missing rank checks for peephole weight tensors (wci_tensor, wcf_tensor, wco_tensor) and an empty check for cs_prev_tensor in LSTMBlockCellGradOp to ensure consistency and prevent potential crashes.
|
Added a |
sgarciagoogle
left a comment
There was a problem hiding this comment.
Thank you for the pull request and for addressing the review comments!
To get this merged into the codebase, could you please revert/drop the change to RELEASE.md (commit 5ee3a77)? Release notes for the 2.22.0 release will be curated internally by the release team.
Once RELEASE.md is removed from the PR we'll be happy to review again. Thank you!
5ee3a77 to
d6c35cc
Compare
|
@sgarciagoogle Done — Understood on the release notes being curated internally; I will leave RELEASE.md alone on my other PRs as well. |
|
Hi @Ashutosh0x, Can you please resolve the conflicts? Thank you! |
d6c35cc to
793cd0b
Compare
LSTMBlockCellOp read x_tensor->dim_size(1) and cs_prev_tensor->dim_size(1) before its rank checks ran, so a rank 1 input aborted the process with "Check failed: d < dims()" instead of returning InvalidArgument. Validate the input ranks with a check_rank lambda, as LSTMBlockCellGradOp now does, before any dimension is read, and drop the later duplicate checks. LSTMBlockCellGradOp did not reject an empty cs_prev, which gives LSTMBlockCellBpropWithCUDA a zero-sized launch configuration that aborts via TF_CHECK_OK. Reject it as the forward op does. The tests feed the offending input through an unknown-shape signature so that the kernel check, not the shape function, is what they exercise. Fixes tensorflow#113069 Fixes tensorflow#113071
793cd0b to
2bb2150
Compare
|
@dmiltr3 Thanks for the review. Addressed in 2bb2150, rebased onto current master:
|
dmiltr3
left a comment
There was a problem hiding this comment.
Correction to our earlier review: The previous review requested the removal of lines 630-708 in LSTMBlockCellGradOp::Compute on the grounds that they were redundant rank checks. This was incorrect; those lines are actually dimension size matching checks (e.g., cs_prev_tensor->dim_size(0) == batch_size), which are critical to prevent silent buffer overflows. You correctly ignored that advice, and we apologize for the confusion. Please leave those checks in place.
Thank you for the updates! The PR now correctly prevents CHECK failures on invalid ranks and handles the empty cs_prev edge case without adding overhead. We have two remaining findings to fully secure the peephole weights and clean up some dead code.
1. Missing size validation for peephole weights
While the PR checks that the peephole weights (wci, wcf, wco) are rank 1 to avoid vec<T>() crashes, it never checks that their sizes match cell_size. Passing a 1D tensor of the wrong size will cause an out-of-bounds assert or memory corruption during Eigen multiplication.
Please validate their sizes in both LSTMBlockCellOp and LSTMBlockCellGradOp alongside the existing b_tensor checks.
In tensorflow/core/kernels/rnn/lstm_ops.cc, around line 397 (and similarly in LSTMBlockCellGradOp around line 660), immediately after b_tensor->dim_size(0) == cell_size * 4 is validated, add:
OP_REQUIRES(ctx, wci_tensor->dim_size(0) == cell_size,
absl::InvalidArgumentError(absl::StrCat(
"wci.dim_size(0) != cell_size: ", wci_tensor->dim_size(0),
" vs. ", cell_size)));
OP_REQUIRES(ctx, wcf_tensor->dim_size(0) == cell_size,
absl::InvalidArgumentError(absl::StrCat(
"wcf.dim_size(0) != cell_size: ", wcf_tensor->dim_size(0),
" vs. ", cell_size)));
OP_REQUIRES(ctx, wco_tensor->dim_size(0) == cell_size,
absl::InvalidArgumentError(absl::StrCat(
"wco.dim_size(0) != cell_size: ", wco_tensor->dim_size(0),
" vs. ", cell_size)));Please also add corresponding deterministic tests to reach these branches in tensorflow/python/ops/rnn_grad_test.py:
def testLSTMBlockCellInvalidPeepholeSize(self):
kwargs = self._lstm_block_cell_inputs()
kwargs["wci"] = deterministic_random_uniform([3])
with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
r"wci.dim_size\(0\) != cell_size"):
self._run_with_unknown_shape(
gen_rnn_ops.lstm_block_cell, "wci", use_peephole=True, **kwargs)
def testLSTMBlockCellGradInvalidPeepholeSize(self):
kwargs = self._lstm_block_cell_grad_inputs()
kwargs["wci"] = deterministic_random_uniform([3])
with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
r"wci.dim_size\(0\) != cell_size"):
self._run_with_unknown_shape(
gen_rnn_ops.lstm_block_cell_grad, "wci", use_peephole=False, **kwargs)2. Dead code from redundant temp/output tensor rank checks (Nit)
In LSTMBlockCellOp, you successfully removed the duplicate input rank checks. However, lines 454-489 still contain rank checks for tensors like xh_tensor, i_tensor, cs_tensor, etc. These tensors are allocated just a few lines above via allocate_temp, allocate_output, or forward_input_or_allocate_output with explicit 2D TensorShape specifications. It is mathematically impossible for them to not be rank 2. Since you are already refactoring the rank validation in this op, please clean up these redundant checks as well.
In tensorflow/core/kernels/rnn/lstm_ops.cc, please delete the block from line 454 to line 489:
// Sanity check that each of the tensors have the required NDIMS.
OP_REQUIRES(
ctx, xh_tensor.dims() == 2,
absl::InvalidArgumentError(absl::StrCat(
"xh_tensor must be rank 2 but is rank ", xh_tensor.dims(), ".")));
OP_REQUIRES(
ctx, i_tensor->dims() == 2,
...
OP_REQUIRES(
ctx, h_tensor->dims() == 2,
absl::InvalidArgumentError(absl::StrCat(
"h_tensor must be rank 2 but is rank ", h_tensor->dims(), ".")));LSTMBlockCellOp and LSTMBlockCellGradOp checked that wci, wcf and wco are rank 1 but not that their length is cell_size. A wrong length is broadcast against [batch_size, cell_size] tensors, and in the gradient wci_grad is allocated with the shape of wci but written with cell_size elements. Reject it alongside the existing b size check. Remove the rank checks on LSTMBlockCellOp's temp and output tensors. They are allocated with explicit two-dimensional shapes just above, so the checks cannot fail.
|
@dmiltr3 Thanks, both addressed in dbc0789:
The grad op's dimension-matching block is untouched. The two CUDA failures are unrelated: both stop compiling |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates! The PR now successfully prevents CHECK failures on invalid ranks and handles the empty cs_prev edge case. The peephole weight size validations in LSTMBlockCellOp and LSTMBlockCellGradOp are correct. However, we have a few remaining findings to fully secure all sibling kernels and complete the test matrix.
1. Missing peephole size check in BlockLSTMGradOp (P1)
While size validation for wci, wcf, and wco was correctly added to LSTMBlockCellOp and LSTMBlockCellGradOp, the sibling kernel BlockLSTMGradOp remains vulnerable to the same out-of-bounds access bug class. It checks that wci, wcf, and wco are rank 1 (tensorflow/core/kernels/rnn/lstm_ops.cc:1234-1250) but never verifies that their sizes match cell_size.
Please add the size checks to BlockLSTMGradOp and test them. In tensorflow/core/kernels/rnn/lstm_ops.cc around line 1238:
const Tensor* wci_tensor = nullptr;
OP_REQUIRES_OK(ctx, ctx->input("wci", &wci_tensor));
OP_REQUIRES(ctx, wci_tensor->dims() == 1,
absl::InvalidArgumentError(absl::StrCat(
"wci must be rank 1 but is rank ", wci_tensor->dims())));
OP_REQUIRES(ctx, wci_tensor->dim_size(0) == cell_size,
absl::InvalidArgumentError(absl::StrCat(
"wci.dim_size(0) != cell_size: ", wci_tensor->dim_size(0),
" vs. ", cell_size)));
const Tensor* wcf_tensor = nullptr;
OP_REQUIRES_OK(ctx, ctx->input("wcf", &wcf_tensor));
OP_REQUIRES(ctx, wcf_tensor->dims() == 1,
absl::InvalidArgumentError(absl::StrCat(
"wcf must be rank 1 but is rank ", wcf_tensor->dims())));
OP_REQUIRES(ctx, wcf_tensor->dim_size(0) == cell_size,
absl::InvalidArgumentError(absl::StrCat(
"wcf.dim_size(0) != cell_size: ", wcf_tensor->dim_size(0),
" vs. ", cell_size)));
const Tensor* wco_tensor = nullptr;
OP_REQUIRES_OK(ctx, ctx->input("wco", &wco_tensor));
OP_REQUIRES(ctx, wco_tensor->dims() == 1,
absl::InvalidArgumentError(absl::StrCat(
"wco must be rank 1 but is rank ", wco_tensor->dims())));
OP_REQUIRES(ctx, wco_tensor->dim_size(0) == cell_size,
absl::InvalidArgumentError(absl::StrCat(
"wco.dim_size(0) != cell_size: ", wco_tensor->dim_size(0),
" vs. ", cell_size)));Please also add a corresponding deterministic test in tensorflow/python/ops/rnn_grad_test.py:
def testBlockLSTMGradInvalidPeepholeSize(self):
for name in ["wci", "wcf", "wco"]:
w, b, x, cs_prev, h_prev, w_peephole = self._block_lstm_inputs()
i, cs, f, o, ci, co, h = self._block_lstm(
w, b, x, cs_prev, h_prev, w_peephole, seq_len_max=x.shape[0])
kwargs = dict(
seq_len_max=math_ops.cast(x.shape[0], dtypes.int64),
x=x, cs_prev=cs_prev, h_prev=h_prev, w=w,
wci=w_peephole, wcf=w_peephole, wco=w_peephole, b=b,
i=i, cs=cs, f=f, o=o, ci=ci, co=co, h=h,
cs_grad=deterministic_random_uniform(cs.shape.as_list()),
h_grad=deterministic_random_uniform(h.shape.as_list()),
use_peephole=False,
)
kwargs[name] = deterministic_random_uniform([3])
with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
f"{name}.dim_size\\(0\\) != cell_size"):
self._run_with_unknown_shape(
gen_rnn_ops.BlockLSTMGrad, name, **kwargs)2. Incomplete test matrix for peephole size validation (P1)
The snippet provided in our previous review for testing LSTMBlockCellInvalidPeepholeSize only verified the wci dimension validation branch. Because every new or changed branch needs a deterministic test that reaches it, please update testLSTMBlockCellInvalidPeepholeSize and testLSTMBlockCellGradInvalidPeepholeSize to test all three peephole weights (wci, wcf, wco).
In tensorflow/python/ops/rnn_grad_test.py around line 275:
def testLSTMBlockCellInvalidPeepholeSize(self):
# A peephole weight whose length differs from cell_size is broadcast
# against [batch_size, cell_size] tensors and read out of bounds.
for name in ["wci", "wcf", "wco"]:
kwargs = self._lstm_block_cell_inputs()
kwargs[name] = deterministic_random_uniform([3])
with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
f"{name}.dim_size\\(0\\) != cell_size"):
self._run_with_unknown_shape(
gen_rnn_ops.lstm_block_cell, name, use_peephole=True, **kwargs)
def testLSTMBlockCellGradInvalidPeepholeSize(self):
# wci_grad is allocated with the shape of wci but written with cell_size
# elements.
for name in ["wci", "wcf", "wco"]:
kwargs = self._lstm_block_cell_grad_inputs()
kwargs[name] = deterministic_random_uniform([3])
with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
f"{name}.dim_size\\(0\\) != cell_size"):
self._run_with_unknown_shape(
gen_rnn_ops.lstm_block_cell_grad, name, use_peephole=False,
**kwargs)3. Pre-existing typo in error message (P2)
In LSTMBlockCellGradOp::Compute (tensorflow/core/kernels/rnn/lstm_ops.cc:673), there is a pre-existing copy-paste typo in the error message for f_tensor dimension validation. It incorrectly cites i.dim_size(1) instead of f.dim_size(1).
If possible, please update "i.dim_size(1) != cell_size: " to "f.dim_size(1) != cell_size: " for consistency with line 669. This is a non-blocking suggestion.
BlockLSTMGradOp checked that wci, wcf and wco are rank 1 but not that their length is cell_size, unlike BlockLSTMOp. wci_grad is allocated with the shape of wci and written with cell_size elements, so reject a mismatched length the way the forward op does. Cover wci, wcf and wco in the peephole size tests for LSTMBlockCell, LSTMBlockCellGrad and BlockLSTMGrad. Fix the f_tensor size message in LSTMBlockCellGradOp, which named i.
|
@dmiltr3 Thanks, all three addressed in c8b5562:
For reference, the CPU job on the previous head (dbc0789) passed with the patched kernel: |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates! The pull request successfully addresses all rank validation issues and adds robust size checks for peephole weights (wci, wcf, wco) in LSTMBlockCellOp, LSTMBlockCellGradOp, and BlockLSTMGradOp. The typo in the error message has also been fixed. We have a few remaining findings to fully secure the sibling kernels.
1. Missing cs_prev emptiness validation in BlockLSTMOp and BlockLSTMGradOp (P1)
While the PR adds a safeguard against an empty cs_prev tensor in LSTMBlockCellGradOp to prevent a zero-sized CUDA launch configuration abort (see #58270), it misses the sibling BlockLSTMOp and BlockLSTMGradOp. These kernels invoke the exact same GPU functors (LSTMBlockCellFprop and BlockLSTMBprop) and will fatally crash with cudaErrorInvalidValue via TF_CHECK_OK if passed a tensor where batch_size == 0 or cell_size == 0.
Please add the same check to both BlockLSTMOp and BlockLSTMGradOp immediately after their cs_prev rank validation.
In tensorflow/core/kernels/rnn/lstm_ops.cc for BlockLSTMOp, around line 961:
const Tensor* cs_prev_tensor = nullptr;
OP_REQUIRES_OK(ctx, ctx->input("cs_prev", &cs_prev_tensor));
OP_REQUIRES(ctx, cs_prev_tensor->dims() == 2,
absl::InvalidArgumentError("cs_prev must be 2D"));
OP_REQUIRES(
ctx, cs_prev_tensor->dim_size(0) > 0 && cs_prev_tensor->dim_size(1) > 0,
absl::InvalidArgumentError(
absl::StrCat("cs_prev_tensor is empty, has shape: (",
cs_prev_tensor->dim_size(0), ",",
cs_prev_tensor->dim_size(1), ").")));
OP_REQUIRES(ctx, cs_prev_tensor->dim_size(0) == batch_size,And similarly in BlockLSTMGradOp, around line 1209:
const Tensor* cs_prev_tensor = nullptr;
OP_REQUIRES_OK(ctx, ctx->input("cs_prev", &cs_prev_tensor));
OP_REQUIRES(
ctx, cs_prev_tensor->dims() == 2,
absl::InvalidArgumentError(absl::StrCat(
"cs_prev must be rank 2 but is rank ", cs_prev_tensor->dims())));
OP_REQUIRES(
ctx, cs_prev_tensor->dim_size(0) > 0 && cs_prev_tensor->dim_size(1) > 0,
absl::InvalidArgumentError(
absl::StrCat("cs_prev_tensor is empty, has shape: (",
cs_prev_tensor->dim_size(0), ",",
cs_prev_tensor->dim_size(1), ").")));Please also add corresponding deterministic test cases to tensorflow/python/ops/rnn_grad_test.py:
def testBlockLSTMOpEmptyCsPrev(self):
w, b, x, cs_prev, h_prev, w_peephole = self._block_lstm_inputs(
hidden_size=0)
kwargs = dict(
seq_len_max=math_ops.cast(x.shape[0], dtypes.int64),
x=x, h_prev=h_prev, w=w, wci=w_peephole, wcf=w_peephole,
wco=w_peephole, b=b, use_peephole=False)
with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
"cs_prev_tensor is empty"):
self._run_with_unknown_shape(
gen_rnn_ops.BlockLSTM, "cs_prev", cs_prev=cs_prev, **kwargs)
def testBlockLSTMGradEmptyCsPrev(self):
w, b, x, cs_prev, h_prev, w_peephole = self._block_lstm_inputs(
hidden_size=0)
shape_3d = [x.shape[0], x.shape[1], 0]
empty_3d = array_ops.zeros(shape_3d, dtype=dtypes.float32)
kwargs = dict(
seq_len_max=math_ops.cast(x.shape[0], dtypes.int64),
x=x, h_prev=h_prev, w=w, wci=w_peephole, wcf=w_peephole,
wco=w_peephole, b=b, i=empty_3d, cs=empty_3d, f=empty_3d,
o=empty_3d, ci=empty_3d, co=empty_3d, h=empty_3d,
cs_grad=empty_3d, h_grad=empty_3d, use_peephole=False)
with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
"cs_prev_tensor is empty"):
self._run_with_unknown_shape(
gen_rnn_ops.BlockLSTMGrad, "cs_prev", cs_prev=cs_prev, **kwargs)2. Integer truncation masking exact size matching for b_tensor (P1)
In BlockLSTMGradOp::Compute (tensorflow/core/kernels/rnn/lstm_ops.cc:1269), the check cell_size == b_tensor->dim_size(0) / 4 is vulnerable to integer division truncation. If b_tensor has a length of cell_size * 4 + 3, it will pass this check instead of being correctly rejected.
Please update the check to enforce exact equality:
OP_REQUIRES(ctx, b_tensor->dim_size(0) == cell_size * 4,
absl::InvalidArgumentError(
absl::StrCat("w and b cell_size don't match: ", cell_size,
" vs. ", b_tensor->dim_size(0))));3. Missing test coverage for BlockLSTMOp peephole sizes (P1)
While testBlockLSTMGradInvalidPeepholeSize was successfully added, the forward op BlockLSTMOp lacks a corresponding test verifying that it rejects invalid peephole weight sizes.
Please add the following test to tensorflow/python/ops/rnn_grad_test.py:
def testBlockLSTMInvalidPeepholeSize(self):
for name in ["wci", "wcf", "wco"]:
w, b, x, cs_prev, h_prev, w_peephole = self._block_lstm_inputs()
kwargs = dict(
seq_len_max=math_ops.cast(x.shape[0], dtypes.int64),
x=x, cs_prev=cs_prev, h_prev=h_prev, w=w,
wci=w_peephole, wcf=w_peephole, wco=w_peephole, b=b,
use_peephole=False,
)
kwargs[name] = deterministic_random_uniform([3])
with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
f"{name}.dim_size\\(0\\) != cell_size"):
self._run_with_unknown_shape(
gen_rnn_ops.BlockLSTM, name, **kwargs)4. Redundant rank checks in BlockLSTMGradOp (P2)
BlockLSTMGradOp contains redundant rank checks for its internal state tensors. At tensorflow/core/kernels/rnn/lstm_ops.cc:1295-1315, it manually checks dims() == 3 for multiple tensors (e.g., i_out, cs_out), but then immediately passes them to the check_dims lambda at line 1330 which performs the exact same verification.
Please remove the redundant dims() == 3 block in tensorflow/core/kernels/rnn/lstm_ops.cc at lines 1295-1315:
- OP_REQUIRES(ctx, i_out->dims() == 3,
- absl::InvalidArgumentError(absl::StrCat(
- "i must be rank 3. Received: ", i_out->dims())));
- OP_REQUIRES(ctx, cs_out->dims() == 3,
- absl::InvalidArgumentError(absl::StrCat(
- "cs must be rank 3. Received: ", cs_out->dims())));
- OP_REQUIRES(ctx, f_out->dims() == 3,
- absl::InvalidArgumentError(absl::StrCat(
- "f must be rank 3. Received: ", f_out->dims())));
- OP_REQUIRES(ctx, o_out->dims() == 3,
- absl::InvalidArgumentError(absl::StrCat(
- "o must be rank 3. Received: ", o_out->dims())));
- OP_REQUIRES(ctx, ci_out->dims() == 3,
- absl::InvalidArgumentError(absl::StrCat(
- "ci must be rank 3. Received: ", ci_out->dims())));
- OP_REQUIRES(ctx, co_out->dims() == 3,
- absl::InvalidArgumentError(absl::StrCat(
- "co must be rank 3. Received: ", co_out->dims())));
- OP_REQUIRES(ctx, h_out->dims() == 3,
- absl::InvalidArgumentError(absl::StrCat(
- "h must be rank 3. Received: ", h_out->dims())));BlockLSTMGradOp accepted a bias of length 4 * cell_size + 1..3 because it compared cell_size with b.dim_size(0) / 4. Compare b.dim_size(0) with cell_size * 4, as BlockLSTMOp does. Remove its rank-3 checks on i, cs, f, o, ci, co and h; check_dims validates the rank of the same tensors before any dimension is read. Add tests for the BlockLSTMGrad bias size and the BlockLSTM peephole sizes, and share the BlockLSTM(Grad) inputs between the tests. Correct the comment on the empty cs_prev check in LSTMBlockCellGradOp: GpuLaunchKernel skips zero-sized launches, so the check keeps the gradient consistent with the forward op rather than preventing an abort.
|
@dmiltr3 Thanks. Points 2–4 are in d1df254; on point 1 I think the premise no longer holds, details below. 2. Exact 1. Empty
The same finding applies to my own reasoning for the LSTMBlockCellGrad empty check, so I corrected that comment: the check now just keeps the gradient consistent with the forward op, which already rejects an empty CI on c8b5562: the CPU job passed ( |
dmiltr3
left a comment
There was a problem hiding this comment.
Correction to our earlier review: The previous review requested adding an empty cs_prev check (dim_size(0) > 0) to BlockLSTMOp and BlockLSTMGradOp to prevent a zero-sized CUDA launch configuration abort. However, GpuLaunchKernel natively bypasses execution when grid or block dimensions are zero, and Eigen natively supports empty tensors. These kernels thus safely support batch_size=0. Artificially rejecting empty tensors would break backward compatibility for dynamic batching (D5) and boundary edge-case handling (D6). The contributor's pushback was entirely correct, and you should not add these checks.
Thank you for the updates! The pull request successfully addresses all rank validation issues and adds robust size checks for peephole weights (wci, wcf, wco) across all ops in the family. The integer division bug in bias validation is also fully resolved. By using def_function to bypass Python eager shape checks, you have ensured the C++ kernels are robustly and directly exercised. The PR is now fully secured and cleanly meets all code guidelines. We are approving it now.
dmiltr3
left a comment
There was a problem hiding this comment.
Hi @Ashutosh0x, thanks for the PR! The changes look great, but testLSTMBlockCellInvalidRank and the other newly added tests are currently failing in our internal CI when run in Graph mode.
When _run_with_unknown_shape uses def_function.function in Graph mode, the tensors from the outer scope are captured as constants, and the LSTMBlockCell op gets inlined directly into the outer graph. During this inlining, its shape inference executes on the actual value tensor which has a known shape, raising a ValueError (Shape must be rank 2 but is rank 1) instead of deferring to the C++ kernel check.
To hide the shape from the shape inference in Graph mode as intended, please wrap value in an array_ops.placeholder_with_default with shape=None before tracing:
--- a/tensorflow/python/ops/rnn_grad_test.py
+++ b/tensorflow/python/ops/rnn_grad_test.py
@@ -23,6 +23,7 @@ from tensorflow.python.eager import def_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_spec
from tensorflow.python.framework import test_util
+from tensorflow.python.eager import context
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_rnn_ops
@@ -213,6 +214,8 @@ class RNNGradTest(test.TestCase):
while the graph is built, so the check under test is the kernel's.
"""
value = kwargs.pop(name)
+ if not context.executing_eagerly():
+ value = array_ops.placeholder_with_default(value, shape=None)
@def_function.function(
autograph=False,Once this is patched, the tests will pass in both Eager and Graph modes. Could you please apply this fix?
In graph mode the function call is inlined and shape inference sees the argument's static shape, so the tests raised ValueError instead of reaching the kernel. Feed the value through placeholder_with_default with an unknown shape there.
|
@dmiltr3 Thanks, applied in 9d22951. Reproduced it locally on TF 2.21 inside |
dmiltr3
left a comment
There was a problem hiding this comment.
The latest commit exactly implements the requested fix to prevent static shape inference from raising ValueError in graph mode during test execution. All tests now correctly reach the C++ OpKernel runtime checks. The changes are clean, minimal, and fully satisfy the remaining blocking requirements.
Summary
LSTMBlockCellOp::Computereadsdim_size(1)onxandcs_prevbefore its rank checks run (they sit after output allocation), so a rank 1 input aborts the process instead of returningInvalidArgument:The op's shape function declares
WithRank(..., 2), but it does not run when the input's shape is unknown at graph construction, or in eager mode, sotf.raw_ops.LSTMBlockCellreaches the kernel directly.Fixes #113069 (LSTMBlockCell) and #113071 (LSTMBlockCellGrad).
Changes
LSTMBlockCellOp: validate the eight input ranks with acheck_ranklambda, the same pattern Validate input shapes in the LSTM gradient kernels #126028 introduced inLSTMBlockCellGradOp, before any dimension is read, and drop the later duplicate input checks. The checks on allocated temp/output tensors stay where they are. The empty-cs_prevcheck moves up with them. The rank checks on the temp/output tensors are removed, since they are allocated with explicit 2-D shapes.LSTMBlockCellGradOp: rank validation already landed in Validate input shapes in the LSTM gradient kernels #126028, so this only adds the empty-cs_prevcheck the forward op has (A check fail can be triggered in LSTMBlockCell #58270), so the gradient accepts the same inputs as the forward op.Both ops, and
BlockLSTMGradOp: check thatwci,wcfandwcohave lengthcell_size(BlockLSTMOpalready does). A wrong length is broadcast against[batch_size, cell_size]tensors, and in the grad opwci_gradis allocated with the shape ofwcibut written withcell_sizeelements.BlockLSTMGradOp: requireb.dim_size(0) == cell_size * 4exactly (it comparedcell_sizewithb.dim_size(0) / 4, so4 * cell_size + 1..3passed), and drop rank-3 checks that duplicatecheck_dims.Also fixes the
f_tensorsize message inLSTMBlockCellGradOp, which namedi.Tests
Added to
tensorflow/python/ops/rnn_grad_test.py. Each test feeds the offending input through atf.functionwith an unknown-shapeTensorSpec, so the shape function cannot reject it first and the kernel check is what is exercised, and assertsInvalidArgumentErrorwith the kernel message:testLSTMBlockCellInvalidRank: rank 1xtestLSTMBlockCellInvalidPeepholeRank: rank 2wci,use_peephole=TruetestLSTMBlockCellGradInvalidPeepholeRank: rank 2wci,use_peephole=False(vec<T>()is called regardless)testLSTMBlockCellInvalidPeepholeSize/testLSTMBlockCellGradInvalidPeepholeSize/testBlockLSTMGradInvalidPeepholeSize: each ofwci,wcf,wcoof length 3 with a differentcell_sizetestBlockLSTMInvalidPeepholeSize:BlockLSTM(already validated, previously untested)testBlockLSTMGradInvalidBiasSize:bof length4 * cell_size + 3testLSTMBlockCellGradEmptyCsPrev:cs_prevof shape[2, 0]Checked against tf-nightly 2.22.0-dev20260904 (CPU, before this change):
testLSTMBlockCellInvalidRank's input aborts withCheck failed: d < dims(), and the empty-cs_prevgrad, the wrong-length peephole weights and the4 * cell_size + 3bias are all accepted without an error. CI://tensorflow/python/ops:rnn_grad_test_cpupasses on the patched kernel. Without the unknown-shape signature the same rank 1 input is rejected at trace time with aValueError.