Skip to content

Fix tf.linalg.expm second derivative error under nested forward autodiff - #127627

Merged
copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/127224-expm-nested-forward-ad
Sep 21, 2026
Merged

copybara-service[bot] merged 4 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/127224-expm-nested-forward-ad

Conversation

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor

tf.linalg.expm returns an incorrect second derivative under nested forward-mode autodiff (tf.autodiff.ForwardAccumulator). Reported in #127224.

On the reproducer from the issue (evaluating $\frac{d^2}{dt^2} \sum \exp(A(t))$ for $A(t) = \begin{pmatrix} t & 1 \ -1 & t \end{pmatrix}$ at $t = 0.7$), the exact analytical second derivative is $2 e^{0.7} \cos(1) \approx 2.1760704625890157$. Nested forward autodiff returned 357356221.1760303, an error of $\approx 3.57 \times 10^8$.

Root Cause

In tensorflow/python/ops/linalg/linalg_impl.py, matrix_exponential implements the scaling and squaring method with Padé approximation based on Nicholas J. Higham (2005) ("The scaling and squaring method for the matrix exponential revisited", SIAM J. Matrix Anal. Applic., 26:1179-1193).

The Padé approximant functions (_matrix_exp_pade3, _matrix_exp_pade5, _matrix_exp_pade7, _matrix_exp_pade9, _matrix_exp_pade13) used integer-cleared polynomial coefficients where all terms were multiplied by $(2m)! / m!$. In _matrix_exp_pade9, the constant coefficient $b_0$ is $17,643,225,600 \approx 1.76 \times 10^{10}$, and in _matrix_exp_pade13, $b_0$ is $64,764,752,532,480,000 \approx 6.48 \times 10^{16}$. (In single-precision float32, $6.48 \times 10^{16}$ exceeds the 24-bit significand of IEEE 754, losing precision during constant conversion).

During Padé evaluation, these huge scalar multipliers were inside the matrix multiplication operand (tmp = ... + b[1] * ident, matrix_u = matmul(matrix, tmp)). Under nested forward-mode autodiff, the second-order JVP cross-terms scale quadratically as $O(b_k^2) \sim 10^{17} - 10^{20}$. Furthermore, solving $(-u + v) X = u + v$ causes catastrophic numerical cancellation between two matrices whose condition numbers were artificially inflated by 10 to 16 orders of magnitude.

Solution

This PR normalizes the Padé polynomial coefficients by $b_0$ ($c_k = b_k / b_0$) across all approximants (_matrix_exp_pade3, _matrix_exp_pade5, _matrix_exp_pade7, _matrix_exp_pade9, _matrix_exp_pade13), strictly matching Higham (2005) Equation (2.2).

With normalized coefficients:

  • All coefficients are bounded in $(0, 1]$.
  • In float64, the second derivative under nested forward-mode autodiff drops from 357356221.1760303 to 2.376 (eliminating the $10^8$ catastrophic scaling error), and reverse-mode autodiff matches analytical ground truth to 15 decimal places (2.1760704625890144).
  • In float32, the second derivative under nested forward-mode autodiff drops from 691.488 to 2.343.
  • Primal numerical consistency is preserved to machine epsilon across all matrix norms and dtypes (maximum difference against original implementation on random batches is $< 7 \times 10^{-16}$ in float64 and $< 4 \times 10^{-7}$ in float32).

Testing

  • Adds testSecondDerivativeNestedForwardAccumulator to tensorflow/python/kernel_tests/linalg/matrix_exponential_op_test.py, verifying:
    • 1st-order forward JVP against analytical reference $2 e^t \cos(1)$.
    • 2nd-order nested forward JVP (ForwardAccumulator over ForwardAccumulator) across float32 and float64.
    • 2nd-order reverse-mode Hessian (GradientTape over GradientTape) across float32 and float64.
  • All 76 tests in matrix_exponential_op_test.py pass cleanly.

Fixes #127224.

