Skip to content

fix: validate input rank before reading dims in LSTMBlockCell kernels - #124034

Merged
copybara-service[bot] merged 5 commits into
tensorflow:masterfrom
Ashutosh0x:fix/lstm-block-cell-rank-validation
Oct 9, 2026
Merged

copybara-service[bot] merged 5 commits into
tensorflow:masterfrom
Ashutosh0x:fix/lstm-block-cell-rank-validation

Conversation

@Ashutosh0x

@Ashutosh0x Ashutosh0x commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

LSTMBlockCellOp::Compute reads dim_size(1) on x and cs_prev before its rank checks run (they sit after output allocation), so a rank 1 input aborts the process instead of returning InvalidArgument:

F0000 tensor_shape.cc:362] Check failed: d < dims() (1 vs. 1)

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, so tf.raw_ops.LSTMBlockCell reaches the kernel directly.

Fixes #113069 (LSTMBlockCell) and #113071 (LSTMBlockCellGrad).

Changes

  • LSTMBlockCellOp: validate the eight input ranks with a check_rank lambda, the same pattern Validate input shapes in the LSTM gradient kernels #126028 introduced in LSTMBlockCellGradOp, 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_prev check 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_prev check 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 that wci, wcf and wco have length cell_size (BlockLSTMOp already does). A wrong length is broadcast against [batch_size, cell_size] tensors, and in the grad op wci_grad is allocated with the shape of wci but written with cell_size elements.

  • BlockLSTMGradOp: require b.dim_size(0) == cell_size * 4 exactly (it compared cell_size with b.dim_size(0) / 4, so 4 * cell_size + 1..3 passed), and drop rank-3 checks that duplicate check_dims.

Also fixes the f_tensor size message in LSTMBlockCellGradOp, which named i.

Tests

Added to tensorflow/python/ops/rnn_grad_test.py. Each test feeds the offending input through a tf.function with an unknown-shape TensorSpec, so the shape function cannot reject it first and the kernel check is what is exercised, and asserts InvalidArgumentError with the kernel message:

  • testLSTMBlockCellInvalidRank: rank 1 x
  • testLSTMBlockCellInvalidPeepholeRank: rank 2 wci, use_peephole=True
  • testLSTMBlockCellGradInvalidPeepholeRank: rank 2 wci, use_peephole=False (vec<T>() is called regardless)
  • testLSTMBlockCellInvalidPeepholeSize / testLSTMBlockCellGradInvalidPeepholeSize / testBlockLSTMGradInvalidPeepholeSize: each of wci, wcf, wco of length 3 with a different cell_size
  • testBlockLSTMInvalidPeepholeSize: BlockLSTM (already validated, previously untested)
  • testBlockLSTMGradInvalidBiasSize: b of length 4 * cell_size + 3
  • testLSTMBlockCellGradEmptyCsPrev: cs_prev of shape [2, 0]

Checked against tf-nightly 2.22.0-dev20260904 (CPU, before this change): testLSTMBlockCellInvalidRank's input aborts with Check failed: d < dims(), and the empty-cs_prev grad, the wrong-length peephole weights and the 4 * cell_size + 3 bias are all accepted without an error. CI: //tensorflow/python/ops:rnn_grad_test_cpu passes on the patched kernel. Without the unknown-shape signature the same rank 1 input is rejected at trace time with a ValueError.

@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Jul 27, 2026
@google-ml-butler
google-ml-butler Bot requested a review from cantonios July 27, 2026 02:25
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Jul 27, 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 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.

Comment thread tensorflow/core/kernels/rnn/lstm_ops.cc Resolved
Comment thread tensorflow/core/kernels/rnn/lstm_ops.cc Resolved
@Ashutosh0x

Copy link
Copy Markdown
Contributor Author

Added a RELEASE.md entry under Bug Fixes and Other Changes, since the template asks for issue-closing changes to be documented there. Happy to drop it if the team prefers to curate the 2.22.0 notes internally — just say the word.

@keerthanakadiri
keerthanakadiri requested a review from a team July 27, 2026 04:34
@keerthanakadiri keerthanakadiri added the comp:core issues related to core part of tensorflow label Jul 27, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Jul 27, 2026
@keerthanakadiri keerthanakadiri added the prtype:bugfix PR to fix a bug label Jul 27, 2026

