Skip to content

fix: reject resource variable dtype mismatch in training ops - #124045

Closed
Ashutosh0x wants to merge 6 commits into
tensorflow:masterfrom
Ashutosh0x:fix/resource-var-dtype-mismatch
Closed

Ashutosh0x wants to merge 6 commits into
tensorflow:masterfrom
Ashutosh0x:fix/resource-var-dtype-mismatch

Conversation

@Ashutosh0x

Copy link
Copy Markdown
Contributor

Summary

A training op's T attr is inferred from its value inputs and is independent of the dtype of the resource variable it updates, so a graph can pair a float32 op with a float64 or bfloat16 variable. Nothing validates that pairing, and both code paths in training_op_helpers.h go on to read the variable as T:

  • GetInputTensorFromVariable → PrepareToUpdateVariable → flat<T>()
  • EnsureSparseVariableAccess → flat<T>() (when the tensor's refcount is not 1)

Tensor::flat<T>() CHECK-fails on a dtype mismatch, so the process aborts instead of returning InvalidArgument.

Fixes #113074 (ResourceApplyGradientDescent) and #113145 (ResourceSparseApplyAdagrad).

Reproduction

Verified against tf-nightly 2.22.0-dev20260726:

import numpy as np, tensorflow as tf
from tensorflow.python.ops import gen_training_ops

var = tf.Variable(tf.zeros([4, 2], dtype=tf.float64))
gen_training_ops.resource_apply_gradient_descent(
    var.handle, np.float32(0.1), tf.constant(np.zeros((4, 2)), tf.float32))
F0000 tensor.cc:967] Check failed: dtype() == expected_dtype (2 vs. 1)  float expected, got double
*** Check failure stack trace: ***

The same abort reproduces on the sparse path via resource_sparse_apply_adagrad, and with bfloat16 in place of float64 (which is what the two issues report).

Fix

Validate the variable's dtype against T in the two helpers, rather than patching each of the 72 GetInputTensorFromVariable call sites in training_ops.cc. This covers the whole Resource*Apply* family, including ops with no filed issue yet.

Both helpers need the check, for different reasons:

  • GetInputTensorFromVariable is what actually surfaces the error to the user.
  • EnsureSparseVariableAccess runs earlier on the sparse path, from MaybeLockVariableInputMutexesInOrder, and does its own flat<T>() copy whenever the refcount is not 1. Its caller discards the status by design (.IgnoreError()), so the guard there only prevents the abort — the reported error still comes from GetInputTensorFromVariable.

No behaviour that previously worked can be affected: any mismatch that reaches these helpers today ends in a CHECK failure.

Tests

Adds testResourceApplyOpsRejectDtypeMismatch to tensorflow/python/training/training_ops_test.py, covering both the dense and sparse paths across four ops, in the style of the existing testSparseApplyOpsRejectLowerRankGrad.

I could not build TensorFlow from source on this machine, so the reproduction above is verified against nightly but the fix itself is not runtime-verified — it rests on the CI build and tests.

@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium 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 prevents process crashes by raising an InvalidArgumentError instead of triggering a CHECK failure when a resource variable's data type does not match the training op's expected type. This validation is added to both sparse and dense variable retrieval paths in training_op_helpers.h, and a regression test suite is introduced. The feedback suggests improving the robustness of these new tests by using assertRaisesRegex to explicitly verify the error message, preventing false positives from unrelated failures.

Comment on lines +604 to +606
for apply_op in cases:
with self.assertRaises(errors.InvalidArgumentError):
self.evaluate(apply_op())

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.

medium

Using assertRaises without checking the error message can lead to false positives in tests (e.g., if the op fails due to an uninitialized variable or shape mismatch instead of the expected dtype mismatch). It is highly recommended to use assertRaisesRegex to verify that the specific error message is returned.

