Repository navigation
Conversation
A resource training op takes its type T from the learning rate and gradient, and ResourceScatterNd* from the updates, so either can be given a resource variable of another dtype. Reading the variable's tensor as T then fails a CHECK and aborts the process (tensorflow#113074, tensorflow#113145). Add ValidateVariableDtype<T> to training_op_helpers.h, with the message ResourceGather already uses, and call it with the variable's lock held: in both branches of GetInputTensorFromVariable, which every resource training op goes through, in EnsureSparseVariableAccess in place of its inline check, and in ScatterNdUpdateOp after it locks the variable, since EnsureSparseVariableAccess returns before its check once the variable is in copy-on-read mode.
There was a problem hiding this comment.
Code Review
This pull request introduces a ValidateVariableDtype helper function to validate resource variable dtypes, preventing process aborts when variables are read with mismatched types, especially in copy-on-read mode. This validation is integrated into ScatterNdUpdateOp, EnsureSparseVariableAccess, and GetInputTensorFromVariable, with corresponding regression tests added. The review feedback recommends adding a defensive check for uninitialized variables to provide a clearer error message, and updating the function's documentation to clarify locking requirements when called from EnsureSparseVariableAccess.
dmiltr3
left a comment
There was a problem hiding this comment.
The PR successfully fixes the unrecoverable process abort (Check failed: dtype() == expected_dtype) by properly checking the data type in GetInputTensorFromVariable and ScatterNdUpdateOp::Compute. The fix correctly encapsulates the type validation within ValidateVariableDtype, ensuring it applies even when EnsureSparseVariableAccess is bypassed by variables already in copy-on-read mode. The comprehensive testing for both copy_on_read states properly validates this fix.
Suggestions
- Location:
tensorflow/core/kernels/resource_variable_ops.cclines 768-773 (inResourceGatherOp) and lines 961-966 (inResourceGatherNdOp). - Rationale: The change factors out
ValidateVariableDtypeintraining_op_helpers.hto preserve the exact error message"dtype mismatch: expected %s but got %s (resource variable dtype)"used across multiple resource operations. As per codebase idioms, when a helper is added for an invariant check, other call sites that re-implement the exact same logic inline should be updated to reuse it. BothResourceGatherOpandResourceGatherNdOpinsideresource_variable_ops.cc(which already includestraining_op_helpers.h) duplicate this exact logic and error message format. - Replacement for
ResourceGatherOp:tf_shared_lock ml(*v->mu()); OP_REQUIRES_OK(c, ValidateVariableDtype<T>(v.get())); const Tensor& params = *v->tensor();
- Replacement for
ResourceGatherNdOp:tf_shared_lock ml(*v->mu()); OP_REQUIRES_OK(c, ValidateVariableDtype<T>(v.get())); const Tensor& params = *v->tensor();
ResourceGather and ResourceGatherNd checked the variable's dtype inline with the same message as ValidateVariableDtype, under the same shared lock. Call the helper instead.
|
Thanks @dmiltr3, done: |
dmiltr3
left a comment
There was a problem hiding this comment.
The change successfully resolves the fatal abort by enforcing data type consistency under the resource lock prior to promotion, and perfectly implements our prior ask for ResourceGatherOp and ResourceGatherNdOp.
We identified two remaining gaps required for completeness: ensuring a sibling kernel uses the new helper, and expanding the new tests to run in eager mode.
Sibling Kernel Completeness
Location: tensorflow/core/kernels/resource_variable_ops.cc lines 1182 and 1189 (in ResourceScatterUpdateOp)
The ResourceScatterUpdateOp sibling kernel re-implements the dtype verification logic inline with a different error message ("DType of scatter resource and updates does not match."). Since ValidateVariableDtype<T> was factored out specifically to standardise this error message and check, please update ResourceScatterUpdateOp to reuse it as well:
if (is_non_pod_dtype || use_exclusive_lock_) {
mutex_lock ml(*v->mu());
OP_REQUIRES_OK(c, ValidateVariableDtype<T>(v.get()));
DoCompute(c, v.get());
} else {
// For POD dtypes, we can safely run the update without the mutex.
tf_shared_lock ml(*v->mu());
OP_REQUIRES_OK(c, ValidateVariableDtype<T>(v.get()));
DoCompute(c, v.get());
}Test Matrix Completeness
Location: tensorflow/python/kernel_tests/array_ops/scatter_nd_ops_test.py line 262 and tensorflow/python/training/training_ops_test.py line 594
The newly added tests testResourceScatterNdUpdateRejectsVariableOfAnotherDtype and testResourceApplyOpsRejectVariableOfAnotherDtype currently only run in the suite's default graph mode. They should explicitly cover eager execution as well. Please add the @test_util.run_in_graph_and_eager_modes decorator to both test methods:
@test_util.run_in_graph_and_eager_modes
def testResourceScatterNdUpdateRejectsVariableOfAnotherDtype(self):and:
@test_util.run_in_graph_and_eager_modes
def testResourceApplyOpsRejectVariableOfAnotherDtype(self):ResourceScatterUpdate and its arithmetic variants checked the variable's dtype against the updates' dtype inline, which is T, with their own message. Call ValidateVariableDtype<T> instead, so it reports the same message as the other resource ops. Run the new dtype tests in both graph and eager mode.
|
Thanks @dmiltr3, both done:
|
dmiltr3
left a comment
There was a problem hiding this comment.
The PR correctly addresses unrecoverable process aborts caused by reading resource variables with mismatched dtypes by enforcing type validation on all access paths, and correctly implements our previous carry-over requests (R2, R3, R4) by reusing the validation helper in ResourceScatterUpdateOp and testing graph and eager modes.
We have identified two remaining gaps required for completeness: ensuring a sibling kernel in the same file uses the new helper, and expanding the test coverage to scatter_update.
Sibling Kernel Completeness
Location: tensorflow/core/kernels/resource_variable_ops.cc lines 653-655 (in AssignUpdateVariableOp)
Rationale: The change factors out ValidateVariableDtype to preserve the exact error message "dtype mismatch: expected %s but got %s (resource variable dtype)" across multiple resource operations. As per codebase idioms, when a helper is added for an invariant check, other call sites that re-implement the exact same logic inline should be updated to reuse it. AssignUpdateVariableOp in the same file re-implements the dtype verification logic inline with its own error message ("DType of variable handle and value does not match."). Please standardise this kernel to use the new helper as well.
Replacement:
```cpp
OP_REQUIRES_OK(context, ValidateAssignUpdateVariableOpShapes(
var_tensor->shape(), value.shape()));
OP_REQUIRES_OK(context, ValidateVariableDtype(variable.get()));
OP_REQUIRES_OK(
context, PrepareToUpdateVariable<Device, T>(
```
Missing Test for Sibling Kernel
Location: tensorflow/python/kernel_tests/array_ops/scatter_ops_test.py
Rationale: The previous review requested updating ResourceScatterUpdateOp to use ValidateVariableDtype<T>, which was successfully implemented. However, no corresponding test was added for state_ops.scatter_update (or resource_scatter_update) to verify it rejects variables of another dtype. The new tests only cover scatter_nd_update and the training ops. Every modified kernel branch requires a test that reaches it. Please add a test for scatter_update (similar to the one added for scatter_nd_update).
Replacement:
```python
@test_util.run_in_graph_and_eager_modes
def testResourceScatterUpdateRejectsVariableOfAnotherDtype(self):
with ops.device("/CPU:0"):
for copy_on_read in (False, True):
with self.subTest(copy_on_read=copy_on_read):
ref = resource_variable_ops.ResourceVariable(
np.zeros((4, 2)), dtype=dtypes.bfloat16)
self.evaluate(ref.initializer)
if copy_on_read:
self.evaluate(
resource_variable_ops.resource_gather(
ref.handle, [0], dtype=dtypes.bfloat16))
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"dtype mismatch: expected float but got bfloat16"):
self.evaluate(
state_ops.resource_scatter_update(
ref.handle, [0],
constant_op.constant(np.ones((1, 2)), dtypes.float32)))
```
AssignAddVariableOp and AssignSubVariableOp compared the variable's dtype with the value's, which the op ties to T, so the check is the same and only the message changes to the standard one. Add tests for ResourceScatterUpdate, covering both lock branches with and without copy-on-read mode, and for AssignAddVariableOp and AssignSubVariableOp. They run eagerly, since in a graph the handle's shape inference rejects the mismatch before the kernel runs.
|
Thanks @dmiltr3, both done in dd47a1b:
On TF 2.21 both tests fail only on the message, with each case reaching the branch it targets. With custom ops that make the kernels' checks as this PR does, they pass, and matching dtypes still update the variable. |
dmiltr3
left a comment
There was a problem hiding this comment.
The update in AssignUpdateVariableOp cleanly standardizes the dtype check on ValidateVariableDtype<T>.
Please update two test details so the new tests pass across all execution modes:
1. Enter eager mode in resource_variable_ops_test.py
Location: tensorflow/python/kernel_tests/variables/resource_variable_ops_test.py lines 1965-2005
Because resource_variable_ops_test.py does not import top-level tensorflow, the default execution mode in ResourceVariableOpsTest is graph mode unless a test explicitly enters context.eager_mode() (as in testReadVariableDtypeMismatchEager and testAssignVariableDtypeMismatchEager earlier in the file). Without with context.eager_mode():, both new tests run in graph mode and fail during graph construction with ValueError: Trying to read variable with wrong dtype before the C++ kernel runs.
def testResourceScatterUpdateRejectsVariableOfAnotherDtype(self):
# Runs eagerly, since in a graph the handle's shape inference rejects the
# dtype before the kernel runs. Float updates take the kernel's shared-lock
# branch and string updates its exclusive-lock branch. Before the variable
# is in copy-on-read mode, which a gather puts it in,
# EnsureSparseVariableAccess rejects it first.
with context.eager_mode(), ops.device("/CPU:0"): def testAssignUpdateRejectsVariableOfAnotherDtype(self):
# Runs eagerly, like the test above.
with context.eager_mode(), ops.device("/CPU:0"):2. Disable XLA auto-JIT on the C++ kernel error-message tests
Location: tensorflow/python/kernel_tests/array_ops/scatter_nd_ops_test.py line 262 and tensorflow/python/training/training_ops_test.py line 594
Both test targets build strict XLA auto-JIT test suites. In the graph-mode subtest generated by @test_util.run_in_graph_and_eager_modes, XLA compiles the graph and checks the variable dtype in XlaOpKernelContext::ReadVariableInput (Trying to read variable with wrong dtype), bypassing the C++ CPU kernel and its dtype mismatch message. Please add @test_util.disable_xla("Tests C++ kernel validation") to both methods so non-XLA suites test both modes while XLA auto-JIT suites skip the C++ kernel message check.
@test_util.run_in_graph_and_eager_modes
@test_util.disable_xla("Tests C++ kernel validation")
def testResourceScatterNdUpdateRejectsVariableOfAnotherDtype(self): @test_util.run_in_graph_and_eager_modes
@test_util.disable_xla("Tests C++ kernel validation")
def testResourceApplyOpsRejectVariableOfAnotherDtype(self):The ResourceScatterUpdate and assign tests only reach the kernel eagerly, so enter context.eager_mode() rather than rely on the default mode. Under XLA auto-JIT the graph-mode runs of the ScatterNdUpdate and training op tests check the dtype in XLA, so disable XLA for them.
|
Thanks @dmiltr3, both done in 94b3020:
|
Fixes #113074
Fixes #113145
Cause
A resource training op such as
ResourceApplyGradientDescentorResourceSparseApplyAdagradtakes its typeTfrom the learning rate and gradient, not from the variable, so it can be given a resource variable of another dtype.ResourceScatterNd{Update,Add,Sub,Min,Max}takesTfrom the updates in the same way. Reading the variable's tensor withflat<T>()then failsCheck failed: dtype() == expected_dtypeand aborts the process.GetInputTensorFromVariable, which every resource training op goes through, never checks the dtype. On the dense path,PrepareToUpdateVariablecopies a variable in copy-on-read mode withflat<T>(), and otherwise the kernel reads it withflat<T>(). On the sparse path,MaybeLockVariableInputMutexesInOrdercallsEnsureSparseVariableAccess, which does check the dtype, but discards its status withIgnoreError().ScatterNdUpdateOprelies on the check inEnsureSparseVariableAccess, but that function returns before the check once the variable is in copy-on-read mode, which any gather or sparse update puts it in.Fix
EnsureSparseVariableAccessintoValidateVariableDtype<T>intraining_op_helpers.h, keeping its message:dtype mismatch: expected float but got bfloat16 (resource variable dtype).ResourceGatherandResourceGatherNdhad the same check inline, under the same shared lock, and now call the helper instead.ResourceScatterUpdateand its arithmetic variants made the same check inline with their own message (DType of scatter resource and updates does not match.); they now call the helper too, so they report the same message as the other resource ops.AssignAddVariableOpandAssignSubVariableOpdid the same withDType of variable handle and value does not match.and now call the helper as well.GetInputTensorFromVariable, after the existing lock assertions and beforePrepareToUpdateVariable.ScatterNdUpdateOponce it has locked the variable.Every call runs with the variable's mutex held, as the gather ops' checks already did, because another op can replace
*var->tensor()under the lock (EnsureSparseVariableAccessdoes when it copies). That is why the check isn't moved above the early return inEnsureSparseVariableAccess, which comes before the lock. Matching dtypes behave as before.Tests
training_ops_test.py:testResourceApplyOpsRejectVariableOfAnotherDtyperunsResourceApplyGradientDescent(dense path) andResourceSparseApplyAdagrad(sparse path) with a float32 learning rate and gradient on bfloat16 variables, first fresh and then in copy-on-read mode, and checks for the error above.scatter_nd_ops_test.py:testResourceScatterNdUpdateRejectsVariableOfAnotherDtypedoes the same forResourceScatterNdUpdate.disable_xla, since under XLA auto-JIT the graph-mode run checks the variable's dtype in XLA instead of the kernel.resource_variable_ops_test.py:testResourceScatterUpdateRejectsVariableOfAnotherDtyperunsResourceScatterUpdatewith float32 updates on a bfloat16 variable (the shared-lock branch) and string updates on a float32 variable (the exclusive-lock branch), fresh and in copy-on-read mode.testAssignUpdateRejectsVariableOfAnotherDtyperunsAssignAddVariableOpandAssignSubVariableOpwith a float32 value on a bfloat16 variable. Both entercontext.eager_mode(), since in a graph the handle's shape inference already rejects these withValueError: Trying to read variable with wrong dtypebefore the kernel runs. They pin to CPU and need no new imports or BUILD deps either.Verification
I couldn't build TensorFlow locally, so I checked against the TF 2.21.0 pip package:
Check failed: dtype() == expected_dtype (14 vs. 1). With the variables changed to float32 and the error assertions removed, both pass and every op call runs, so they fail only because of the dtype mismatch.training_op_helpers.hthat call the helpers the way the kernels do:MaybeLockVariableInputMutexesInOrderfollowed byGetInputTensorFromVariable(dense and sparse), andEnsureSparseVariableAccessfollowed by the lock and the check as inScatterNdUpdateOp. With master's header, the dense and sparse paths abort with and without copy-on-read mode, and the scatter path aborts in copy-on-read mode. With this PR's header all six cases raiseInvalidArgumentErrorwith the message above, and matching dtypes still update the variable in every mode.ResourceScatterUpdateand assign tests fail on 2.21.0 on the message alone: each case getsDType of scatter resource and updates does not match.orDType of variable handle and value does not match.from the branch it targets. With custom ops that makeResourceScatterUpdateOp's andAssignUpdateVariableOp's checks as this PR does, using itstraining_op_helpers.h, and with the tests' calls routed to them, both tests pass, and matching dtypes (float32, bfloat16 and string scatter updates, fresh and in copy-on-read mode, and float32 and bfloat16AssignAddandAssignSub) still update the variable.#124045 tried to fix this and was closed as stale. This covers the points from its review: the sparse path no longer depends on the status that
MaybeLockVariableInputMutexesInOrderignores,ResourceScatterNdUpdateis covered, and the tests useassertRaisesRegex, run on CPU, and add no imports.