Repository navigation
fix: reject resource variable dtype mismatch in training ops - #124045
Ashutosh0x wants to merge 6 commits into
Conversation
There was a problem hiding this comment.
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.
| for apply_op in cases: | ||
| with self.assertRaises(errors.InvalidArgumentError): | ||
| self.evaluate(apply_op()) |
There was a problem hiding this comment.
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.
| 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
- Ensure tests cover edge cases and expected behavior precisely. (link)
There was a problem hiding this comment.
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 theEnsureSparseVariableAccesscall, so it has the same ordering problem: when the variable's refcount is not 1, theflat<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.
sgarciagoogle
left a comment
There was a problem hiding this comment.
Hi @Ashutosh0x,
Thanks for the PR. Before we can merge this, we need a few adjustments:
-
Move Dtype Validation to the Top of
EnsureSparseVariableAccess- Currently,
if (var->tensor()->dtype() != DataTypeToEnum<T>::v())is placed after the early returnif (var->tensor()->RefCountIsOne()) return absl::OkStatus();. - Because
RefCountIsOne()is typicallytruefor unshared variables,EnsureSparseVariableAccessreturns early and skips the dtype check. As a result, callers relying on it (such asResourceScatterNdUpdateinscatter_nd_op.cc:308) will still crash with aCHECKfailure whenRefCountIsOne()istrue. - Action: Please move the dtype check to the very beginning of
EnsureSparseVariableAccessintraining_op_helpers.h, before anycopy_on_read_modeorRefCountIsOne()checks.
- Currently,
-
Expand Test Coverage (Execution Modes & Mixed Precision)
- In
training_ops_test.py, decoratetestResourceApplyOpsRejectDtypeMismatchwith@test_util.run_in_graph_and_eager_modesso both Eager and Graph modes are verified (see existing tests intraining_ops_test.pyfor reference). - Please also add test cases for mixed-precision pairings (e.g.,
float32ops againstbfloat16orfloat16resource variables), not justfloat64vs.float32.
- In
-
Add Unit Tests for Affected Non-Training Ops
- Since
ResourceStridedSliceAssignandResourceScatterNdUpdateare also affected by theEnsureSparseVariableAccesschange, please add unit tests assertingInvalidArgumentErroron dtype mismatch in their test files (strided_slice_op_test.pyandscatter_nd_ops_test.py).
- Since
Thank you!
2a551b2 to
db781ea
Compare
|
@sgarciagoogle Thanks — all three are in 1. Check moved to the top of 2. 3. Tests for both affected ops — one deviation: there is no One behaviour change to confirm you are happy with: on the Still not runtime-verified locally — no source build on this machine, so it rests on CI. |
|
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. |
db781ea to
05efec5
Compare
sgarciagoogle
left a comment
There was a problem hiding this comment.
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!
|
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. |
dmiltr3
left a comment
There was a problem hiding this comment.
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.
|
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 1. BUILD dep. Added: Correct catch, and it is an omission this PR introduced — the header only gained 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 I also applied it to 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: 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
left a comment
There was a problem hiding this comment.
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)
)|
Thanks @dmiltr3 — addressed in 5379d83. array_ops import. Removed, and both variables now come from the Confirmed the diagnosis before changing anything: the I verified the substitution is actually equivalent rather than assuming it — One more of the same, in a file you did not name. Checking whether the array_ops_test.py needs no equivalent change: its @sgarciagoogle — your CPU-scoping item is on the branch too, in 2fa180a, As before, the kernel change itself is not runtime-verified locally — no |
dmiltr3
left a comment
There was a problem hiding this comment.
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.
|
Hi @Ashutosh0x, Can you please resolve the conflicts? Thank you! |
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.
5379d83 to
fcecf5e
Compare
dmiltr3
left a comment
There was a problem hiding this comment.
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();
}|
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. |
|
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. |
Summary
A training op's
Tattr 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 intraining_op_helpers.hgo on to read the variable asT: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 returningInvalidArgument.Fixes #113074 (
ResourceApplyGradientDescent) and #113145 (ResourceSparseApplyAdagrad).Reproduction
Verified against
tf-nightly 2.22.0-dev20260726:The same abort reproduces on the sparse path via
resource_sparse_apply_adagrad, and withbfloat16in place offloat64(which is what the two issues report).Fix
Validate the variable's dtype against
Tin the two helpers, rather than patching each of the 72GetInputTensorFromVariablecall sites intraining_ops.cc. This covers the wholeResource*Apply*family, including ops with no filed issue yet.Both helpers need the check, for different reasons:
GetInputTensorFromVariableis what actually surfaces the error to the user.EnsureSparseVariableAccessruns earlier on the sparse path, fromMaybeLockVariableInputMutexesInOrder, and does its ownflat<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 fromGetInputTensorFromVariable.No behaviour that previously worked can be affected: any mismatch that reaches these helpers today ends in a
CHECKfailure.Tests
Adds
testResourceApplyOpsRejectDtypeMismatchtotensorflow/python/training/training_ops_test.py, covering both the dense and sparse paths across four ops, in the style of the existingtestSparseApplyOpsRejectLowerRankGrad.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.