Skip to content

Reject scalar gradients in UnbatchGrad - #128345

Merged
copybara-service[bot] merged 5 commits into
tensorflow:masterfrom
GodlyDonuts:codex/fix-unbatch-grad-scalar
Oct 30, 2026
Merged

copybara-service[bot] merged 5 commits into
tensorflow:masterfrom
GodlyDonuts:codex/fix-unbatch-grad-scalar

Conversation

@GodlyDonuts

Copy link
Copy Markdown
Contributor

Fixes #65636.

Reject scalar gradients before updating UnbatchGrad's shared state. Both empty-output construction and gradient concatenation require a batch axis; malformed gradients currently abort the process instead of raising InvalidArgumentError.

Add graph/eager coverage for scalar rejection, unknown gradient rank, valid empty outputs, and successful reuse of the same batch key after rejection.

Validation: seven focused tests passed with the source-extracted kernel compiled against tf-nightly. The regression aborts with the unchanged master kernel. C++ syntax, Pylint, and diff checks passed; full Bazel tests were not run.

@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Sep 30, 2026
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Sep 30, 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 a validation check in UnbatchGradResource within batch_kernels.cc to ensure that the gradient tensor has a rank of at least 1, throwing an invalid argument error otherwise. Additionally, it adds comprehensive unit tests in batch_ops_test.py covering scalar gradients, empty original inputs, and valid execution following an invalid scalar gradient. I have no further feedback to provide as the changes are well-tested and robust.

@nithyak0204 nithyak0204 self-assigned this Oct 1, 2026
@nithyak0204
nithyak0204 requested a review from a team October 1, 2026 04:57
@nithyak0204 nithyak0204 added the prtype:bugfix PR to fix a bug label Oct 1, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Oct 1, 2026
@dmiltr3
dmiltr3 self-requested a review October 1, 2026 16:15

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

We have two architectural adjustments required before we can merge this:

  1. Synchronize Shape Inference (D3):
    Since the runtime UnbatchGrad kernel now explicitly rejects scalar gradients, the static shape inference function in tensorflow/core/ops/batch_ops.cc must also be updated to match. Otherwise, graph construction will succeed for an invalid shape, but crash later during execution.
    Please update the SetShapeFn for UnbatchGrad:

        .SetShapeFn([](shape_inference::InferenceContext* c) {
          shape_inference::ShapeHandle grad_shape;
          TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(2), 1, &grad_shape));
          c->set_output(0, c->UnknownShapeOfRank(c->Rank(grad_shape)));
          return absl::OkStatus();
        });
  2. Reduce Lock Contention (D7):
    In tensorflow/core/kernels/batch_kernels.cc, the new shape validation for grad_t (and the existing scalar validation and extraction for batch_key) is currently performed inside the mutex_lock ml(mu_); critical section. Since these checks only inspect the incoming op context and do not mutate shared state, please hoist them above the lock acquisition to reduce contention on the fast path:

        if (!TensorShapeUtils::IsScalar(batch_key_t.shape())) {
          return absl::InvalidArgumentError(absl::StrCat(
              "Expected `id` to be scalar. Received ", batch_key_t.DebugString()));
        }
        if (!TensorShapeUtils::IsVectorOrHigher(grad_t.shape())) {
          return absl::InvalidArgumentError(absl::StrCat(
              "Expected `grad` to have rank at least 1. Received ",
              grad_t.shape().DebugString()));
        }
    
        const int64_t batch_key = context->input(3).scalar<int64_t>()();
    
        mutex_lock ml(mu_);
        // Mark our tensor as available.
        if (!available_tensors_.emplace(batch_key, grad_t).second) {

@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 detailed work on improving the UnbatchGrad kernel's robustness and shape validation. While the change successfully hoists validation out of the critical section and adds excellent test coverage, there are a few important issues regarding state invariants and shape function parity that need to be addressed before submission.

1. State/Memory Leak on Invalid Index

In tensorflow/core/kernels/batch_kernels.cc, the validation of batch_index_t happens after grad_t has already been inserted into the available_tensors_ map. If batch_index_t is invalid, the function returns an error but fails to clean up the inserted tensor, permanently orphaning the batch_key in the shared resource. This will cause subsequent valid runs with the same batch key to fail.

To resolve this and further reduce lock contention, please hoist the data_t and batch_index_t validation out of the mutex_lock and before the map insertion.

Suggested fix:

    if (!TensorShapeUtils::IsVectorOrHigher(grad_t.shape())) {
      return absl::InvalidArgumentError(
          absl::StrCat("Expected `grad` to have rank at least 1. Received ",
                       grad_t.shape().DebugString()));
    }

    if (data_t.NumElements() > 0) {
      if (batch_index_t.NumElements() == 0) {
        return absl::InvalidArgumentError(
            "batch_index is empty while the tensor isn't.");
      }
      if (!TensorShapeUtils::IsMatrix(batch_index_t.shape())) {
        return absl::InvalidArgumentError(
            absl::StrCat("Wrong shape for index tensor. Expected a matrix of "
                         "shape [batch_size, 3]; Got: ",
                         batch_index_t.shape().DebugString(), "."));
      }
      if (batch_index_t.NumElements() != batch_index_t.dim_size(0) * 3) {
        return absl::InvalidArgumentError(absl::StrCat(
            "batch_index should contain ", batch_index_t.dim_size(0) * 3,
            " elements. Received ", batch_index_t.NumElements()));
      }
    }

    const int64_t batch_key = context->input(3).scalar<int64_t>()();
    mutex_lock ml(mu_);
    // Mark our tensor as available.
    if (!available_tensors_.emplace(batch_key, grad_t).second) {
      return absl::InvalidArgumentError("Two runs with the same batch key.");
    }

(Please remember to remove the corresponding batch_index_t validation lines from further down in the function).

2. Missing Shape Function Parity for id Parameter

In tensorflow/core/ops/batch_ops.cc, the SetShapeFn does not validate the rank of input(3) (id), although the runtime kernel strictly enforces it to be a scalar. TensorFlow's shape functions must not accept shapes that the runtime kernel will reject.

Please enforce the scalar constraint during shape inference:

    .SetShapeFn([](shape_inference::InferenceContext* c) {
      shape_inference::ShapeHandle id_shape;
      TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 0, &id_shape));
      
      shape_inference::ShapeHandle grad_shape;
      TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(2), 1, &grad_shape));
      c->set_output(0, c->UnknownShapeOfRank(c->Rank(grad_shape)));
      return absl::OkStatus();
    });