@sgarciagoogle sgarciagoogle 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 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!

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Jul 29, 2026
@Ashutosh0x
Ashutosh0x force-pushed the fix/lstm-block-cell-rank-validation branch from 5ee3a77 to d6c35cc Compare July 29, 2026 17:21
@Ashutosh0x

Copy link
Copy Markdown
Contributor Author

@sgarciagoogle Done — 5ee3a77 is dropped and the branch is rebased onto current master, so the RELEASE.md conflict is gone too. The PR is now just the two files: lstm_ops.cc and rnn_grad_test.py.

Understood on the release notes being curated internally; I will leave RELEASE.md alone on my other PRs as well.

sgarciagoogle
sgarciagoogle previously approved these changes Aug 7, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Aug 7, 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 Aug 7, 2026
@sgarciagoogle sgarciagoogle removed the awaiting review Pull request awaiting review label Aug 7, 2026
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Aug 7, 2026
@twubndgsijlc-netizen

twubndgsijlc-netizen commented Aug 7, 2026 via email

Copy link
Copy Markdown

@nithyak0204

Copy link
Copy Markdown

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

@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed ready to pull PR ready for merge process labels Sep 9, 2026
@Ashutosh0x
Ashutosh0x force-pushed the fix/lstm-block-cell-rank-validation branch from d6c35cc to 793cd0b Compare September 9, 2026 12:05
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
@Ashutosh0x
Ashutosh0x force-pushed the fix/lstm-block-cell-rank-validation branch from 793cd0b to 2bb2150 Compare October 9, 2026 01:48
@Ashutosh0x

Copy link
Copy Markdown
Contributor Author

@dmiltr3 Thanks for the review. Addressed in 2bb2150, rebased onto current master:

  1. Redundant grad checks: removed. Those rank checks landed in Validate input shapes in the LSTM gradient kernels #126028 while this PR was open, which is also what caused the conflict. The grad op now only gains the empty cs_prev check.
  2. Tests not reaching the kernel: right. Each test now feeds the offending input through def_function.function with TensorSpec(shape=None) and asserts InvalidArgumentError with the kernel message only. On tf-nightly 2.22.0-dev20260904 the rank 1 x case aborts with Check failed: d < dims() through that path, and raises ValueError at trace time without it.
  3. Forward peephole test: added testLSTMBlockCellInvalidPeepholeRank. On master the forward op does reject a rank 2 wci before vec<T>(), through the late checks, so this one pins the check's new position and message rather than an abort.
  4. Consistency: the forward op now uses the same check_rank lambda, placed before the first dim_size read, and the 40 lines of hoisted OP_REQUIRES are gone.

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

Copy link
Copy Markdown
Contributor Author

@dmiltr3 Thanks, both addressed in dbc0789:

  1. Peephole sizes: wci, wcf and wco are now checked against cell_size right after the b size check in both ops, with the messages you suggested, plus testLSTMBlockCellInvalidPeepholeSize and testLSTMBlockCellGradInvalidPeepholeSize. On tf-nightly 2.22.0-dev20260904 (CPU release build) both inputs are accepted silently, so the tests fail without the change. In the grad op it matters regardless of use_peephole's effect on the math, since wci_grad is allocated with the shape of wci. The existing callers in the tree (rnn_grad_test.py, rnn_cell_test.py) already pass cell_size peephole weights when use_peephole=False.
  2. Temp/output rank checks: removed. All of them are allocated with explicit 2-D shapes just above (forward_input_or_allocate_output only forwards on an exact shape match).

The grad op's dimension-matching block is untouched.

The two CUDA failures are unrelated: both stop compiling external/triton/third_party/amd/lib/TritonAMDGPUToLLVM/TritonGPUToLLVM.cpp (no viable conversion from 'mlir::amdgpu::Chipset' to 'const ROCDL::TargetInfo'), and the same two jobs fail on the current exported_pr_* runs as well.

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

Copy link
Copy Markdown
Contributor Author