In tensorflow/python/ops/linalg/linalg_impl.py, the Pade approximant
implementations for matrix exponential (_matrix_exp_pade3,
_matrix_exp_pade5, _matrix_exp_pade7, _matrix_exp_pade9,
_matrix_exp_pade13) used unnormalized integer-cleared polynomial
coefficients. For higher-degree approximants, the constant term b_0
scaled up to 1.76e10 (order 9) and 6.48e16 (order 13).

Under nested forward-mode autodiff (ForwardAccumulator over
ForwardAccumulator), evaluating tangents through matrix multiplications
containing these unnormalized polynomial terms caused cross-terms to scale
quadratically (O(b_k^2) ~ 10^20) and inflated matrix conditioning by 10
orders of magnitude. On a 2x2 rotation generator matrix at t = 0.7 where
the exact analytical second derivative is 2*exp(0.7)*cos(1) ~ 2.176,
nested forward autodiff returned 357,356,221.

This commit normalizes all Pade polynomial coefficients by b_0 (c_k = b_k / b_0)
following Nicholas J. Higham (2005) Equation (2.2), bounding all coefficients
in [0, 1]. This eliminates condition-number inflation, preserves primal
accuracy to machine precision, and prevents catastrophic derivative
explosion in higher-order autodiff.

Fixes tensorflow#127224.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request updates the Pade approximants for matrix exponentials in linalg_impl.py by scaling the coefficients and adds a regression test for nested forward-mode JVP and reverse-mode Hessian. The review feedback suggests optimizing the Pade approximant functions by removing redundant multiplications of ident by c[0] (which is always 1.0) to avoid unnecessary kernel calls in eager mode. Additionally, it is recommended to apply tighter numerical tolerances for float64 in the new regression test to ensure higher precision.

Comment on lines +137 to 147
b = [120.0, 60.0, 12.0, 1.0]
c = [constant_op.constant(x / b[0], matrix.dtype) for x in b]
ident = linalg_ops.eye(
array_ops.shape(matrix)[-2],
batch_shape=array_ops.shape(matrix)[:-2],
dtype=matrix.dtype)
matrix_2 = math_ops.matmul(matrix, matrix)
tmp = matrix_2 + b[1] * ident
tmp = c[3] * matrix_2 + c[1] * ident
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = b[2] * matrix_2 + b[0] * ident
matrix_v = c[2] * matrix_2 + c[0] * ident
return matrix_u, matrix_v

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since c[0] is always exactly 1.0 (as c[0] = b[0] / b[0]), multiplying ident by c[0] is a redundant operation. In eager mode, this introduces an unnecessary element-wise multiplication kernel call. We can optimize this by directly adding ident instead of c[0] * ident.

Suggested change
b = [120.0, 60.0, 12.0, 1.0]
c = [constant_op.constant(x / b[0], matrix.dtype) for x in b]
ident = linalg_ops.eye(
array_ops.shape(matrix)[-2],
batch_shape=array_ops.shape(matrix)[:-2],
dtype=matrix.dtype)
matrix_2 = math_ops.matmul(matrix, matrix)
tmp = matrix_2 + b[1] * ident
tmp = c[3] * matrix_2 + c[1] * ident
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = b[2] * matrix_2 + b[0] * ident
matrix_v = c[2] * matrix_2 + c[0] * ident
return matrix_u, matrix_v
b = [120.0, 60.0, 12.0, 1.0]
c = [constant_op.constant(x / b[0], matrix.dtype) for x in b]
ident = linalg_ops.eye(
array_ops.shape(matrix)[-2],
batch_shape=array_ops.shape(matrix)[:-2],
dtype=matrix.dtype)
matrix_2 = math_ops.matmul(matrix, matrix)
tmp = c[3] * matrix_2 + c[1] * ident
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = c[2] * matrix_2 + ident
return matrix_u, matrix_v
References
  1. Identify unnecessary memory usage or redundant computations. (link)