Additionally, please add a test in tensorflow/python/ops/batch_ops_test.py to assert that passing a non-scalar id correctly raises a ValueError during graph construction.

@GodlyDonuts

Copy link
Copy Markdown
Contributor Author

All input validation now runs before the mutex and map insertion, including empty batch_index with nonempty original_input. Static id/index checks and regression tests are included. Eleven focused source-op/kernel tests passed, including reuse of the same resource and batch key after invalid indices.

@GodlyDonuts
GodlyDonuts requested a review from dmiltr3 October 1, 2026 20:04

@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 changes effectively resolve the lock contention issues by hoisting validation out of the critical section and perfectly align the runtime OpKernel validation with the shape inference function.

We have one minor follow-up regarding test integrity:

  • Pin Error Messages in Negative Tests: In tensorflow/python/ops/batch_ops_test.py (lines 642, 787, 813), the tests testUnbatchGradInvalidId, testUnbatchGradInvalidBatchId, and testUnbatchGradInvalidArgs were updated to use a bare assertRaises((errors.InvalidArgumentError, ValueError)). To ensure we do not mask unrelated failures, please use assertRaisesRegex and pin the exact error messages expected. Since graph mode and eager mode raise different messages, you can use an alternation pattern.

    For example, for testUnbatchGradInvalidId and testUnbatchGradInvalidArgs:

    with self.assertRaisesRegex((errors.InvalidArgumentError, ValueError), r"Shape must be rank 0|Expected `id` to be scalar"):

    For testUnbatchGradInvalidBatchId:

    with self.assertRaisesRegex((errors.InvalidArgumentError, ValueError), r"Dimension must be 3|Expected 1st dimension size to be 3|Wrong shape for index tensor"):

Please make these test updates and we'll be ready to move forward.

@GodlyDonuts
GodlyDonuts requested a review from dmiltr3 October 2, 2026 06:03
@GodlyDonuts

Copy link
Copy Markdown
Contributor Author

Corrected the invalid-index fixture to use a scalar ID, so it tests the intended index-shape error. Rank/index tests now accept the specific static or runtime validation messages. Validation: 11 tests passed against the compiled kernel source; pylint passed.

@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 your patience, and my apologies for the churn over the last few reviews. We provided some contradictory and mathematically flawed guidance which caused unnecessary extra work. You handled it perfectly, especially by catching our flawed dimension check and correctly hoisting the validation logic.

The current commit looks great. The lock contention is reduced, the state leak on invalid index is fixed, the shape function is aligned with the runtime kernel, and the tests are hermetic. I am approving this now.

Retractions

  • Oct 1: We asked you to check the matrix dimensions using batch_index_t.NumElements() != batch_index_t.dim_size(0) * 3. This was technically flawed, as an empty matrix [0, 0] would incorrectly pass this check. Your decision to use batch_index_t.dim_size(1) != 3 instead is the correct approach.
  • Oct 1: We blocked the PR asking you to add shape inference parity and tests for the id parameter. This was scope creep since your PR was focused on grad, and we unfairly penalized you for using the SetShapeFn snippet we provided in the previous review which omitted the id check. Thank you for implementing it regardless.

@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 2, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Oct 2, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Oct 5, 2026
@nithyak0204 nithyak0204 removed the kokoro:force-run Tests on submitted change label Oct 5, 2026
copybara-service Bot pushed a commit that referenced this pull request Oct 30, 2026
…orFlow.

Downstream custom-op libraries (such as TF.Text) that compile `tf_op_shim` sources directly against TensorFlow wheel headers and link dynamically against `libtensorflow_framework.so` need the shim source files exported and must avoid direct protobuf `Map::at()` lookups across the shared-library boundary. Additionally, `bool(os.environ.get("USE_PYWRAP_RULES", False))` in the Python repository rules evaluates `"0"` and `"false"` to `True`.

- Export `shape.cc`, `tf_op_shim.cc`, and `tf_tensor_view.cc` in `tensorflow/lite/kernels/shim/BUILD`.
- Look up op attributes via `::tensorflow::AttrSlice(context_->def()).Find(attr_name)` in `TfInitContext::GetAttr` and remove an unused `error_codes.proto.h` include.
- Parse `USE_PYWRAP_RULES` in `python_version.bzl` and `python_repo.bzl.oss` using `.get("USE_PYWRAP_RULES", "").lower() in ("true", "1")`.

FUTURE_COPYBARA_INTEGRATE_REVIEW=#128345 from GodlyDonuts:codex/fix-unbatch-grad-scalar bba427c
PiperOrigin-RevId: 998255671
@copybara-service
copybara-service Bot merged commit 4f2f18b into tensorflow:master Oct 30, 2026
17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Oct 30, 2026
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.

Check failed in tf.raw_ops.UnbatchGrad when the input of original_input is empty.

3 participants