@dmiltr3 Thanks, all three addressed in c8b5562:

  1. BlockLSTMGradOp peephole sizes: added the wci/wcf/wco dim_size(0) == cell_size checks right after each rank check, matching BlockLSTMOp, plus testBlockLSTMGradInvalidPeepholeSize. Same reason as the cell grad op: wci_grad is allocated with the shape of wci and written with cell_size elements.
  2. Test matrix: testLSTMBlockCellInvalidPeepholeSize, testLSTMBlockCellGradInvalidPeepholeSize and testBlockLSTMGradInvalidPeepholeSize now loop over wci, wcf and wco.
  3. Typo: the f_tensor message now reads f.dim_size(1) != cell_size.

For reference, the CPU job on the previous head (dbc0789) passed with the patched kernel: //tensorflow/python/ops:rnn_grad_test_cpu PASSED, 3193/3193 tests. Against tf-nightly 2.22.0-dev20260904 (unpatched), all three size tests fail with InvalidArgumentError not raised, so they do exercise the new checks.

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

Copy link
Copy Markdown
Contributor Author

@dmiltr3 Thanks. Points 2–4 are in d1df254; on point 1 I think the premise no longer holds, details below.

2. Exact b size in BlockLSTMGradOp: now b_tensor->dim_size(0) == cell_size * 4, matching BlockLSTMOp, with testBlockLSTMGradInvalidBiasSize (length 4 * cell_size + 3).
3. BlockLSTM peephole sizes: added testBlockLSTMInvalidPeepholeSize over wci/wcf/wco.
4. Duplicate rank-3 checks in BlockLSTMGradOp: removed; check_dims validates the same ranks before any dimension is read.

1. Empty cs_prev in BlockLSTMOp / BlockLSTMGradOp: I left these out, for three reasons:

  • GpuLaunchKernel returns OK without launching when the grid or block is empty (tensorflow/core/util/gpu_kernel_helper.h, if (grid_dim.x * grid_dim.y * grid_dim.z > 0 && block_dim.x * block_dim.y * block_dim.z > 0), from 764eae3 "General fix for GPU kernels with empty inputs", Feb 2023). A check fail can be triggered in LSTMBlockCell #58270 predates that, so a zero-sized launch no longer reaches TF_CHECK_OK with an error.
  • In BlockLSTMGradOp, cell_size == 0 is already rejected by "w matrix columns must be a positive multiple of 4", and batch_size == 0 is explicitly supported: testBlockLSTMGradConsistentShapesStillWork in rnn_cell_test.py (Validate input shapes in the LSTM gradient kernels #126028) runs it with a zero batch, so an emptiness check would break that test. The suggested testBlockLSTMGradEmptyCsPrev (with hidden_size=0) fails on the w check before reaching cs_prev.
  • BlockLSTMOp currently returns correctly shaped empty outputs for both a zero batch and a zero cell size (checked on tf-nightly 2.22.0-dev20260904: h of shape (2, 0, 4) and (2, 2, 0)), so rejecting them would turn valid calls into errors.

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 cs_prev. Happy to drop it instead if you prefer.

CI on c8b5562: the CPU job passed (rnn_grad_test_cpu PASSED, 3193/3193). Windows failed only on two unrelated targets that fail to link (//tensorflow/core/common_runtime:lower_if_op_test, //tensorflow/core/tfrt/fallback:fallback_state_test, undefined grappler::Cluster / tsl::io::RandomAccessInputStream symbols; 1702 other tests passed), and CUDA has the same triton build error as before.

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

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Oct 9, 2026
@nithyak0204 nithyak0204 removed the kokoro:force-run Tests on submitted change label Oct 9, 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.

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?

@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Reviewer Requested Changes in PR Queue Oct 9, 2026
@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed ready to pull PR ready for merge process labels Oct 9, 2026
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.
@Ashutosh0x

Copy link
Copy Markdown
Contributor Author

@dmiltr3 Thanks, applied in 9d22951. _run_with_unknown_shape now wraps the value in placeholder_with_default(value, shape=None) when not executing eagerly.

Reproduced it locally on TF 2.21 inside Graph().as_default(): without the placeholder the rank 1 x raises ValueError: Shape must be rank 2 but is rank 1 at graph construction, and with it the input reaches the kernel (on the unpatched kernel that is the Check failed: d < dims() abort this PR fixes). Eager mode is unchanged.

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

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels 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 db255a4 into tensorflow:master Oct 9, 2026
17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Oct 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:core issues related to core part of tensorflow 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.LSTMBlockCell aborts with internal CHECK failure on invalid-rank input instead of raising an error

8 participants