Suggested change
for apply_op in cases:
with self.assertRaises(errors.InvalidArgumentError):
self.evaluate(apply_op())
for apply_op in cases:
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"Trying to read a resource variable of dtype double as float",
):
self.evaluate(apply_op())
References
  1. Ensure tests cover edge cases and expected behavior precisely. (link)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — applied in 2a551b2. A bare assertRaises would have passed if the op failed for an unrelated reason, and all four cases produce the same message here since var is float64 against a float32 T:

      with self.assertRaisesRegex(
          errors.InvalidArgumentError,
          'Trying to read a resource variable of dtype double as float',
      ):

While checking this I also traced the other two callers of EnsureSparseVariableAccess outside training_ops.cc, since unlike the training ops they surface the status through OP_REQUIRES_OK rather than discarding it:

  • ResourceStridedSliceAssign (strided_slice_op.cc:337) already performs exactly this dtype check — but after the EnsureSparseVariableAccess call, so it has the same ordering problem: when the variable's refcount is not 1, the flat<T>() copy aborts before the check runs. The new guard closes that too. The reported message changes to the one above; no test asserts the old "l-value dtype ... does not match r-value dtype" string.
  • ResourceScatterNdUpdate (scatter_nd_op.cc:308) has no validation on the resource path at all — there's a literal // TODO(apassos): what to validate here? — so it gains the check.

Neither can regress a working call, since any mismatch reaching those points today ends in a CHECK failure.

@keerthanakadiri
keerthanakadiri requested a review from a team July 27, 2026 04:31
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Jul 27, 2026
@keerthanakadiri keerthanakadiri added the prtype:bugfix PR to fix a bug label Jul 27, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue 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.

Hi @Ashutosh0x,
Thanks for the PR. Before we can merge this, we need a few adjustments:

  1. Move Dtype Validation to the Top of EnsureSparseVariableAccess

    • Currently, if (var->tensor()->dtype() != DataTypeToEnum<T>::v()) is placed after the early return if (var->tensor()->RefCountIsOne()) return absl::OkStatus();.
    • Because RefCountIsOne() is typically true for unshared variables, EnsureSparseVariableAccess returns early and skips the dtype check. As a result, callers relying on it (such as ResourceScatterNdUpdate in scatter_nd_op.cc:308) will still crash with a CHECK failure when RefCountIsOne() is true.
    • Action: Please move the dtype check to the very beginning of EnsureSparseVariableAccess in training_op_helpers.h, before any copy_on_read_mode or RefCountIsOne() checks.
  2. Expand Test Coverage (Execution Modes & Mixed Precision)

    • In training_ops_test.py, decorate testResourceApplyOpsRejectDtypeMismatch with @test_util.run_in_graph_and_eager_modes so both Eager and Graph modes are verified (see existing tests in training_ops_test.py for reference).
    • Please also add test cases for mixed-precision pairings (e.g., float32 ops against bfloat16 or float16 resource variables), not just float64 vs. float32.
  3. Add Unit Tests for Affected Non-Training Ops

    • Since ResourceStridedSliceAssign and ResourceScatterNdUpdate are also affected by the EnsureSparseVariableAccess change, please add unit tests asserting InvalidArgumentError on dtype mismatch in their test files (strided_slice_op_test.py and scatter_nd_ops_test.py).

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/resource-var-dtype-mismatch branch from 2a551b2 to db781ea Compare July 29, 2026 17:15
@Ashutosh0x

Copy link
Copy Markdown
Contributor Author

@sgarciagoogle Thanks — all three are in db781ea, rebased onto master (which also clears the RELEASE.md conflict).

1. Check moved to the top of EnsureSparseVariableAccess, before the copy_on_read_mode and RefCountIsOne() returns. Your reading of ResourceScatterNdUpdate is right: DoCompute passes params = *v->tensor() straight into DoScatterNd<Device, T, ...>, so the unshared case did still abort. The unlocked read is safe — a Var's dtype is fixed at construction (Var(DataType dtype) : tensor_(dtype)) and the copy-on-read assignment allocates its replacement with that same dtype.