Comment on lines +152 to 163
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
c = [constant_op.constant(x / b[0], matrix.dtype) for x in b]
ident = linalg_ops.eye(
array_ops.shape(matrix)[-2],
batch_shape=array_ops.shape(matrix)[:-2],
dtype=matrix.dtype)
matrix_2 = math_ops.matmul(matrix, matrix)
matrix_4 = math_ops.matmul(matrix_2, matrix_2)
tmp = matrix_4 + b[3] * matrix_2 + b[1] * ident
tmp = c[5] * matrix_4 + c[3] * matrix_2 + c[1] * ident
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident
matrix_v = c[4] * matrix_4 + c[2] * matrix_2 + c[0] * ident
return matrix_u, matrix_v

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since c[0] is always exactly 1.0, multiplying ident by c[0] is a redundant operation. We can optimize this by directly adding ident instead of c[0] * ident.

Suggested change
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
c = [constant_op.constant(x / b[0], matrix.dtype) for x in b]
ident = linalg_ops.eye(
array_ops.shape(matrix)[-2],
batch_shape=array_ops.shape(matrix)[:-2],
dtype=matrix.dtype)
matrix_2 = math_ops.matmul(matrix, matrix)
matrix_4 = math_ops.matmul(matrix_2, matrix_2)
tmp = matrix_4 + b[3] * matrix_2 + b[1] * ident
tmp = c[5] * matrix_4 + c[3] * matrix_2 + c[1] * ident
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident
matrix_v = c[4] * matrix_4 + c[2] * matrix_2 + c[0] * ident
return matrix_u, matrix_v
b = [30240.0, 15120.0, 3360.0, 420.0, 30.0, 1.0]
c = [constant_op.constant(x / b[0], matrix.dtype) for x in b]
ident = linalg_ops.eye(
array_ops.shape(matrix)[-2],
batch_shape=array_ops.shape(matrix)[:-2],
dtype=matrix.dtype)
matrix_2 = math_ops.matmul(matrix, matrix)
matrix_4 = math_ops.matmul(matrix_2, matrix_2)
tmp = c[5] * matrix_4 + c[3] * matrix_2 + c[1] * ident
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = c[4] * matrix_4 + c[2] * matrix_2 + ident
return matrix_u, matrix_v
References
  1. Identify unnecessary memory usage or redundant computations. (link)

Comment on lines +168 to 180
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0, 56.0, 1.0]
c = [constant_op.constant(x / b[0], matrix.dtype) for x in b]
ident = linalg_ops.eye(
array_ops.shape(matrix)[-2],
batch_shape=array_ops.shape(matrix)[:-2],
dtype=matrix.dtype)
matrix_2 = math_ops.matmul(matrix, matrix)
matrix_4 = math_ops.matmul(matrix_2, matrix_2)
matrix_6 = math_ops.matmul(matrix_4, matrix_2)
tmp = matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident
tmp = c[7] * matrix_6 + c[5] * matrix_4 + c[3] * matrix_2 + c[1] * ident
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident
matrix_v = c[6] * matrix_6 + c[4] * matrix_4 + c[2] * matrix_2 + c[0] * ident
return matrix_u, matrix_v

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since c[0] is always exactly 1.0, multiplying ident by c[0] is a redundant operation. We can optimize this by directly adding ident instead of c[0] * ident.

Suggested change
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0, 56.0, 1.0]
c = [constant_op.constant(x / b[0], matrix.dtype) for x in b]
ident = linalg_ops.eye(
array_ops.shape(matrix)[-2],
batch_shape=array_ops.shape(matrix)[:-2],
dtype=matrix.dtype)
matrix_2 = math_ops.matmul(matrix, matrix)
matrix_4 = math_ops.matmul(matrix_2, matrix_2)
matrix_6 = math_ops.matmul(matrix_4, matrix_2)
tmp = matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident
tmp = c[7] * matrix_6 + c[5] * matrix_4 + c[3] * matrix_2 + c[1] * ident
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 + b[0] * ident
matrix_v = c[6] * matrix_6 + c[4] * matrix_4 + c[2] * matrix_2 + c[0] * ident
return matrix_u, matrix_v
b = [17297280.0, 8648640.0, 1995840.0, 277200.0, 25200.0, 1512.0, 56.0, 1.0]
c = [constant_op.constant(x / b[0], matrix.dtype) for x in b]
ident = linalg_ops.eye(
array_ops.shape(matrix)[-2],
batch_shape=array_ops.shape(matrix)[:-2],
dtype=matrix.dtype)
matrix_2 = math_ops.matmul(matrix, matrix)
matrix_4 = math_ops.matmul(matrix_2, matrix_2)
matrix_6 = math_ops.matmul(matrix_4, matrix_2)
tmp = c[7] * matrix_6 + c[5] * matrix_4 + c[3] * matrix_2 + c[1] * ident
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = c[6] * matrix_6 + c[4] * matrix_4 + c[2] * matrix_2 + ident
return matrix_u, matrix_v
References
  1. Identify unnecessary memory usage or redundant computations. (link)

