Repository navigation
Validate input shapes in the LSTM gradient kernels - #126028
copybara-service[bot] merged 4 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces input rank and dimension validation checks to LSTMBlockCellGradOp and BlockLSTMGradOp to prevent out-of-bounds reads and crashes, and adds corresponding unit tests. The review feedback notes that the check_dims helper in BlockLSTMGradOp should explicitly verify the rank of each tensor before accessing its dimensions to avoid potential crashes on lower-rank inputs.
dmiltr3
left a comment
There was a problem hiding this comment.
In tensorflow/python/kernel_tests/nn_ops/rnn_cell_test.py, testLSTMBlockCellGradInvalidRank fails when run in graph mode:
ValueError: Shape must be rank 2 but is rank 1 for '{{node LSTMBlockCellGrad}} = LSTMBlockCellGrad[...]' with input shapes: [0], ...
Cause
When x=constant_op.constant([], dtype=dtypes.float32) is passed, TensorFlow's static shape inference (SetShapeFn in tensorflow/core/ops/rnn_ops.cc) validates the rank during op creation in graph mode before kernel execution. When shape inference fails at graph construction time, Python raises a ValueError rather than errors_impl.InvalidArgumentError, and the error message starts with "Shape must be rank 2..." rather than "x must be rank 2...".
Required Fix
Please update testLSTMBlockCellGradInvalidRank in tensorflow/python/kernel_tests/nn_ops/rnn_cell_test.py to accept both exception types and match "must be rank 2":
--- a/tensorflow/python/kernel_tests/nn_ops/rnn_cell_test.py
+++ b/tensorflow/python/kernel_tests/nn_ops/rnn_cell_test.py
@@ -1539,3 +1539,3 @@
with self.assertRaisesRegex(
- errors_impl.InvalidArgumentError, "x must be rank 2"
+ (ValueError, errors_impl.InvalidArgumentError), "must be rank 2"
):|
@dmiltr3 Applied in a9c8bae, with the comment in the test expanded to say which layer raises in which mode: eager execution reaches the kernel check added by this PR, while graph construction is stopped earlier by the op's shape function in rnn_ops.cc, which surfaces as a ValueError with the "Shape must be rank 2" wording you quote. One clarification for the record: CI on this PR is green across all jobs, and the test runs eagerly under TF2, where it passes against the fixed kernel as written. The graph mode behavior you describe is real, I reproduced the exact ValueError, but it is a latent robustness concern for harnesses that run these tests in graph mode rather than an observed failure. Widening the accepted exception types covers both layers either way, so the change is worth making. |
|
Hi @vishwakt, Can you please resolve the conflicts? Thank you! |
Keeps both this branch's BlockLSTMGrad shape validation tests and the seq_len_max bounds tests added on master in the same region of rnn_cell_test.py.
|
@nithyak0204 i've resolved the conflicts. Looks like i'll need an approval from @dmiltr3 once again :) |
Fixes #112746
Both gradient kernels reported in the issue terminate the process on malformed input instead of returning an error.
BlockLSTMGrad, whenxcarries a different batch size from the other inputs, crashes with no message.LSTMBlockCellGrad, whenxis rank 1, aborts withCheck failed: d < dims() (1 vs. 1).Cause
BlockLSTMGradOptakestimelenandbatch_sizefromxandcell_sizefromw, then slices every other input with them. It checks the rank of those inputs, and checkscell_sizeagainstwandb, but never checks that their batch, cell or time dimensions actually agree with the values taken fromxandw, so a mismatch is read out of bounds.Sweeping the batch sizes shows exactly when it crashes, where the first column is
xand the second is every other input:The crash happens when one side has a zero batch and the other does not, since the empty tensor has nothing to read. A mismatch between two non-zero batch sizes does not crash, but silently computes against the wrong shape, which is equally unintended.
A shorter time dimension on one of the per step inputs is a second reachable crash, for example
iwithtimelen1 whilexhas 3, which tripsCheck failed: limit <= dim0_size (3 vs. 1)while slicing.LSTMBlockCellGradOpreadsx->dim_size(1)andcs_prev->dim_size(1)before any shape check runs, and its later sanity checks index dimension 1 of the remaining inputs. Indexing a dimension a tensor does not have is a fatal check, so a rank 1 input aborts. The forwardLSTMBlockCellOpvalidates the ranks of these same inputs before using them; the gradient does not.Fix
BlockLSTMGradOpnow checks thatcs_prev,h_prev,i,cs,f,o,ci,co,h,cs_gradandh_gradagree withtimelen,batch_sizeandcell_size, and adds the rank 3 checks thatcs_gradandh_gradwere missing.LSTMBlockCellGradOpvalidates the ranks of its inputs before the dimensions are read, mirroringLSTMBlockCellOp.Both use a small status returning helper so the checks stay readable, with
OP_REQUIRES_OKat the call site rather thanOP_REQUIRESinside the helper, since the latter would only return from the helper.Consistent shapes are unaffected, including a consistent zero batch size, which works today and must keep working.
Tests
Four tests in
rnn_cell_test.py: the reported batch size mismatch, the time dimension mismatch, the reported rank 1xforLSTMBlockCellGrad, and a control that consistent shapes still work for batch sizes 0 and 2.Verified against the released 2.21.0 wheel on macOS arm64 CPU: all three failing tests terminate the interpreter rather than failing an assertion, which is why they cannot be written against current TensorFlow as ordinary assertion failures, and the control test passes unchanged.
Relationship to other open PRs on this file
Two other PRs touch
lstm_ops.cc. Neither covers this gap and I have kept clear of both.wcolumns are a positive multiple of 4 inBlockLSTMGradOp. That check is already present on master at the point I branched, so that PR looks to have landed already.seq_len_maxbounds checks into one inBlockLSTMOpandBlockLSTMGradOp. This PR does not touch those lines.If #125400 lands first, the changes here sit in a different part of the same function and should not conflict.
Note for reviewers
I could not build TensorFlow locally, so the C++ changes have not been compiled and the new tests have not been run against a patched binary. The reproducers, the batch size matrix, the crash signatures and the control case were all verified against the released wheel.