2. testResourceApplyOpsRejectDtypeMismatch now carries @test_util.run_in_graph_and_eager_modes and covers float64, bfloat16 and float16 variables against float32 ops.

3. Tests for both affected ops — one deviation: there is no strided_slice_op_test.py in the tree. The strided-slice-assign coverage lives in SliceAssignTest in kernel_tests/array_ops/array_ops_test.py, so testResourceStridedSliceAssignRejectsDtypeMismatch went there beside the existing testTypeErrorResource; scatter-nd went into StatefulScatterNdTest. Both call the generated ops directly, since the Python v[:].assign(...) path type-checks before the kernel is reached.

One behaviour change to confirm you are happy with: on the RefCountIsOne path ResourceStridedSliceAssign previously reached its own OP_REQUIRES and reported l-value dtype ... does not match r-value dtype; it now returns this helper's message instead. That path errored rather than crashed before, so it is the only change beyond crash prevention. The old string appears only in strided_slice_op.cc and no test asserts it.

Still not runtime-verified locally — no source build on this machine, so it rests on CI.

@Ashutosh0x

Copy link
Copy Markdown
Contributor Author

Also dropped the RELEASE.md entry from this PR, per your note on #124034 that the 2.22.0 release notes are curated internally. The PR is now the kernel header plus the three test files; nothing else changed.

@Ashutosh0x
Ashutosh0x force-pushed the fix/resource-var-dtype-mismatch branch from db781ea to 05efec5 Compare July 29, 2026 17:24

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

Hi @Ashutosh0x,

Thank you for addressing the previous review comments.

There is one small blocker before we can merge: the GPU CI jobs (build-linux-x86-cuda and build-linux-x86-cuda13) are currently failing on testResourceApplyOpsRejectDtypeMismatch.

Why it failed

ResourceSparseApplyAdagrad and ResourceSparseApplyMomentum are CPU-only kernels (registered only on DEVICE_CPU). When running under @test_util.run_in_graph_and_eager_modes on a GPU runner, Eager mode attempts to place them on the GPU by default. This raises an InvalidArgumentError due to missing GPU op registration rather than reaching the dtype mismatch check in the kernel, causing assertRaisesRegex to fail.

Steps to make the PR merge-ready

In tensorflow/python/training/training_ops_test.py, please scope the test execution to CPU using with ops.device('/CPU:0'): (or with ops.device('CPU'):) and use standard TF dtypes for consistency:

  @test_util.run_in_graph_and_eager_modes
  def testResourceApplyOpsRejectDtypeMismatch(self):
    # Regression test for #113074 and #113145: the op's `T` attr is inferred
    # from the value inputs and is independent of the variable's dtype, so a
    # float32 op can be paired with a float64 variable. Both the dense and the
    # sparse path then read the variable as `T` through Tensor::flat<T>(),
    # which CHECK-fails and aborts the process.
    #
    # The narrower dtypes are the mixed-precision shape of the same bug, and
    # the one the two issues actually report: a float32 training op applied to
    # a half or bfloat16 variable.
    with ops.device('/CPU:0'):
      for var_dtype, dtype_name in (
          (dtypes.float64, 'double'),
          (dtypes.bfloat16, 'bfloat16'),
          (dtypes.float16, 'half'),
      ):
        var = resource_variable_ops.ResourceVariable(
            array_ops.ones((4, 2), dtype=var_dtype)
        )
        accum = resource_variable_ops.ResourceVariable(
            array_ops.ones((4, 2), dtype=var_dtype)
        )
        self.evaluate(variables.global_variables_initializer())
        s = np.float32(0.1)
        grad = np.zeros((4, 2), np.float32)
        sparse_grad = np.zeros((1, 2), np.float32)
        idx = constant_op.constant([0], dtypes.int32)
        g = gen_training_ops
        cases = [
            lambda: g.resource_apply_gradient_descent(var.handle, s, grad),  # pylint: disable=cell-var-from-loop
            lambda: g.resource_apply_adagrad(var.handle, accum.handle, s, grad),  # pylint: disable=cell-var-from-loop
            lambda: g.resource_sparse_apply_adagrad(  # pylint: disable=cell-var-from-loop
                var.handle, accum.handle, s, sparse_grad, idx
            ),
            lambda: g.resource_sparse_apply_momentum(  # pylint: disable=cell-var-from-loop
                var.handle, accum.handle, s, sparse_grad, idx, s
            ),
        ]
        for apply_op in cases:
          with self.assertRaisesRegex(
              errors.InvalidArgumentError,
              'Trying to read a resource variable of dtype %s as float'
              % dtype_name,
          ):
            self.evaluate(apply_op())