Comment on lines 198 to 205
tmp = (
matrix_8 + b[7] * matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 +
b[1] * ident)
c[9] * matrix_8 + c[7] * matrix_6 + c[5] * matrix_4 + c[3] * matrix_2 +
c[1] * ident)
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = (
b[8] * matrix_8 + b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 +
b[0] * ident)
c[8] * matrix_8 + c[6] * matrix_6 + c[4] * matrix_4 + c[2] * matrix_2 +
c[0] * ident)
return matrix_u, matrix_v

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since c[0] is always exactly 1.0, multiplying ident by c[0] is a redundant operation. We can optimize this by directly adding ident instead of c[0] * ident.

Suggested change
tmp = (
matrix_8 + b[7] * matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 +
b[1] * ident)
c[9] * matrix_8 + c[7] * matrix_6 + c[5] * matrix_4 + c[3] * matrix_2 +
c[1] * ident)
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = (
b[8] * matrix_8 + b[6] * matrix_6 + b[4] * matrix_4 + b[2] * matrix_2 +
b[0] * ident)
c[8] * matrix_8 + c[6] * matrix_6 + c[4] * matrix_4 + c[2] * matrix_2 +
c[0] * ident)
return matrix_u, matrix_v
tmp = (
c[9] * matrix_8 + c[7] * matrix_6 + c[5] * matrix_4 + c[3] * matrix_2 +
c[1] * ident)
matrix_u = math_ops.matmul(matrix, tmp)
matrix_v = (
c[8] * matrix_8 + c[6] * matrix_6 + c[4] * matrix_4 + c[2] * matrix_2 +
ident)
return matrix_u, matrix_v
References
  1. Identify unnecessary memory usage or redundant computations. (link)

Comment on lines 223 to 232
tmp_u = (
math_ops.matmul(matrix_6, matrix_6 + b[11] * matrix_4 + b[9] * matrix_2) +
b[7] * matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident)
math_ops.matmul(
matrix_6, c[13] * matrix_6 + c[11] * matrix_4 + c[9] * matrix_2) +
c[7] * matrix_6 + c[5] * matrix_4 + c[3] * matrix_2 + c[1] * ident)
matrix_u = math_ops.matmul(matrix, tmp_u)
tmp_v = b[12] * matrix_6 + b[10] * matrix_4 + b[8] * matrix_2
tmp_v = c[12] * matrix_6 + c[10] * matrix_4 + c[8] * matrix_2
matrix_v = (
math_ops.matmul(matrix_6, tmp_v) + b[6] * matrix_6 + b[4] * matrix_4 +
b[2] * matrix_2 + b[0] * ident)
math_ops.matmul(matrix_6, tmp_v) + c[6] * matrix_6 + c[4] * matrix_4 +
c[2] * matrix_2 + c[0] * ident)
return matrix_u, matrix_v

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since c[0] is always exactly 1.0, multiplying ident by c[0] is a redundant operation. We can optimize this by directly adding ident instead of c[0] * ident.

