Repository navigation
Fix fatal process abort on resource variable dtype mismatch in training ops - #128701
Conversation
…ng ops Validate variable dtype against target dtype T in GetInputTensorFromVariable and PrepareToUpdateVariable before accessing typed tensor buffers, preventing fatal CheckTypeAndIsAligned abort crashes on dtype mismatches. Fixes tensorflow#113145. Signed-off-by: bodapatisaikrishna <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request adds dtype validation checks in PrepareToUpdateVariable and GetInputTensorFromVariable to prevent fatal crashes when a resource variable's dtype does not match the expected optimizer dtype, raising an InvalidArgumentError instead. It also includes corresponding unit tests to verify this behavior. The reviewer noted that the validation check added to PrepareToUpdateVariable is redundant because GetInputTensorFromVariable already performs the same check, and suggested removing it to avoid unnecessary overhead in the hot path.
| if (tensor->IsInitialized() && tensor->dtype() != DataTypeToEnum<T>::v()) { | ||
| return absl::InvalidArgumentError(absl::StrCat( | ||
| "dtype mismatch: expected ", DataTypeString(DataTypeToEnum<T>::v()), | ||
| " but got ", DataTypeString(tensor->dtype()))); | ||
| } |
There was a problem hiding this comment.
This dtype validation is redundant because GetInputTensorFromVariable already performs the exact same validation for both resource variables (lines 301-307) and reference variables (lines 320-324) before the tensor is passed to PrepareToUpdateVariable. Since training ops are executed in the hot path of model training, removing this duplicate check avoids unnecessary overhead.
References
- Identify unnecessary memory usage or redundant computations. (link)
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the fix! This PR successfully identifies and addresses the CheckTypeAndIsAligned fatal abort caused by dtype mismatches in training op variables.
However, we need to adjust how uninitialized variables are handled. By gating the dtype checks on IsInitialized(), uninitialized resource variables of the wrong dtype bypass the validation and fall through to the !tensor->RefCountIsOne() branch in PrepareToUpdateVariable. Because uninitialized tensors have a null buffer, RefCountIsOne() is false. This forces an allocation of a temporary tensor of the mismatched dtype, and the subsequent call to tmp.flat<T>() triggers the exact same fatal CHECK abort this PR intends to fix.
Additionally, EnsureSparseVariableAccess attempts to copy uninitialized tensors, which leads to similar crashes.
Please apply the following changes to unconditionally validate the dtype for resource variables and safely early-return when they are uninitialized (allowing them to fail gracefully downstream with FailedPreconditionError):
1. Fix PrepareToUpdateVariable
In tensorflow/core/kernels/training_op_helpers.h, update PrepareToUpdateVariable to check dtype unconditionally and return early if uninitialized:
template <typename Device, typename T>
absl::Status PrepareToUpdateVariable(OpKernelContext* ctx, Tensor* tensor,
bool copy_on_read_mode) {
if (tensor->dtype() != DataTypeToEnum<T>::v()) {
return absl::InvalidArgumentError(absl::StrCat(
"dtype mismatch: expected ", DataTypeString(DataTypeToEnum<T>::v()),
" but got ", DataTypeString(tensor->dtype())));
}
if (!tensor->IsInitialized()) {
return absl::OkStatus();
}
if (copy_on_read_mode || !tensor->RefCountIsOne()) {2. Fix GetInputTensorFromVariable
In tensorflow/core/kernels/training_op_helpers.h, update the resource variable path in GetInputTensorFromVariable to unconditionally check the dtype (remove the is_initialized bypass):
TF_RETURN_IF_ERROR(LookupResource(ctx, handle, &var));
if (var->tensor()->dtype() != DataTypeToEnum<T>::v()) {
return absl::InvalidArgumentError(absl::StrCat(
"dtype mismatch: expected ", DataTypeString(DataTypeToEnum<T>::v()),
" but got ", DataTypeString(var->tensor()->dtype()),
" (resource variable dtype)"));
}
if (sparse) {(Note: Do not remove the IsInitialized() check in the reference variable path at the bottom of the function, as uninitialized reference variables genuinely default to DT_FLOAT and should not trigger a dtype error).
3. Fix EnsureSparseVariableAccess
In tensorflow/core/kernels/training_op_helpers.h, update EnsureSparseVariableAccess to return early for uninitialized tensors so we don't attempt to copy them:
if (var->tensor()->dtype() != DataTypeToEnum<T>::v()) {
return absl::InvalidArgumentError(absl::StrCat(
"dtype mismatch: expected ", DataTypeString(DataTypeToEnum<T>::v()),
" but got ", DataTypeString(var->tensor()->dtype()),
" (resource variable dtype)"));
}
if (!var->tensor()->IsInitialized()) {
return absl::OkStatus();
}
if (var->tensor()->RefCountIsOne()) {4. Add regression tests for uninitialized variables
In tensorflow/python/training/training_ops_test.py, add a test to verify that uninitialized variables correctly raise InvalidArgumentError (if dtype mismatches) or FailedPreconditionError (if dtype matches) instead of aborting the process:
@test_util.run_v2_only
def testResourceVariableUninitialized(self):
from tensorflow.python.ops import gen_resource_variable_ops
var_uninit_f32 = gen_resource_variable_ops.var_handle_op(
dtype=dtypes.float32, shape=[1, 2]
)
var_uninit_f16 = gen_resource_variable_ops.var_handle_op(
dtype=dtypes.float16, shape=[1, 2]
)
lr = constant_op.constant(0.1, dtype=dtypes.float16)
grad = constant_op.constant([[0.1, 0.2]], dtype=dtypes.float16)
# Mismatched dtype should raise InvalidArgumentError
with self.assertRaisesRegex(
errors.InvalidArgumentError, "dtype mismatch"
):
self.evaluate(
gen_training_ops.resource_apply_gradient_descent(
var=var_uninit_f32,
alpha=lr,
delta=grad,
)
)
# Matched dtype should raise FailedPreconditionError
with self.assertRaisesRegex(
errors.FailedPreconditionError, "uninitialized"
):
self.evaluate(
gen_training_ops.resource_apply_gradient_descent(
var=var_uninit_f16,
alpha=lr,
delta=grad,
)
)Unconditionally validate resource variable dtype in training op helpers and return early when tensors are uninitialized so downstream ops can gracefully report errors without crashing. Signed-off-by: bodapatisaikrishna <[email protected]>
|
Updated the dtype checks to validate unconditionally and early-return if uninitialized, and added the regression tests. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the fix! This PR successfully identifies and addresses the CheckTypeAndIsAligned fatal abort caused by dtype mismatches in training op variables.
By adding unconditional dtype validation to GetInputTensorFromVariable, EnsureSparseVariableAccess, and PrepareToUpdateVariable, the change ensures that variables with mismatched types trigger an absl::InvalidArgumentError instead of falling through to typed buffer access functions. The checks correctly test the dtype before checking IsInitialized(), preventing uninitialized tensors with the wrong dtype from bypassing the check.
The regression tests extensively assert that mismatched inputs produce InvalidArgumentError while properly initialized ones preserve the FailedPreconditionError.
We have one minor nit for code hygiene:
1. Move in-function imports to module level (P2)
In tensorflow/python/training/training_ops_test.py, context and gen_resource_variable_ops are imported inside testResourceVariableUninitialized:
from tensorflow.python.eager import context
from tensorflow.python.ops import gen_resource_variable_opsPlease move these imports to the top-level import block of the file. Lazy in-function imports should be avoided in favor of proper module structure.
|
Done, moved the imports to module level. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates! The change successfully fixes the fatal process abort in training ops triggered by dtype mismatches by guarding GetInputTensorFromVariable and EnsureSparseVariableAccess. Returning absl::OkStatus() for uninitialized variables in PrepareToUpdateVariable cleanly shifts the responsibility for generating FailedPreconditionError downstream. The regression tests effectively pin the InvalidArgumentError and FailedPreconditionError responses. The previous import restructuring recommendation has been applied.
However, the change in PrepareToUpdateVariable leaves the exact same fatal abort unfixed in one of its callers, AssignUpdateVariableOp. We have a few remaining requests below to close this gap and isolate the new tests properly.
Incomplete Fix: Uninitialized Variable Fatal Abort in AssignUpdateVariableOp
By making PrepareToUpdateVariable return absl::OkStatus() for uninitialized variables, callers are now responsible for checking IsInitialized() before calling var_tensor->flat<T>(). While training ops do this correctly, AssignUpdateVariableOp (which handles AssignAddVariableOp and AssignSubVariableOp in tensorflow/core/kernels/resource_variable_ops.cc) lacks an IsInitialized() check. It only validates shapes. If an uninitialized resource variable (default shape []) and a scalar value (shape []) are passed, shape validation succeeds. PrepareToUpdateVariable returns OkStatus(), and the op proceeds to call var_tensor->flat<T>(), hitting the exact same CHECK(IsInitialized()) fatal abort we aim to fix.
Please add an explicit initialization check in AssignUpdateVariableOp to prevent this fatal abort, bringing it to parity with the fix in the training ops.
tensorflow/core/kernels/resource_variable_ops.cc:649
mutex_lock ml(*variable->mu());
Tensor* var_tensor = variable->tensor();
OP_REQUIRES(context, var_tensor->IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ", handle.name()));
OP_REQUIRES_OK(context, ValidateAssignUpdateVariableOpShapes(
var_tensor->shape(), value.shape()));Test Hygiene: Reused shared_name in Eager Mode
In testResourceVariableUninitialized, the shared_name is evaluated once and reused for var_uninit_f32, var_uninit_f16, and accum_uninit_f16. In eager mode, var_handle_op with the same shared_name and container resolves to the exact same underlying resource slot, meaning all three handles alias the same variable. While the assertions still pass because the underlying variable is uninitialized, this violates test isolation. Each variable should receive a unique anonymous name.
tensorflow/python/training/training_ops_test.py:755
var_uninit_f32 = gen_resource_variable_ops.var_handle_op(
dtype=dtypes.float32, shape=[1, 2],
shared_name=(context.anonymous_name() if context.executing_eagerly() else "")
)
var_uninit_f16 = gen_resource_variable_ops.var_handle_op(
dtype=dtypes.float16, shape=[1, 2],
shared_name=(context.anonymous_name() if context.executing_eagerly() else "")
)
accum_uninit_f16 = gen_resource_variable_ops.var_handle_op(
dtype=dtypes.float16, shape=[1, 2],
shared_name=(context.anonymous_name() if context.executing_eagerly() else "")
)Graph Mode Coverage
The new tests testResourceVariableDtypeMismatch and testResourceVariableUninitialized are restricted to eager mode via @test_util.run_v2_only. Since training ops and resource variables are supported and commonly used in graph mode (and the CheckTypeAndIsAligned fatal abort is fully possible during graph execution), please verify the fix in graph mode as well by replacing the decorator with @test_util.run_in_graph_and_eager_modes.
|
Pushed a fix with that check added, gave each variable an anonymous name in the test, and enabled graph mode coverage. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for the updates! The implementation successfully prevents fatal process aborts caused by dtype mismatches and uninitialized resource variables in training operations and AssignUpdateVariableOp. The regression tests thoroughly cover both graph and eager execution modes and correctly assert expected error types and messages.
However, shifting the initialization responsibility downwards from EnsureSparseVariableAccess left a few sibling scatter/gather operations vulnerable to the exact same failure class.
P1: Incomplete Fix: Uninitialized Variable Fatal Aborts in Scatter/Gather Callers
By early-returning absl::OkStatus() from EnsureSparseVariableAccess for uninitialized variables, all callers of this helper must explicitly check IsInitialized() before accessing the returned tensor's buffer or shape.
ResourceScatterUpdateOp, ResourceGatherOp, and ResourceGatherNdOp in tensorflow/core/kernels/resource_variable_ops.cc, as well as ScatterNdUpdateOp in tensorflow/core/kernels/scatter_nd_op.cc, currently lack this check. This allows uninitialized variables (which have a 0-D shape) to bypass early validation. Subsequently, ops crash the process upon dim_size(0) access, or return a misleading InvalidArgumentError instead of the canonical FailedPreconditionError.
Please add the missing IsInitialized() assertions after locking the mutex in all these callers to match the fix pattern used in AssignUpdateVariableOp. Expand the test cases to verify these operations fail gracefully on uninitialized resource variables.
tensorflow/core/kernels/resource_variable_ops.cc:1194 (ResourceScatterUpdateOp)
const bool is_non_pod_dtype =
update_dtype == DT_STRING || update_dtype == DT_VARIANT;
if (is_non_pod_dtype || use_exclusive_lock_) {
mutex_lock ml(*v->mu());
OP_REQUIRES(c, v->tensor()->IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ",
handle.name()));
OP_REQUIRES(c, v->tensor()->dtype() == update_dtype,
absl::InvalidArgumentError(
"DType of scatter resource and updates does not match."));
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(c, v->tensor()->IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ",
handle.name()));
OP_REQUIRES(c, v->tensor()->dtype() == update_dtype,
absl::InvalidArgumentError(
"DType of scatter resource and updates does not match."));
DoCompute(c, v.get());
}tensorflow/core/kernels/resource_variable_ops.cc:770 (ResourceGatherOp)
tf_shared_lock ml(*v->mu());
OP_REQUIRES(c, v->tensor()->IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ",
handle.name()));
OP_REQUIRES(
c, v->tensor()->dtype() == DataTypeToEnum<T>::v(),
absl::InvalidArgumentError(absl::StrCat(
"dtype mismatch: expected ", DataTypeString(DataTypeToEnum<T>::v()),
" but got ", DataTypeString(v->tensor()->dtype()),
" (resource variable dtype)")));tensorflow/core/kernels/resource_variable_ops.cc:963 (ResourceGatherNdOp)
tf_shared_lock ml(*v->mu());
OP_REQUIRES(c, v->tensor()->IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ",
handle.name()));
OP_REQUIRES(
c, v->tensor()->dtype() == DataTypeToEnum<T>::v(),
absl::InvalidArgumentError(absl::StrCat(
"dtype mismatch: expected ", DataTypeString(DataTypeToEnum<T>::v()),
" but got ", DataTypeString(v->tensor()->dtype()),
" (resource variable dtype)")));tensorflow/core/kernels/scatter_nd_op.cc:292 (ScatterNdUpdateOp)
mutex_lock m(*v->mu());
OP_REQUIRES(c, v->tensor()->IsInitialized(),
errors::FailedPrecondition(
"Attempting to use uninitialized variables: ",
handle.name()));
DoCompute(c);|
Added the initialization checks across ResourceScatterUpdateOp, ResourceGatherOp, ResourceGatherNdOp, and ScatterNdUpdateOp, and expanded the test cases to verify each of them fails gracefully on uninitialized variables. |
dmiltr3
left a comment
There was a problem hiding this comment.
Correction to our earlier review: We apologize for the extra review rounds and retract our earlier requests from the previous reviews to add IsInitialized() early returns in tensorflow/core/kernels/training_op_helpers.h, to add IsInitialized() and dtype checks in tensorflow/core/kernels/resource_variable_ops.cc and tensorflow/core/kernels/scatter_nd_op.cc, and to add testResourceVariableUninitialized in tensorflow/python/training/training_ops_test.py. In TensorFlow's Var implementation (tensorflow/core/framework/resource_var.h), Var(DataType dtype) constructs its underlying Tensor(DataType) with a 1-D {0} shape (num_elements() == 0), for which Tensor::IsInitialized() always returns true. Because of this, the v->tensor()->IsInitialized() checks on Var never trigger, and in eager mode an uninitialized VarHandleOp fails downstream shape validation with InvalidArgumentError (shape [0] vs [1, 2]), whereas in graph mode a non-anonymous VarHandleOp (shared_name="") does not register a Var in ResourceMgr until AssignVariableOp runs, causing lookup to fail with InternalError or NotFoundError. Meanwhile, placing the unconditional dtype check at the top of PrepareToUpdateVariable and GetInputTensorFromVariable already rejects dtype-mismatched resource variables before !tensor->RefCountIsOne() or flat<T>() is reached.
Please apply the following cleanup to return the PR to its minimal, passing state:
1. Revert tensorflow/core/kernels/resource_variable_ops.cc and tensorflow/core/kernels/scatter_nd_op.cc
Revert all changes in tensorflow/core/kernels/resource_variable_ops.cc and tensorflow/core/kernels/scatter_nd_op.cc so both files match master.
2. Remove the dead IsInitialized() early returns in tensorflow/core/kernels/training_op_helpers.h
In tensorflow/core/kernels/training_op_helpers.h, remove if (!var->tensor()->IsInitialized()) { return absl::OkStatus(); } from EnsureSparseVariableAccess (lines 79-81) and if (!tensor->IsInitialized()) { return absl::OkStatus(); } from PrepareToUpdateVariable (lines 254-256), keeping only the dtype validation in PrepareToUpdateVariable and GetInputTensorFromVariable:
template <typename Device, typename T>
absl::Status PrepareToUpdateVariable(OpKernelContext* ctx, Tensor* tensor,
bool copy_on_read_mode) {
if (tensor->dtype() != DataTypeToEnum<T>::v()) {
return absl::InvalidArgumentError(absl::StrCat(
"dtype mismatch: expected ", DataTypeString(DataTypeToEnum<T>::v()),
" but got ", DataTypeString(tensor->dtype())));
}
if (copy_on_read_mode || !tensor->RefCountIsOne()) {3. Remove testResourceVariableUninitialized and unused imports in tensorflow/python/training/training_ops_test.py
In tensorflow/python/training/training_ops_test.py, delete testResourceVariableUninitialized (lines 754-920) along with the imports added for it (from tensorflow.python.eager import context, from tensorflow.python.ops import gen_resource_variable_ops, and from tensorflow.python.ops import gen_state_ops at lines 22, 31-32), keeping testResourceVariableDtypeMismatch (lines 703-752).
|
Reverted resource_variable_ops.cc and scatter_nd_op.cc, removed the unneeded initialization checks, and pruned the tests to keep just the dtype mismatch coverage. |
dmiltr3
left a comment
There was a problem hiding this comment.
Thank you for applying the cleanup from the previous review round. The changes in tensorflow/core/kernels/training_op_helpers.h and tensorflow/python/training/training_ops_test.py are clean, minimal, and pass standard CPU and GPU test suites.
One internal presubmit test failure remains in the XLA GPU variant of training_ops_test (training_ops_test_xla_gpu), which runs training_ops_test.py with XLA auto-clustering enabled (--tf_xla_auto_jit=2):
1. Disable XLA auto-clustering on testResourceVariableDtypeMismatch (tensorflow/python/training/training_ops_test.py:700)
When testResourceVariableDtypeMismatch runs with XLA auto-clustering enabled, gen_training_ops.resource_apply_gradient_descent is compiled through the XLA bridge (XlaOpKernelContext::ReadVariableInput) rather than executing the C++ runtime kernel in tensorflow/core/kernels/training_op_helpers.h. The XLA bridge raises InvalidArgumentError: Trying to read variable with wrong dtype. Expected half got float, which bypasses the C++ helper check under test and fails the assertRaisesRegex(errors.InvalidArgumentError, "dtype mismatch") assertion in both eager and graph modes.
Please decorate testResourceVariableDtypeMismatch with @test_util.disable_xla so the test always exercises the C++ runtime kernel validation in training_op_helpers.h:
@test_util.run_in_graph_and_eager_modes
@test_util.disable_xla("Tests C++ kernel validation in training_op_helpers.h")
def testResourceVariableDtypeMismatch(self):|
Added @test_util.disable_xla to testResourceVariableDtypeMismatch so it exercises the C++ kernel validation directly. |
Calling resource variable training ops (such as
tf.raw_ops.ResourceSparseApplyAdagradortf.raw_ops.ResourceApplyGradientDescent) with a resource variable whose dtype differs from the optimizer's target typeTcurrently aborts the runtime process with a fatal internalCHECKfailure:Cause
In
tensorflow/core/kernels/training_op_helpers.h,GetInputTensorFromVariableretrieves the underlying tensor from aDT_RESOURCEvariable handle viaLookupResourcewithout validating that the variable tensor's dtype matches target dtypeT. Because resource variables only specifyDT_RESOURCEat op registration, the op kernel proceeds with a type-mismatched tensor and invokes typed buffer access (flat<T>()/flat_outer_dims<T>()), hittingTensor::CheckTypeAndIsAligned()which terminates the process.Solution
GetInputTensorFromVariableandPrepareToUpdateVariableintraining_op_helpers.hto returnerrors::InvalidArgumenton dtype mismatches when the variable tensor is initialized.tensorflow/python/training/training_ops_test.pycovering resource variable dtype mismatches for both sparse and dense training ops.Fixes #113145.