Once this update is pushed and the CUDA CI passes, let us know and we will be happy to review again!

@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Aug 11, 2026
@github-actions

Copy link
Copy Markdown

This PR is stale because it has been open for 14 days with no activity. It will be closed if no further activity occurs. Thank you.

@github-actions github-actions Bot added the stale This label marks the issue/pr stale - to be closed automatically if no activity label Aug 26, 2026
@dmiltr3
dmiltr3 self-requested a review September 1, 2026 15:58
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Sep 1, 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.

1. Missing BUILD Dependency

tensorflow/core/kernels/training_op_helpers.h includes absl/strings/str_cat.h, but the training_op_helpers target in tensorflow/core/kernels/BUILD is missing "@com_google_absl//absl/strings" in deps. Please update deps in tensorflow/core/kernels/BUILD:

cc_library(
    name = "training_op_helpers",
    srcs = ["training_op_helpers.cc"],
    hdrs = ["training_op_helpers.h"],
    visibility = [
        ":friends",
        ":optimizer_helper_friends",
    ],
    deps = [
        ":dense_update_functor",
        ":variable_ops",
        "//tensorflow/core:framework",
        "//tensorflow/core:lib",
        "//tensorflow/tsl/platform:mutex",
        "@com_google_absl//absl/status",
        "@com_google_absl//absl/strings",
    ],
)

2. XLA Bridge Error Message Matching in Unit Tests

When tests run under XLA compilation (e.g. scatter_nd_ops_test_xla_gpu or training_ops_test_xla_gpu), XLA's tf2xla bridge formats the dtype mismatch error as:

Trying to read variable with wrong dtype. Expected float got double

whereas the standard C++ kernel returns:

Trying to read a resource variable of dtype double as float

To prevent test assertion failures under XLA execution, update assertRaisesRegex in:

tensorflow/python/kernel_tests/array_ops/scatter_nd_ops_test.py:

      with self.assertRaisesRegex(
          errors.InvalidArgumentError,
          r"(Trying to read a resource variable of dtype %s as float|Trying to read variable with wrong dtype)"
          % dtype_name,
      ):

tensorflow/python/training/training_ops_test.py:

      for apply_op in cases:
        with self.assertRaisesRegex(
            errors.InvalidArgumentError,
            r"(Trying to read a resource variable of dtype %s as float|Trying to read variable with wrong dtype)"
            % dtype_name,
        ):
          self.evaluate(apply_op())

3. CI Check Failure Analysis

The failures observed in CI/build-linux-x86-cuda and CI/build-linux-x86-cuda13 were caused by runner container execution errors (ScriptExecutorError: Executing the custom container implementation failed), which are self-hosted runner infrastructure flakes rather than code regressions.

@github-actions github-actions Bot removed stale This label marks the issue/pr stale - to be closed automatically if no activity stat:awaiting response Status - Awaiting response from author labels Sep 2, 2026
@Ashutosh0x

Copy link
Copy Markdown
Contributor Author

Thanks @dmiltr3 — all three addressed in 779f706, along with @sgarciagoogle's outstanding item.