Suggested change
tmp_u = (
math_ops.matmul(matrix_6, matrix_6 + b[11] * matrix_4 + b[9] * matrix_2) +
b[7] * matrix_6 + b[5] * matrix_4 + b[3] * matrix_2 + b[1] * ident)
math_ops.matmul(
matrix_6, c[13] * matrix_6 + c[11] * matrix_4 + c[9] * matrix_2) +
c[7] * matrix_6 + c[5] * matrix_4 + c[3] * matrix_2 + c[1] * ident)
matrix_u = math_ops.matmul(matrix, tmp_u)
tmp_v = b[12] * matrix_6 + b[10] * matrix_4 + b[8] * matrix_2
tmp_v = c[12] * matrix_6 + c[10] * matrix_4 + c[8] * matrix_2
matrix_v = (
math_ops.matmul(matrix_6, tmp_v) + b[6] * matrix_6 + b[4] * matrix_4 +
b[2] * matrix_2 + b[0] * ident)
math_ops.matmul(matrix_6, tmp_v) + c[6] * matrix_6 + c[4] * matrix_4 +
c[2] * matrix_2 + c[0] * ident)
return matrix_u, matrix_v
tmp_u = (
math_ops.matmul(
matrix_6, c[13] * matrix_6 + c[11] * matrix_4 + c[9] * matrix_2) +
c[7] * matrix_6 + c[5] * matrix_4 + c[3] * matrix_2 + c[1] * ident)
matrix_u = math_ops.matmul(matrix, tmp_u)
tmp_v = c[12] * matrix_6 + c[10] * matrix_4 + c[8] * matrix_2
matrix_v = (
math_ops.matmul(matrix_6, tmp_v) + c[6] * matrix_6 + c[4] * matrix_4 +
c[2] * matrix_2 + ident)
return matrix_u, matrix_v
References
  1. Identify unnecessary memory usage or redundant computations. (link)

Comment on lines +195 to +198
# 2nd order nested forward-mode JVP
actual_2nd = forward_ad(forward_ad(target))(x)
self.assertAllClose(
expected, self.evaluate(actual_2nd), rtol=1e-1, atol=0.25)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The test uses a very loose tolerance (rtol=1e-1, atol=0.25) for the second-order nested forward-mode JVP test. While this is necessary for float32 due to numerical precision limits, float64 should be able to achieve much higher precision. We should use tighter tolerances for float64 to prevent precision regressions.

Suggested change
# 2nd order nested forward-mode JVP
actual_2nd = forward_ad(forward_ad(target))(x)
self.assertAllClose(
expected, self.evaluate(actual_2nd), rtol=1e-1, atol=0.25)
# 2nd order nested forward-mode JVP
actual_2nd = forward_ad(forward_ad(target))(x)
if dtype == ops.dtypes.float64:
self.assertAllClose(
expected, self.evaluate(actual_2nd), rtol=1e-5, atol=1e-5)
else:
self.assertAllClose(
expected, self.evaluate(actual_2nd), rtol=1e-1, atol=0.25)
References
  1. Ensure tests cover edge cases and expected behavior. (link)

@keerthanakadiri
keerthanakadiri requested a review from a team September 18, 2026 10:52
@keerthanakadiri keerthanakadiri self-assigned this Sep 18, 2026
@nithyak0204 nithyak0204 added awaiting review Pull request awaiting review comp:ops OPs related issues prtype:bugfix PR to fix a bug labels Sep 18, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Sep 18, 2026
@nithyak0204 nithyak0204 added python Pull requests that update Python code and removed comp:ops OPs related issues labels Sep 18, 2026

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for your contribution to fix the nested forward-mode autodiff second derivative error!

The CI checks have passed successfully, and the logic and testing are sound. However, I have a few requests based on previous reviewer feedback that were missed before we can merge this in:

  1. Redundant Multiplications: In tensorflow/python/ops/linalg/linalg_impl.py, we need to optimize the Pade approximant functions by directly adding ident without the redundant c[0] * multiplication, because c[0] evaluates to 1.0. By removing this multiplication, we save an unnecessary kernel call in eager mode.
  2. Tighten test tolerances: In tensorflow/python/kernel_tests/linalg/matrix_exponential_op_test.py, the new regression test testSecondDerivativeNestedForwardAccumulator uses extremely loose tolerances for float64 (rtol=1e-1, atol=0.25). We need to apply tighter tolerances specifically for float64 to verify the higher precision from your fix.

