Repository navigation
Reject scalar gradients in UnbatchGrad - #128345
copybara-service[bot] merged 5 commits into
Conversation
There was a problem hiding this comment.
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.
dmiltr3
left a comment
There was a problem hiding this comment.
We have two architectural adjustments required before we can merge this:
-
Synchronize Shape Inference (D3):
Since the runtimeUnbatchGradkernel now explicitly rejects scalar gradients, the static shape inference function intensorflow/core/ops/batch_ops.ccmust also be updated to match. Otherwise, graph construction will succeed for an invalid shape, but crash later during execution.
Please update theSetShapeFnforUnbatchGrad:.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(); }); -
Reduce Lock Contention (D7):
Intensorflow/core/kernels/batch_kernels.cc, the new shape validation forgrad_t(and the existing scalar validation and extraction forbatch_key) is currently performed inside themutex_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
left a comment
There was a problem hiding this comment.
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.
|
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. |
dmiltr3
left a comment
There was a problem hiding this comment.
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 teststestUnbatchGradInvalidId,testUnbatchGradInvalidBatchId, andtestUnbatchGradInvalidArgswere updated to use a bareassertRaises((errors.InvalidArgumentError, ValueError)). To ensure we do not mask unrelated failures, please useassertRaisesRegexand pin the exact error messages expected. Since graph mode and eager mode raise different messages, you can use an alternation pattern.For example, for
testUnbatchGradInvalidIdandtestUnbatchGradInvalidArgs: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.
|
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
left a comment
There was a problem hiding this comment.
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 usebatch_index_t.dim_size(1) != 3instead is the correct approach. - Oct 1: We blocked the PR asking you to add shape inference parity and tests for the
idparameter. This was scope creep since your PR was focused ongrad, and we unfairly penalized you for using theSetShapeFnsnippet we provided in the previous review which omitted theidcheck. Thank you for implementing it regardless.
…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
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.