Skip to content

Reject resource variables of another dtype in training and scatter ops - #128715

Open
vishwakt wants to merge 5 commits into
tensorflow:masterfrom
vishwakt:fix-resource-variable-dtype-mismatch
Open

vishwakt wants to merge 5 commits into
tensorflow:masterfrom
vishwakt:fix-resource-variable-dtype-mismatch

Conversation

@vishwakt

@vishwakt vishwakt commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #113074
Fixes #113145

Cause

A resource training op such as ResourceApplyGradientDescent or ResourceSparseApplyAdagrad takes its type T from 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} takes T from the updates in the same way. Reading the variable's tensor with flat<T>() then fails Check failed: dtype() == expected_dtype and aborts the process.

  • GetInputTensorFromVariable, which every resource training op goes through, never checks the dtype. On the dense path, PrepareToUpdateVariable copies a variable in copy-on-read mode with flat<T>(), and otherwise the kernel reads it with flat<T>(). On the sparse path, MaybeLockVariableInputMutexesInOrder calls EnsureSparseVariableAccess, which does check the dtype, but discards its status with IgnoreError().
  • ScatterNdUpdateOp relies on the check in EnsureSparseVariableAccess, 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

  • Factor the existing check in EnsureSparseVariableAccess into ValidateVariableDtype<T> in training_op_helpers.h, keeping its message: dtype mismatch: expected float but got bfloat16 (resource variable dtype). ResourceGather and ResourceGatherNd had the same check inline, under the same shared lock, and now call the helper instead. ResourceScatterUpdate and 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. AssignAddVariableOp and AssignSubVariableOp did the same with DType of variable handle and value does not match. and now call the helper as well.
  • Call it in both branches of GetInputTensorFromVariable, after the existing lock assertions and before PrepareToUpdateVariable.
  • Call it in ScatterNdUpdateOp once 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 (EnsureSparseVariableAccess does when it copies). That is why the check isn't moved above the early return in EnsureSparseVariableAccess, which comes before the lock. Matching dtypes behave as before.

Tests

  • training_ops_test.py: testResourceApplyOpsRejectVariableOfAnotherDtype runs ResourceApplyGradientDescent (dense path) and ResourceSparseApplyAdagrad (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: testResourceScatterNdUpdateRejectsVariableOfAnotherDtype does the same for ResourceScatterNdUpdate.
  • Both run in graph and eager mode, pin to CPU so they take the same path on GPU CI, and need no new imports or BUILD deps. They are marked 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: testResourceScatterUpdateRejectsVariableOfAnotherDtype runs ResourceScatterUpdate with 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. testAssignUpdateRejectsVariableOfAnotherDtype runs AssignAddVariableOp and AssignSubVariableOp with a float32 value on a bfloat16 variable. Both enter context.eager_mode(), since in a graph the handle's shape inference already rejects these with ValueError: Trying to read variable with wrong dtype before 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:

  • Both new tests abort the process on 2.21.0 with 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.
  • I compiled custom ops against the pip headers with this PR's training_op_helpers.h that call the helpers the way the kernels do: MaybeLockVariableInputMutexesInOrder followed by GetInputTensorFromVariable (dense and sparse), and EnsureSparseVariableAccess followed by the lock and the check as in ScatterNdUpdateOp. 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 raise InvalidArgumentError with the message above, and matching dtypes still update the variable in every mode.
  • The ResourceScatterUpdate and assign tests fail on 2.21.0 on the message alone: each case gets DType of scatter resource and updates does not match. or DType of variable handle and value does not match. from the branch it targets. With custom ops that make ResourceScatterUpdateOp's and AssignUpdateVariableOp's checks as this PR does, using its training_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 bfloat16 AssignAdd and AssignSub) 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 MaybeLockVariableInputMutexesInOrder ignores, ResourceScatterNdUpdate is covered, and the tests use assertRaisesRegex, run on CPU, and add no imports.

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.
@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Oct 9, 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 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.

@keerthanakadiri keerthanakadiri self-assigned this Oct 12, 2026
@keerthanakadiri
keerthanakadiri requested a review from a team October 12, 2026 08:02
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 12, 2026
@keerthanakadiri keerthanakadiri added the comp:core issues related to core part of tensorflow label Oct 12, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Oct 12, 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 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.cc lines 768-773 (in ResourceGatherOp) and lines 961-966 (in ResourceGatherNdOp).
  • Rationale: The change factors out ValidateVariableDtype in training_op_helpers.h to 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. Both ResourceGatherOp and ResourceGatherNdOp inside resource_variable_ops.cc (which already includes training_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();

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Oct 12, 2026
ResourceGather and ResourceGatherNd checked the variable's dtype inline
with the same message as ValidateVariableDtype, under the same shared
lock. Call the helper instead.
@vishwakt

Copy link
Copy Markdown
Contributor Author

Thanks @dmiltr3, done: ResourceGatherOp and ResourceGatherNdOp now call ValidateVariableDtype<T> under their shared lock in place of the inline check. The error message is unchanged, and these were the only other copies of it.

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

Copy link
Copy Markdown
Contributor Author

Thanks @dmiltr3, both done:

  1. ResourceScatterUpdateOp now calls ValidateVariableDtype<T> in both lock branches. It compared the variable's dtype with the updates' dtype, which the op ties to T, so the check is the same and only the message changes to the standard one; no test depends on the old message.
  2. Both new tests now run with @test_util.run_in_graph_and_eager_modes. With matching dtypes they pass in both modes on TF 2.21, and with the mismatched dtypes they still abort it, so they catch the bug in either mode.

@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 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)))
```

@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Oct 26, 2026
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.
@vishwakt

vishwakt commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @dmiltr3, both done in dd47a1b:

  1. AssignUpdateVariableOp now calls ValidateVariableDtype<T> after the shape check. It 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; no test depends on the old message.
  2. I added testResourceScatterUpdateRejectsVariableOfAnotherDtype to resource_variable_ops_test.py rather than scatter_ops_test.py, since that target is tagged no_oss and isn't run by default, and resource_variable_ops_test.py already has testGatherDtypeMismatch and testGatherNdDtypeMismatch. It calls resource_variable_ops.resource_scatter_update (state_ops has no resource_scatter_update), with float32 updates on a bfloat16 variable for the shared-lock branch and string updates on a float32 variable for the exclusive-lock branch, each fresh and in copy-on-read mode. Since AssignUpdateVariableOp changed too, testAssignUpdateRejectsVariableOfAnotherDtype does the same for AssignAddVariableOp and AssignSubVariableOp. Both run eagerly only: in a graph, the handle's shape inference already raises ValueError: Trying to read variable with wrong dtype before the kernel runs, which is also why the gather tests accept either error.

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.

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

vishwakt commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @dmiltr3, both done in 94b3020:

  1. Both new tests now enter context.eager_mode(). In the OSS CI they already ran eagerly and passed on dd47a1b, since --config=v2 sets TF2_BEHAVIOR=1, but with graph mode as the default the previous version raised ValueError: Trying to read variable with wrong dtype in every case, as you describe. With the explicit eager mode they reach the kernel either way.
  2. testResourceScatterNdUpdateRejectsVariableOfAnotherDtype and testResourceApplyOpsRejectVariableOfAnotherDtype now have @test_util.disable_xla("Tests C++ kernel validation").

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Nov 5, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Nov 5, 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 kokoro:force-run Tests on submitted change ready to pull PR ready for merge process size:M CL Change Size: Medium

Projects

Status: Approved by Reviewer

4 participants