Specifically, you can apply these patches:

tensorflow/python/ops/linalg/linalg_impl.py:
Replace + c[0] * ident with + ident wherever applicable in _matrix_exp_pade3, _matrix_exp_pade5, _matrix_exp_pade7, _matrix_exp_pade9, and _matrix_exp_pade13. For example:

-  matrix_v = c[2] * matrix_2 + c[0] * ident
+  matrix_v = c[2] * matrix_2 + ident

tensorflow/python/kernel_tests/linalg/matrix_exponential_op_test.py:
Please tighten the precision checks for float64:

      if dtype == ops.dtypes.float64:
        atol_1st = 1e-12
        rtol_1st = 1e-12
        atol_2nd = 1e-12
        rtol_2nd = 1e-12
        atol_hess = 1e-12
        rtol_hess = 1e-12
      else:
        atol_1st = 1e-3
        rtol_1st = 1e-3
        atol_2nd = 0.25
        rtol_2nd = 1e-1
        atol_hess = 1e-4
        rtol_hess = 1e-4

      # 1st order forward-mode JVP
      actual_1st = forward_ad(target)(x)
      self.assertAllClose(
          expected, self.evaluate(actual_1st), rtol=rtol_1st, atol=atol_1st)

      # 2nd order nested forward-mode JVP
      actual_2nd = forward_ad(forward_ad(target))(x)
      self.assertAllClose(
          expected, self.evaluate(actual_2nd), rtol=rtol_2nd, atol=atol_2nd)

      # 2nd order reverse-mode Hessian
      with backprop.GradientTape() as t2:
        t2.watch(x)
        with backprop.GradientTape() as t1:
          t1.watch(x)
          y = target(x)
        g1 = t1.gradient(y, x)
      g2 = t2.gradient(g1, x)
      self.assertAllClose(expected, self.evaluate(g2), rtol=rtol_hess, atol=atol_hess)

Please apply these changes, ensure tests pass, and we'll gladly integrate it!

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Sep 18, 2026
In tensorflow/python/ops/linalg/linalg_impl.py, drop the now-redundant
c[0] * ident multiplication in _matrix_exp_pade3, _matrix_exp_pade5,
_matrix_exp_pade7, _matrix_exp_pade9, and _matrix_exp_pade13. Since the
previous commit normalizes coefficients by b_0, c[0] is always 1.0, so
the multiplication was a no-op kernel call.

In matrix_exponential_op_test.py, tighten the float64 tolerances in
testSecondDerivativeNestedForwardAccumulator to rtol=atol=1e-12 for all
three assertions, verifying the higher precision the normalization fix
provides in float64.
Tightening testSecondDerivativeNestedForwardAccumulator's nested
ForwardAccumulator (forward-over-forward) assertion to 1e-12 for
float64 does not hold: isolating the matmul chain used by the Pade
approximants (matrix_2, matrix_4, matrix_6, matrix_8) shows nested
forward-mode autodiff diverges from the reverse-mode/analytical value
by about 9% once three matmuls are chained, and the divergence is the
same magnitude in float32 and float64. That rules out floating-point
precision as the cause; it's a limitation in how TensorFlow composes
forward-over-forward differentiation through chained MatMul ops,
unrelated to the Pade coefficient conditioning this PR fixes.

The 1st-order forward JVP and 2nd-order reverse-mode Hessian
assertions keep the tightened 1e-12 tolerance for float64, since both
verified to machine precision.
@bodapatisaikrishna

bodapatisaikrishna commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review! Applied both requested changes, but I want to flag one thing before this goes green in CI.

I dropped the redundant c[0] * multiplication across all five Pade approximants, and tightened the float64 tolerances for the 1st-order forward JVP and 2nd-order reverse-mode Hessian assertions to atol=rtol=1e-12 both verified to machine precision (errors of 4.4e-16 and 1.8e-15 respectively).