@sgarciagoogle's CPU scoping (2fa180a). This is my fault for the delay: I made this change on 26 Aug and never pushed it, so the branch has been sitting with the CUDA failure you diagnosed still in it. It is on the branch now. The test body is wrapped in ops.device('/CPU:0') — variables included, so the resource lives on the same device as the kernel that reads it — and the variables are built from TF dtypes via array_ops.ones rather than the numpy equivalents, as you suggested.

1. BUILD dep. Added:

        "@com_google_absl//absl/status",
        "@com_google_absl//absl/strings",
        "@tsl//tsl/platform:mutex",

Correct catch, and it is an omission this PR introduced — the header only gained #include "absl/strings/str_cat.h" because of the new error messages, so it was building on a transitive dep. One deviation from your snippet: the target in the tree has "@tsl//tsl/platform:mutex", not "//tensorflow/tsl/platform:mutex", so I added only the missing absl/strings line rather than replacing the block.

2. XLA message matching. Both files updated to accept either wording. Split across two implicit-concatenated raw strings, since the single-line form runs past 80 columns at this indent:

            r'(Trying to read a resource variable of dtype %s as float'
            r'|Trying to read variable with wrong dtype)' % dtype_name,

I verified the pattern rather than assuming it: matched against both real message formats — the kernel's from training_op_helpers.h and the bridge's from xla_op_kernel.cc:566 — for all three dtypes under test (double, bfloat16, half), and confirmed the previous pattern does not match the XLA wording, which is the failure you predicted.

I also applied it to array_ops_test.py, which you did not name. All three targets are cuda_py_strict_test with no xla_enable_strict_auto_jit override, and that macro emits a <name>_xla_gpu variant for every non-cpu config, so the ResourceStridedSliceAssign assertion has exactly the same exposure as the other two. Widening an assertRaisesRegex cannot turn a passing test red — it only accepts more — so covering it costs nothing and avoids finding out in a later CI round. Happy to revert that one file if you would rather keep the change to what you specified.

3. CI failures. Agreed on the earlier CUDA runs. Worth flagging separately that the runs from this morning are red for a different and unrelated reason — dependency fetch fails before anything is compiled:

ERROR: An error occurred during the fetch of repository 'llvm-raw':
Error in patch: ... could not apply patch due to CONTENT_DOES_NOT_MATCH_TARGET,
error applying change near line 255
ERROR: Error computing the main repository mapping: no such package '@@llvm-raw//utils/bazel'

That is repo-wide right now, not specific to this PR: every CI run in that window failed the same way, including internal exported PRs #126623, #126624, #126625, #126626, #126510 and #126607. The builds die in 1–5 minutes against the usual 90–146, which is the giveaway. Nothing to do on this branch for it.

Still not runtime-verified locally — no source build on this machine — so the kernel change continues to rest on CI.

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

Unused / Missing Dependency in training_ops_test.py

In tensorflow/python/training/training_ops_test.py, importing from tensorflow.python.ops import array_ops causes strict dependency violations in downstream test targets that do not declare a direct dependency on array_ops.

Please remove from tensorflow.python.ops import array_ops and use constant_op.constant(1.0, shape=(4, 2), dtype=var_dtype) (using the already-imported constant_op) instead:

      for var_dtype, dtype_name in (
          (dtypes.float64, 'double'),
          (dtypes.bfloat16, 'bfloat16'),
          (dtypes.float16, 'half'),
      ):
        var = resource_variable_ops.ResourceVariable(
            constant_op.constant(1.0, shape=(4, 2), dtype=var_dtype)
        )
        accum = resource_variable_ops.ResourceVariable(
            constant_op.constant(1.0, shape=(4, 2), dtype=var_dtype)
        )

@Ashutosh0x

Copy link
Copy Markdown
Contributor Author

Thanks @dmiltr3 — addressed in 5379d83.

array_ops import. Removed, and both variables now come from the
already-imported constant_op:

var = resource_variable_ops.ResourceVariable(
    constant_op.constant(1.0, shape=(4, 2), dtype=var_dtype)
)

Confirmed the diagnosis before changing anything: the training_ops_test
target lists //tensorflow/python/framework:constant_op but not
//tensorflow/python/ops:array_ops, so the import this PR added was a strict
-deps violation. array_ops had no other use in the file, so the import line
is gone rather than left dangling.

I verified the substitution is actually equivalent rather than assuming it —
constant_op.constant(1.0, shape=(4, 2), dtype=...) against
array_ops.ones((4, 2), dtype=...) for all three dtypes under test, matching
on dtype, shape and value:

double    dtype=float64   shape=(4, 2) equal=True all_ones=True
bfloat16  dtype=bfloat16  shape=(4, 2) equal=True all_ones=True
half      dtype=float16   shape=(4, 2) equal=True all_ones=True

One more of the same, in a file you did not name. Checking whether the
violation was isolated, it was not: this PR also added
from tensorflow.python.ops import gen_state_ops to scatter_nd_ops_test.py,
and that target declares //tensorflow/python/ops:state_ops without
state_ops_gen. state_ops does depend on state_ops_gen, but transitively,
which is exactly the kind of luck strict deps exists to reject. Declared it
directly, matching cast_op_test, which imports gen_state_ops and lists
state_ops_gen for the same reason. The generated op is needed there — the
state_ops wrapper type-checks in Python before the kernel is reached, so it
cannot exercise the check under test.

array_ops_test.py needs no equivalent change: its gen_array_ops import
predates this PR and array_ops_gen is already declared.

@sgarciagoogle — your CPU-scoping item is on the branch too, in 2fa180a,
along with the TF-dtype variable construction you asked for. That one was my
delay rather than a disagreement: I made the change on 26 Aug and did not push
it until yesterday, so the CUDA failure you diagnosed sat on the branch far
longer than it should have. Both of your review items should now be covered.

As before, the kernel change itself is not runtime-verified locally — no
source build on this machine — so it continues to rest on CI. The checks above
are Python-level and were run against a real TensorFlow install. CI is
re-running on 5379d83 now; the earlier red was the repo-wide llvm-raw patch
failure, which master cleared later the same day.

dmiltr3
dmiltr3 previously approved these changes Sep 2, 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 changes correctly reject resource variable dtype mismatches in training ops and sparse variable access helpers, preventing process crashes and ensuring clean error propagation. All test targets pass cleanly. Approving the pull request.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Sep 2, 2026
@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 awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Sep 3, 2026
A training op's `T` attr is inferred from its value inputs and is
independent of the dtype of the resource variable it updates, so a graph
can pair a float32 op with a float64 or bfloat16 variable. Both paths in
training_op_helpers.h then read the variable as `T`:

  * GetInputTensorFromVariable -> PrepareToUpdateVariable -> flat<T>()
  * EnsureSparseVariableAccess -> flat<T>() (when the refcount is not 1)

Tensor::flat<T>() CHECK-fails on a dtype mismatch, so the process aborts
with

  F tensor.cc:967] Check failed: dtype() == expected_dtype (2 vs. 1)
    float expected, got double

instead of returning InvalidArgument. Verified against tf-nightly
2.22.0-dev20260726 for both the dense and sparse paths.

Validating in these two helpers covers the whole Resource*Apply* family
rather than patching each of the 72 call sites in training_ops.cc. The
status from EnsureSparseVariableAccess is ignored by its caller by
design, so GetInputTensorFromVariable is what surfaces the error.

Fixes tensorflow#113074
Fixes tensorflow#113145
Use assertRaisesRegex rather than a bare assertRaises so the test cannot
pass for an unrelated reason, such as an uninitialized variable or a
shape mismatch.
The check sat after the copy_on_read_mode and RefCountIsOne early
returns, so it only ran on the path that performs the copy. An unshared
variable -- the common case -- returns at RefCountIsOne, which left
ResourceScatterNdUpdate still aborting: it has no dtype validation of
its own and relies entirely on this helper. Moved to the top, before
any early return.

