PR #122823

tensorflow/tensorflow · Gradients · Merged (internal) · 3 files changed

Safeguarded tf.linalg.det and slogdet backward passes against gradient explosion and NaN contamination on singular matrices by using the continuous adjugate formulation.

Checkout Pull Request

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

$gh pr checkout 122823 --repo tensorflow/tensorflow
Causal & File Impact Graph (PR #122823)Gradients / Merged (internal)
INPUT / TRIGGERGradients Edge CaseROOT CAUSEMissing InvariantPATCHED (3 FILES)linalg_grad_test.pyBUILDlinalg_grad.pyOUTCOMEMerged (internal)

Safeguarded tf.linalg.det and slogdet backward passes against gradient explosion and NaN contamination on singular matrices by using the continuous adjugate formulation.

File-by-File Modification Breakdown (3)

  • tensorflow/python/kernel_tests/linalg/linalg_grad_test.py

    Python/XLA regression test suite verifying edge-case behavior

    +158 / -0
  • tensorflow/python/ops/BUILD

    Bazel build dependencies and test targets

    +1 / -0
  • tensorflow/python/ops/linalg_grad.py

    Automatic differentiation gradient rules for linear algebra ops

    +79 / -9

Changed Files (3)

tensorflow/python/kernel_tests/linalg/linalg_grad_test.py175 lines
@@ -16,9 +16,11 @@
 
 import numpy as np
 
+from tensorflow.python.eager import backprop
 from tensorflow.python.framework import constant_op
 from tensorflow.python.framework import test_util
 from tensorflow.python.ops import array_ops
+from tensorflow.python.ops import gen_linalg_ops
 from tensorflow.python.ops import gradient_checker_v2
 from tensorflow.python.ops import gradients_impl
 from tensorflow.python.ops import linalg_ops
@@ -179,6 +181,162 @@ def Test(self):
   return Test
 
 
+class DetGradSingularMatrixTest(test_lib.TestCase):
+  """Gradients of det and slogdet remain defined for singular matrices.
+
+  The holomorphic derivative of det(A) is the cofactor matrix, so the
+  reverse-mode gradient is its elementwise conjugate, conj(det(A)) * A^{-H}
+  for invertible A. For real A this is the transpose of the classical
+  adjugate, which extends continuously to singular A. These tests compare the
+  analytic gradient against the numerical one via gradient_checker_v2 for
+  real and complex, singular and invertible, and near-singular inputs, check
+  values against the closed-form adjugate, and confirm that slogdet's
+  backward pass stays finite for a singular matrix instead of raising.
+  """
+
+  @test_util.run_in_graph_and_eager_modes(use_gpu=False)
+  def testDetGradSingular2x2(self):
+    # det([[1, 2], [2, 4]]) == 0; its adjugate is [[4, -2], [-2, 1]].
+    m = np.array([[1.0, 2.0], [2.0, 4.0]], dtype=np.float64)
+    theoretical, _ = gradient_checker_v2.compute_gradient(
+        linalg_ops.matrix_determinant, [m])
+    self.assertAllClose([[4.0, -2.0, -2.0, 1.0]], theoretical[0])
+
+  @test_util.run_in_graph_and_eager_modes(use_gpu=False)
+  def testDetGradInvertible2x2(self):
+    # The adjugate of the invertible A = [[1, 2], [3, 4]] is [[4, -3], [-2, 1]].
+    m = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float64)
+    theoretical, numerical = gradient_checker_v2.compute_gradient(
+        linalg_ops.matrix_determinant, [m])
+    self.assertAllClose([[4.0, -3.0, -2.0, 1.0]], theoretical[0])
+    self.assertAllClose(theoretical[0], numerical[0], atol=1e-6)
+
+  @test_util.run_in_graph_and_eager_modes(use_gpu=False)
+  def testDetGradSingularFloat32(self):
+    m = np.array([[1.0, 2.0], [2.0, 4.0]], dtype=np.float32)
+    theoretical, _ = gradient_checker_v2.compute_gradient(
+        linalg_ops.matrix_determinant, [m])
+    self.assertAllClose([[4.0, -2.0, -2.0, 1.0]], theoretical[0], atol=1e-5)
+
+  @test_util.run_in_graph_and_eager_modes(use_gpu=False)
+  def testDetGradNearSingular(self):
+    # A = [[1, 1], [1, 1 + eps]] has det = eps and condition number ~4/eps.
+    # The gradient (adjugate transpose) is [[1 + eps, -1], [-1, 1]], which the
+    # SVD-based evaluation must reproduce without the loss of accuracy that
+    # forming eps * A^{-1} would incur at these condition numbers.
+    for eps in (1e-6, 1e-9, 1e-12):
+      m = constant_op.constant(
+          [[1.0, 1.0], [1.0, 1.0 + eps]], dtype=np.float64)
+      with backprop.GradientTape() as tape:
+        tape.watch(m)
+        d = linalg_ops.matrix_determinant(m)
+      grad = tape.gradient(d, m)
+      self.assertAllClose(
+          self.evaluate(grad), [[1.0 + eps, -1.0], [-1.0, 1.0]], atol=1e-9)
+
+  @test_util.run_in_graph_and_eager_modes(use_gpu=False)
+  def testDetGradNearSingularNumerical(self):
+    # The analytic gradient must also agree with the numerical one for a
+    # near-singular matrix (det = 1e-6, condition number ~4e6).
+    m = np.array([[1.0, 1.0], [1.0, 1.0 + 1e-6]], dtype=np.float64)
+    theoretical, numerical = gradient_checker_v2.compute_gradient(
+        linalg_ops.matrix_determinant, [m])
+    self.assertAllClose(theoretical[0], numerical[0], atol=1e-6)
+
+  @test_util.run_in_graph_and_eager_modes(use_gpu=False)
+  def testDetGradBatchWithSingular(self):
+    # A batch mixing a singular and an invertible matrix must produce the
+    # per-matrix adjugate for both entries.
+    m = constant_op.constant(
+        [[[1.0, 2.0], [2.0, 4.0]], [[1.0, 2.0], [3.0, 4.0]]], dtype=np.float64)
+    with backprop.GradientTape() as tape:
+      tape.watch(m)
+      d = linalg_ops.matrix_determinant(m)
+      total = math_ops.reduce_sum(d)
+    grad = tape.gradient(total, m)
+    self.assertIsNotNone(grad)
+    self.assertAllClose(
+        self.evaluate(grad),
+        [[[4.0, -2.0], [-2.0, 1.0]], [[4.0, -3.0], [-2.0, 1.0]]],
+        atol=1e-10)
+
+  @test_util.run_in_graph_and_eager_modes(use_gpu=False)
+  def testDetGradComplexInvertible(self):
+    # The reverse-mode gradient of det is conj(det(A)) * A^{-H}; compare the
+    # analytic gradient against both that closed form and the numerical
+    # Jacobian for complex64 and complex128.
+    for dtype, tol in ((np.complex64, 2e-2), (np.complex128, 1e-6)):
+      a = np.array(
+          [[1.0 + 1.0j, 2.0 - 1.0j], [3.0 + 0.5j, 4.0 + 2.0j]], dtype=dtype)
+      theoretical, numerical = gradient_checker_v2.compute_gradient(
+          linalg_ops.matrix_determinant, [a])
+      self.assertAllClose(theoretical[0], numerical[0], atol=tol)
+      m = constant_op.constant(a)
+      with backprop.GradientTape() as tape:
+        tape.watch(m)
+        d = linalg_ops.matrix_determinant(m)
+      grad = tape.gradient(d, m)
+      expected = math_ops.conj(d) * linalg_ops.matrix_inverse(m, adjoint=True)
+      self.assertAllClose(
+          self.evaluate(grad), self.evaluate(expected), atol=tol)
+
+  @test_util.run_in_graph_and_eager_modes(use_gpu=False)
+  def testDetGradComplexSingular(self):
+    # [[1+i, 2+2i], [2-i, 4-2i]] has det 0 (second row is conj-scaled first);
+    # the analytic gradient must match the numerical one instead of raising.
+    for dtype, tol in ((np.complex64, 2e-2), (np.complex128, 1e-6)):
+      a = np.array(
+          [[1.0 + 1.0j, 2.0 + 2.0j], [2.0 - 1.0j, 4.0 - 2.0j]], dtype=dtype)
+      theoretical, numerical = gradient_checker_v2.compute_gradient(
+          linalg_ops.matrix_determinant, [a])
+      self.assertAllClose(theoretical[0], numerical[0], atol=tol)
+
+  @test_util.run_in_graph_and_eager_modes(use_gpu=False)
+  def testSlogdetGradSingularDoesNotCrash(self):
+    # log|det(A)| is -inf for a singular A, so its gradient is undefined, but
+    # the backward pass must stay finite instead of raising.
+    m = constant_op.constant([[1.0, 2.0], [2.0, 4.0]], dtype=np.float64)
+    with backprop.GradientTape() as tape:
+      tape.watch(m)
+      _, log_abs_det = gen_linalg_ops.log_matrix_determinant(m)
+    grad = tape.gradient(log_abs_det, m)
+    self.assertIsNotNone(grad)
+    self.assertAllEqual(self.evaluate(math_ops.is_finite(grad)),
+                        [[True, True], [True, True]])
+
+  @test_util.run_in_graph_and_eager_modes(use_gpu=False)
+  def testSlogdetGradInvertibleUnchanged(self):
+    # For invertible A the gradient of log|det(A)| is A^{-H}; the
+    # pseudoinverse-based path must reproduce it for real and complex inputs.
+    a_real = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float64)
+    a_complex = np.array(
+        [[1.0 + 1.0j, 2.0 - 1.0j], [3.0 + 0.5j, 4.0 + 2.0j]],
+        dtype=np.complex128)
+    for a in (a_real, a_complex):
+      m = constant_op.constant(a)
+      with backprop.GradientTape() as tape:
+        tape.watch(m)
+        _, log_abs_det = gen_linalg_ops.log_matrix_determinant(m)
+      grad = tape.gradient(log_abs_det, m)
+      expected = linalg_ops.matrix_inverse(m, adjoint=True)
+      self.assertAllClose(
+          self.evaluate(grad), self.evaluate(expected), atol=1e-10)
+
+  @test_util.run_in_graph_and_eager_modes(use_gpu=False)
+  def testSlogdetGradComplexSingularDoesNotCrash(self):
+    m = constant_op.constant(
+        [[1.0 + 1.0j, 2.0 + 2.0j], [2.0 - 1.0j, 4.0 - 2.0j]],
+        dtype=np.complex128)
+    with backprop.GradientTape() as tape:
+      tape.watch(m)
+      _, log_abs_det = gen_linalg_ops.log_matrix_determinant(m)
+    grad = tape.gradient(log_abs_det, m)
+    self.assertIsNotNone(grad)
+    self.assertAllEqual(
+        self.evaluate(math_ops.is_finite(math_ops.abs(grad))),
+        [[True, True], [True, True]])
+
+
 if __name__ == '__main__':
   # Tests for gradients of binary matrix operations.
   for dtype in np.float32, np.float64:

1. Introduction & Motivation

Differentiable linear algebra layers frequently compute determinants of learned or intermediate matrices that can become rank-deficient during training. Because TensorFlow's _MatrixDeterminantGrad evaluated det⁡(A) A−T\det(A)\, A^{-T} via direct matrix inversion, singular matrices (det⁡(A)=0\det(A) = 0) triggered division by zero, gradient explosion, and NaN contamination across the entire backward pass [1].

2. Matrix Calculus & Singular Extension

By Jacobi's formula, for any invertible matrix A∈Rn×nA \in \mathbb{R}^{n \times n}, the differential of the determinant satisfies [2]:

d(det⁡A)=tr⁡(adj⁡(A) dA)  ⟹  ∇Adet⁡(A)=det⁡(A) A−T=adj⁡(A)T(1)d(\det A) = \operatorname{tr}\big(\operatorname{adj}(A)\, dA\big) \implies \nabla_A \det(A) = \det(A)\, A^{-T} = \operatorname{adj}(A)^T \tag{1}

Because each entry of the classical adjugate adj⁡(A)T\operatorname{adj}(A)^T is an (n−1)×(n−1)(n - 1) \times (n - 1) cofactor minor (a polynomial in the entries of AA), it requires zero division by det⁡(A)\det(A) and extends continuously across singular matrices:

A=(1224),det⁡(A)=0  ⟹  ∇Adet⁡(A)=adj⁡(A)T=(4−2−21)(2)A = \begin{pmatrix} 1 & 2 \\ 2 & 4 \end{pmatrix}, \quad \det(A) = 0 \implies \nabla_A \det(A) = \operatorname{adj}(A)^T = \begin{pmatrix} 4 & -2 \\ -2 & 1 \end{pmatrix} \tag{2}
Matrix Conditiondet⁡(A) A−T\det(A)\, A^{-T} (Before)Adjugate adj⁡(A)T\operatorname{adj}(A)^T (After)
Invertible (det⁡(A)≠0\det(A) \neq 0)Finite gradientIdentical finite gradient
Singular (det⁡(A)=0\det(A) = 0)NaN / inf crashExact continuous cofactor gradient

3. Implementation & Verification

# In tensorflow/python/kernel_tests/linalg/linalg_grad_test.py:
m = np.array([[1.0, 2.0], [2.0, 4.0]], dtype=np.float64)
theoretical, _ = gradient_checker_v2.compute_gradient(linalg_ops.matrix_determinant, [m])
self.assertAllClose([[4.0, -2.0, -2.0, 1.0]], theoretical[0])

4. References

  1. Giles, An Extended Collection of Matrix Derivative Results for Forward and Reverse Mode AD, 2008.
  2. Petersen & Pedersen, The Matrix Cookbook, Section 2.1 (Derivatives of Determinants).
  3. Anandhu P Shaji, Hunting Compiler Bugs and Numerical Traps in TensorFlow, anandhupshaji.me/posts/tensorflow-stories.html#singular-matrix-gradients.
View PR #122823 on GitHubRead technical story

The soul becomes dyed with the color of its thoughts.

Marcus Aurelius

Made with <3 and lots of coffee.