I couldn't tighten the 2nd-order nested-forward (ForwardAccumulator over ForwardAccumulator) assertion to 1e-12 though. Isolating it, the divergence from the analytical value is about 9% and identical in magnitude for float32 and float64 which rules out floating-point precision as the cause. Tracing it further, it shows up specifically once matmuls are chained three levels deep (matrix_6 = matrix_4 * matrix_2, as used in the Pade-9/13 approximants); two chained levels are fine. That looks like a limitation in how TensorFlow composes forward-over-forward autodiff through chained MatMul, unrelated to the coefficient conditioning this PR addresses. I kept that one assertion at its original loose tolerance and left a comment explaining why.

Happy to file that as a separate core TF issue if useful didn't want to conflate it with this fix's scope.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi! Thanks for the updates! The math adjustments and precision thresholds you implemented look correct.

However, the new testSecondDerivativeNestedForwardAccumulator test you added to tensorflow/python/kernel_tests/linalg/matrix_exponential_op_test.py is failing in our internal automated test suites.

The test throws the following exception:

NotImplementedError: tf.GradientTape.gradients() does not support graph control flow operations like tf.cond or tf.while at this time. Use tf.gradients() instead.

This happens because our internal test environment often runs tests in Graph Mode by default, and tf.cond in Graph Mode uses Switch which GradientTape/ForwardAccumulator doesn't fully support.

To fix this natively on your branch, please add the @test_util.run_v2_only decorator to the test to ensure it runs exclusively with TF2 control flow behavior:

  @test_util.run_v2_only
  def testSecondDerivativeNestedForwardAccumulator(self):
      # Regression test for Issue #127224.
      ...

Once you add this decorator, the test correctly passes. Regarding your comment on the three-level chained MatMul nested autodiff discrepancy, filing a separate core TF issue is the right approach. Thanks again!

testSecondDerivativeNestedForwardAccumulator fails under graph mode's
default control flow, where matrix_exponential's internal tf.cond
(for the is_finite check) lowers to Switch/Merge ops that
GradientTape/ForwardAccumulator can't differentiate through, raising
NotImplementedError. Add test_util.run_v2_only so the test only runs
under TF2 control flow, where forward- and reverse-mode
differentiation through the op are supported.
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Thanks for catching that! Added @test_util.run_v2_only to testSecondDerivativeNestedForwardAccumulator so it only runs under TF2 control flow, avoiding the graph-mode tf.cond Switch/Merge issue. Pushed in 687dba2.

Will file a separate core TF issue for the chained-matmul nested-forward-AD discrepancy and link it here for reference.

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing the issues and pushing the fix with @test_util.run_v2_only! We've verified this locally and all internal automated test suites passed cleanly.

LGTM.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Sep 18, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Sep 18, 2026
@nithyak0204 nithyak0204 removed awaiting review Pull request awaiting review kokoro:force-run Tests on submitted change labels Sep 21, 2026
@copybara-service
copybara-service Bot merged commit 1374419 into tensorflow:master Sep 21, 2026
17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Sep 21, 2026
bodapatisaikrishna added a commit to bodapatisaikrishna/bodapatisaikrishna that referenced this pull request Sep 21, 2026
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Following up on the separate issue I mentioned: filed as #127753.

One correction to what I said earlier in this thread. Minimizing it further, it isn't really about three chained matmuls. The wrong result shows up whenever an intermediate is used as an operand both directly and through another op (for example m = tf.identity(x); (m * m) * m gives 2.4 instead of 4.2 under eager forward-over-forward), and it isn't specific to MatMul. So the comment in the test about "two chained matmul levels" is a bit off, but the tolerance it explains is still needed. Details and a standalone repro are in the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

prtype:bugfix PR to fix a bug python Pull requests that update Python code ready to pull PR ready for merge process

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

tf.linalg.expm returns incorrect second derivative under nested forward-mode autodiff

4 participants