PR #124930

tensorflow/tensorflow · XLA · Merged · 2 files changed

In XLA's TensorArrayScatterOp, a missing rank >= 1 invariant check prior to RemoveDim(0) allowed rank-0 scalar tensors to trigger out-of-bounds shape indexing and fatal segmentation faults during compilation. This contribution introduces an explicit compile-time OP_REQUIRES guard and an end-to-end XLA regression test.

Checkout Pull Request

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

$gh pr checkout 124930 --repo tensorflow/tensorflow
Causal & File Impact Graph (PR #124930)XLA / Merged
INPUT / TRIGGERXLA Edge CaseROOT CAUSEMissing InvariantPATCHED (2 FILES)tensor_array_ops_t...tensor_array_ops.ccOUTCOMEMerged

In XLA's TensorArrayScatterOp, a missing rank >= 1 invariant check prior to RemoveDim(0) allowed rank-0 scalar tensors to trigger out-of-bounds shape indexing and fatal segmentation faults during compilation. This contribution introduces an explicit compile-time OP_REQUIRES guard and an end-to-end XLA regression test.

File-by-File Modification Breakdown (2)

  • tensorflow/compiler/tests/tensor_array_ops_test.py

    Python/XLA regression test suite verifying edge-case behavior

    +14 / -0
  • tensorflow/compiler/tf2xla/kernels/tensor_array_ops.cc

    XLA C++ kernel shape-lowering and compile-time invariant checks

    +4 / -0

Changed Files (2)

tensorflow/compiler/tests/tensor_array_ops_test.py20 lines
@@ -1165,5 +1165,19 @@ def fn():
       self.assertEqual(size0_v, 2)
       self.assertEqual(size1_v, 4)
 
+  @test_util.disable_control_flow_v2("TensorArray.scatter in XLA")
+  def testTensorArrayScatterScalarRaisesError(self):
+    with self.session() as session, self.test_scope():
+      scalar = array_ops.placeholder(dtypes.float32, shape=None)
+
+      def fn():
+        ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=3)
+        return ta.scatter(indices=[0], value=scalar).flow
+
+      with self.assertRaisesRegex(
+          errors.InvalidArgumentError,
+          "scatter/unstack requires value to have rank >= 1, got scalar"):
+        session.run(xla.compile(fn), feed_dict={scalar: 1.0})
+
 if __name__ == "__main__":
   test.main()

1. Introduction & Motivation

Compiled execution in TensorFlow via XLA relies on strict static shape inference during the lowering phase from TensorFlow graph nodes to HLO (High Level Optimizer) instructions [1]. Unlike eager execution, where Python runtime checks or dynamic tensor metadata can raise informative exceptions early, XLA kernel constructors operate directly on C++ TensorShape descriptors. When a kernel assumes a structural invariant that the frontend did not enforce, the compiler can dereference invalid dimension offsets and terminate with a segmentation fault rather than a diagnostic error.

In TensorArrayScatterOp, the operator scatters a batch of values into designated indices of a TensorArray. By contract, the scattered input tensor must have at least one leading dimension corresponding to the index axis, with the remaining dimensions matching the element shape of the array. However, the XLA kernel omitted a rank check before stripping axis 0, leaving the compiler vulnerable whenever a user passed a rank-0 scalar tensor.

2. Root-Cause Mechanics & Shape Formulation

Let VV denote the input tensor with shape tuple shape(V)=(d0,d1,…,dk−1)∈Nk\text{shape}(V) = (d_0, d_1, \dots, d_{k-1}) \in \mathbb{N}^k, where k=dims(V)k = \text{dims}(V) is the tensor rank. Scattering elements along axis 00 requires decomposing VV into slice elements whose shape is obtained by projecting away the first coordinate:

k=dims(V)≥1,element_shape(V)=proj⁡[1,k)(shape(V))=(d1,…,dk−1)(1)k = \text{dims}(V) \ge 1, \qquad \text{element\_shape}(V) = \operatorname{proj}_{[1, k)}(\text{shape}(V)) = (d_1, \dots, d_{k-1}) \tag{1}

When a rank-0 scalar is supplied (k=0k = 0), the projection interval [1,0)[1, 0) in Equation (1) is ill-formed. Calling value_shape.RemoveDim(0) attempts to erase a non-existent dimension from an empty dimension vector, causing undefined memory behavior inside XLA lowering.

Input Rank kkBefore FixAfter Fix
k=0k = 0 (scalar)Out-of-bounds RemoveDim(0) segfaultClean InvalidArgumentError
k≥1k \ge 1 (tensor)Lowers slice shape (d1,…,dk−1)(d_1, \dots, d_{k-1})Unchanged XLA lowering

3. Implementation & Code Walkthrough

In tensorflow/compiler/tf2xla/kernels/tensor_array_ops.cc, I inserted an explicit OP_REQUIRES precondition immediately after retrieving ctx->InputShape(2) and before acquiring the XlaResource or invoking RemoveDim(0):

const TensorShape value_shape = ctx->InputShape(2);
OP_REQUIRES(ctx, value_shape.dims() >= 1,
            errors::InvalidArgument(
                "TensorArray scatter/unstack requires value to have rank >= 1, "
                "got scalar with shape ",
                value_shape.DebugString()));

4. Empirical Verification

In tensorflow/compiler/tests/tensor_array_ops_test.py, I authored testTensorArrayScatterScalarRaisesError, which constructs a scalar placeholder, lowers ta.scatter through xla.compile, and verifies that TensorFlow cleanly raises InvalidArgumentError instead of crashing the compiler process.

5. References

  1. XLA Team, XLA: Optimizing Compiler for Machine Learning (Shape & HLO Semantics), TensorFlow Architecture Documentation [2].
  2. Anandhu P Shaji, Hunting Compiler Bugs and Numerical Traps in TensorFlow, anandhupshaji.me/posts/tensorflow-stories.html#xla-compiler-segfault.
View PR #124930 on GitHubRead technical story

The soul becomes dyed with the color of its thoughts.

Marcus Aurelius

Made with <3 and lots of coffee.