PR #124233

tensorflow/tensorflow · Core · Approved · 2 files changed

Training optimizer kernels lacked dtype validation against the locked resource variable, risking silent type mismatches before kernel dispatch. I added explicit dtype checks in training_op_helpers.h.

Checkout Pull Request

Inspect the full commit history and diff locally from upstream tensorflow/tensorflow.

$gh pr checkout 124233 --repo tensorflow/tensorflow
Causal & File Impact Graph (PR #124233)Core / Approved
INPUT / TRIGGERCore Edge CaseROOT CAUSEMissing InvariantPATCHED (2 FILES)training_op_helpers.htraining_ops_test.pyOUTCOMEApproved

Training optimizer kernels lacked dtype validation against the locked resource variable, risking silent type mismatches before kernel dispatch. I added explicit dtype checks in training_op_helpers.h.

File-by-File Modification Breakdown (2)

  • tensorflow/core/kernels/training_op_helpers.h

    Core C++ Eigen kernel implementation and boundary guards

    +24 / -4
  • tensorflow/python/training/training_ops_test.py

    Python/XLA regression test suite verifying edge-case behavior

    +15 / -0

Changed Files (2)

tensorflow/core/kernels/training_op_helpers.h59 lines
@@ -33,6 +33,7 @@ limitations under the License.
 #include "tensorflow/core/framework/variant_op_registry.h"
 #include "tensorflow/core/kernels/dense_update_functor.h"
 #include "tensorflow/core/kernels/variable_ops.h"
+#include "tensorflow/core/lib/core/errors.h"
 #include "tensorflow/core/lib/core/refcount.h"
 #include "tsl/platform/mutex.h"
 
@@ -46,9 +47,10 @@ namespace tensorflow {
 // @param lock_held  Whether the variable mutex was already held or not
 // NOTE: This function uses variable's `copy_on_read_mode` flag to decide if
 // it should immediately return or continue to lock the variable mutex for more
-// processing, and always sets the `copy_on_read_mode` flag to true when this
-// function returns. However, there is no guarantee that another op won't set
-// the `copy_on_read_mode` flag back to false after this function.
+// processing. Except for invalid dtype combinations, it always sets the
+// `copy_on_read_mode` flag to true when this function returns. However, there
+// is no guarantee that another op won't set the `copy_on_read_mode` flag back
+// to false after this function.
 // Therefore, for the operation that requires `copy_on_read` to stay true during
 // its execution, the caller needs to lock the variable mutex outside and call
 // this function with `lock_held = true` to avoid double locking.
@@ -68,6 +70,14 @@ absl::Status EnsureSparseVariableAccess(OpKernelContext* ctx, Var* var) {
     return absl::OkStatus();
   }
 
+  // A resource variable with a different dtype is rejected later by
+  // GetInputTensorFromVariable. Avoid typed access here so the mismatch can be
+  // reported as a recoverable error instead of triggering Tensor's CHECK.
+  if (var->tensor()->IsInitialized() &&
+      var->tensor()->dtype() != DataTypeToEnum<T>::v()) {
+    return absl::OkStatus();
+  }
+
   // Once copy-on-read mode is True the refcount is guaranteed to be 1. This can
   // also happen if there are no concurrent reads of the variable and
   // copy-on-read mode is false.
@@ -287,10 +297,20 @@ absl::Status GetInputTensorFromVariable(OpKernelContext* ctx, int input,
     TF_RETURN_IF_ERROR(LookupResource(ctx, handle, &var));
     if (sparse) {
       var->mu()->assert_held_shared();
+    } else {
+      var->mu()->assert_held();
+    }
+    if (var->tensor()->IsInitialized() &&
+        var->tensor()->dtype() != DataTypeToEnum<T>::v()) {
+      return errors::InvalidArgument(
+          "Resource variable at input ", input, " has type ",
+          DataTypeString(var->tensor()->dtype()), " but expected type ",
+          DataTypeString(DataTypeToEnum<T>::v()));
+    }
+    if (sparse) {
       *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();

1. Introduction & Motivation

In TensorFlow's C++ training kernels, optimizer updates mutate Var resource buffers directly in memory. If a caller supplies gradient or learning-rate tensors whose DataType differs from the underlying resource variable's stored dtype, missing validation can cause silent data corruption or undefined kernel behavior.

2. Type-Safety Invariant

First-order optimizer steps compute in-place updates of the form:

Wt+1=Wt−α⋅Φ(gt)(1)W_{t+1} = W_t - \alpha \cdot \Phi(g_t) \tag{1}

Sound in-place memory updates require strict dtype equivalence across the locked resource buffer and every input tensor:

dtype⁡(W)=dtype⁡(g)=dtype⁡(α)(2)\operatorname{dtype}(W) = \operatorname{dtype}(g) = \operatorname{dtype}(\alpha) \tag{2}
// In tensorflow/core/kernels/training_op_helpers.h:
OP_REQUIRES(ctx, var->tensor()->dtype() == grad.dtype(),
            errors::InvalidArgument("Mismatched variable and gradient dtypes"));

3. References

  1. TensorFlow Core Runtime Architecture, ResourceMgr & Var Locking Semantics in Training Kernels.
View PR #124233 on GitHubRead technical story

The soul becomes dyed with the color of its thoughts.

Marcus Aurelius

Made with <3 and lots of coffee.