Reading the dtype without the mutex is safe: a Var's dtype is fixed at
construction and the copy-on-read assignment preserves it.

Also extends the regression tests:

  - training_ops_test.py runs in both graph and eager modes and covers
    bfloat16 and float16 variables alongside float64, which is the
    mixed-precision pairing the two issues actually report.
  - ResourceScatterNdUpdate and ResourceStridedSliceAssign gain their
    own dtype-mismatch tests, since the reordering is what makes the
    first safe and changes which error the second reports.

ResourceStridedSliceAssign already validated the pairing itself, so on
the RefCountIsOne path it returned InvalidArgument rather than crashing;
it now reports this helper's message instead of its own "l-value dtype"
one. No test asserted the old string.
ResourceSparseApplyMomentum is registered only on DEVICE_CPU, so under
run_in_graph_and_eager_modes on a GPU runner eager mode placed it on GPU
and raised a "no kernel registered" InvalidArgumentError before reaching
the dtype check, failing assertRaisesRegex on the CUDA CI jobs.

Wrap the whole test body in ops.device('/CPU:0') so the variables live on
the same device as the kernels that read them, and build them from TF
dtypes via array_ops.ones instead of the numpy equivalents.
Two things, both from review.

The BUILD dep is a real omission introduced by this PR: the header gained
#include "absl/strings/str_cat.h" for the new error messages, but the
training_op_helpers target never declared @com_google_absl//absl/strings.
It builds today only by transitive luck through another target, which is
exactly what layering_check exists to catch.

The test assertions now accept either wording. The kernel returns
"Trying to read a resource variable of dtype double as float", but under
XLA the tf2xla bridge intercepts the read first and formats it as
"Trying to read variable with wrong dtype. Expected float got double"
(xla_op_kernel.cc:566), so the _xla_gpu variants of these targets would
fail on the narrower pattern.

Applied to array_ops_test.py as well as the two files named in review.
All three targets are cuda_py_strict_test with no xla override, and that
macro emits a <name>_xla_gpu variant for every non-cpu config, so the
strided-slice assertion has the same exposure as the other two. Widening
an assertRaisesRegex cannot turn a passing test red -- it only accepts
more -- so covering it now costs nothing and avoids a third CI round.

Verified locally: both patterns matched against both real message formats
for all three dtypes (double, bfloat16, half), and confirmed the previous
pattern does not match the XLA wording, which is the failure predicted in
review. Python syntax checks clean, all changed lines within 80 columns.
training_ops_test.py imported array_ops solely to build the two variables
in testResourceApplyOpsRejectDtypeMismatch, but the training_ops_test
target does not declare //tensorflow/python/ops:array_ops, so the import
was a strict-deps violation introduced by this PR. constant_op is already
a declared dep and already used in the same test for the index tensor, so
constant_op.constant(1.0, shape=(4, 2), dtype=var_dtype) is a drop-in
replacement; verified equivalent to array_ops.ones for float64, bfloat16
and float16 in dtype, shape and value.

The same violation was in scatter_nd_ops_test.py, which is not in review
but has the identical shape: this PR added a gen_state_ops import for
resource_scatter_nd_update, and the scatter_nd_ops_test target declares
//tensorflow/python/ops:state_ops without state_ops_gen. state_ops does
depend on state_ops_gen, but transitively, which strict deps does not
accept. Declared it directly, matching cast_op_test, which imports
gen_state_ops and lists state_ops_gen for the same reason. The generated
op is required here: the state_ops wrapper type-checks in Python before
the kernel is reached, so it cannot exercise the check under test.

