Skip to content

Validate input shapes in the LSTM gradient kernels - #126028

Merged
copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
vishwakt:fix-lstm-grad-shape-validation
Sep 25, 2026
Merged

copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
vishwakt:fix-lstm-grad-shape-validation

Conversation

@vishwakt

Copy link
Copy Markdown
Contributor

Fixes #112746

Both gradient kernels reported in the issue terminate the process on malformed input instead of returning an error.

BlockLSTMGrad, when x carries a different batch size from the other inputs, crashes with no message. LSTMBlockCellGrad, when x is rank 1, aborts with Check failed: d < dims() (1 vs. 1).

Cause

BlockLSTMGradOp takes timelen and batch_size from x and cell_size from w, then slices every other input with them. It checks the rank of those inputs, and checks cell_size against w and b, but never checks that their batch, cell or time dimensions actually agree with the values taken from x and w, so a mismatch is read out of bounds.

Sweeping the batch sizes shows exactly when it crashes, where the first column is x and the second is every other input:

0, 0 -> ok        1, 0 -> crash      2, 0 -> crash
0, 1 -> crash     1, 1 -> ok         2, 1 -> ok
0, 2 -> crash     1, 2 -> ok         2, 2 -> ok

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 i with timelen 1 while x has 3, which trips Check failed: limit <= dim0_size (3 vs. 1) while slicing.

LSTMBlockCellGradOp reads x->dim_size(1) and cs_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 forward LSTMBlockCellOp validates the ranks of these same inputs before using them; the gradient does not.

Fix

BlockLSTMGradOp now checks that cs_prev, h_prev, i, cs, f, o, ci, co, h, cs_grad and h_grad agree with timelen, batch_size and cell_size, and adds the rank 3 checks that cs_grad and h_grad were missing. LSTMBlockCellGradOp validates the ranks of its inputs before the dimensions are read, mirroring LSTMBlockCellOp.

Both use a small status returning helper so the checks stay readable, with OP_REQUIRES_OK at the call site rather than OP_REQUIRES inside 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 1 x for LSTMBlockCellGrad, 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.

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.

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

Comment thread tensorflow/core/kernels/rnn/lstm_ops.cc Resolved
@keerthanakadiri
keerthanakadiri requested a review from a team August 25, 2026 05:01
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Aug 25, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Aug 25, 2026
@keerthanakadiri keerthanakadiri added the prtype:bugfix PR to fix a bug label Aug 25, 2026
@dmiltr3
dmiltr3 self-requested a review August 25, 2026 14:54
@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Aug 25, 2026
@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Approved by Reviewer in PR Queue Aug 25, 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.

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"
     ):

@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Reviewer Requested Changes in PR Queue Aug 25, 2026
@google-ml-butler google-ml-butler Bot removed the ready to pull PR ready for merge process label Aug 26, 2026
@vishwakt

Copy link
Copy Markdown
Contributor Author

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

dmiltr3
dmiltr3 previously approved these changes Aug 26, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Aug 26, 2026
@google-ml-butler google-ml-butler Bot added the ready to pull PR ready for merge process label Aug 26, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Aug 27, 2026
@nithyak0204

Copy link
Copy Markdown

Hi @vishwakt, Can you please resolve the conflicts? Thank you!

@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Sep 2, 2026
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.
@vishwakt

vishwakt commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

@nithyak0204 i've resolved the conflicts. Looks like i'll need an approval from @dmiltr3 once again :)

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Sep 2, 2026
@nithyak0204
nithyak0204 requested a review from dmiltr3 September 2, 2026 17:31
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Sep 2, 2026
@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Sep 2, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Sep 3, 2026
@copybara-service
copybara-service Bot merged commit 72ca27b into tensorflow:master Sep 25, 2026
18 checks passed
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.BlockLSTMGrad and tf.raw_ops.LSTMBlockCellGrad crash when input tensor has invalid shape.

5 participants