array_ops_test.py needs no equivalent change; its gen_array_ops import
predates this PR and array_ops_gen is already declared.
@Ashutosh0x
Ashutosh0x force-pushed the fix/resource-var-dtype-mismatch branch from 5379d83 to fcecf5e Compare September 3, 2026 08:00
@nithyak0204 nithyak0204 removed the stat:awaiting response Status - Awaiting response from author label Sep 3, 2026
@nithyak0204
nithyak0204 requested a review from dmiltr3 September 3, 2026 14:04
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Sep 3, 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.

Crash on Resource Variable Dtype Mismatch in Training Ops

The changes in tensorflow/core/kernels/training_op_helpers.h only validate var->tensor()->dtype() != DataTypeToEnum<T>::value when sparse is false. When sparse is true, GetInputTensorFromVariable bypasses this check:

    if (sparse) {
      var->mu()->assert_held_shared();
      *out = *var->tensor();
      return absl::OkStatus();
    }

Although EnsureSparseVariableAccess includes the dtype check, its return value is explicitly discarded via .IgnoreError() in GetInputLockingVariableInputLockHolder:

  if (sparse) {
    for (Var* var : vars) {
      EnsureSparseVariableAccess<Device, T>(ctx, var).IgnoreError();
    }
  }

Because EnsureSparseVariableAccess returns early when var->copy_on_read_mode is already true and its status is ignored by the caller, sparse training ops like resource_sparse_apply_adagrad and resource_sparse_apply_momentum proceed with the mismatched tensor. When the kernel subsequently calls out->flat<T>(), it triggers a fatal CHECK failure that aborts the process:

F tensor.cc:967] Check failed: dtype() == expected_dtype (2 vs. 1)  float expected, got double
Fatal Python error: Aborted

Required Fix

Validate the dtype in GetInputTensorFromVariable before checking the sparse flag so that both sparse and dense operations are guarded:

template <typename Device, typename T>
absl::Status GetInputTensorFromVariable(OpKernelContext* ctx, int input,
                                        bool lock_held, bool sparse,
                                        Tensor* out) {
  if (ctx->input_dtype(input) == DT_RESOURCE) {
    core::RefCountPtr<Var> var;
    ResourceHandle handle;
    TF_RETURN_IF_ERROR(HandleFromInput(ctx, input, &handle));
    TF_RETURN_IF_ERROR(LookupResource(ctx, handle, &var));
    if (var->tensor()->dtype() != DataTypeToEnum<T>::value) {
      return errors::InvalidArgument(
          "Trying to read a resource variable of dtype ",
          DataTypeString(var->tensor()->dtype()), " as ",
          DataTypeString(DataTypeToEnum<T>::value));
    }
    if (sparse) {
      var->mu()->assert_held_shared();
      *out = *var->tensor();
      return absl::OkStatus();
    }
    var->mu()->assert_held();
    TF_RETURN_IF_ERROR(PrepareToUpdateVariable<Device, T>(
        ctx, var->tensor(), var->copy_on_read_mode.load()));
    *out = *var->tensor();
    return absl::OkStatus();
  }
  *out = ctx->mutable_input(input, lock_held);
  return absl::OkStatus();
}

@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Sep 3, 2026
@github-actions

Copy link
Copy Markdown

This PR is stale because it has been open for 14 days with no activity. It will be closed if no further activity occurs. Thank you.

@github-actions github-actions Bot added the stale This label marks the issue/pr stale - to be closed automatically if no activity label Sep 18, 2026
@github-actions

github-actions Bot commented Oct 2, 2026

Copy link
Copy Markdown

This PR was closed because it has been inactive for 14 days since being marked as stale. Please reopen if you'd like to work on this further.

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 size:M CL Change Size: Medium stale This label marks the issue/pr stale - to be closed automatically if no activity stat:awaiting response Status - Awaiting response from author

Projects

Status: Closed/Rejected

Development

Successfully merging this pull request may close these issues.

tf.raw.ops.ResourceApplyGradientDescent aborts with internal CHECK failure on dtype mismatch instead of raising an error

6 participants