Skip to content

Keep float64 and complex NumPy inputs in matrix_rank and lu_* - #129741

Merged
copybara-service[bot] merged 2 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/129739-linalg-numpy-dtype-hint
Nov 2, 2026
Merged

copybara-service[bot] merged 2 commits into
tensorflow:masterfrom
bodapatisaikrishna:fix/129739-linalg-numpy-dtype-hint

Conversation

@bodapatisaikrishna

Copy link
Copy Markdown
Contributor

Fixes #129739.

matrix_rank, lu_solve, lu_matrix_inverse and lu_reconstruct convert their matrix with dtype_hint=dtypes.float32. The hint is there so lists and integer inputs become float32, but convert_to_tensor also applies it to NumPy arrays whenever the cast is possible:

x = np.diag([1.0, 1e-9])
tf.linalg.matrix_rank(x)                    # 1  (float32 SVD and tolerance)
tf.linalg.matrix_rank(tf.constant(x))       # 2

z = np.array([[1, 1j], [1j, -1]])           # rank 1
tf.linalg.matrix_rank(z)                    # 2, rank of the real part

lu, perm = tf.linalg.lu(complex_matrix)
tf.linalg.lu_reconstruct(lu.numpy(), perm.numpy())   # float32, real parts only

I added a small _convert_with_float32_hint helper that skips the hint when the value already has a float64 or complex dtype, and used it in the four places. Everything else is converted exactly as before. I compared outputs before and after for Python float and int lists, float16/float32/float64/int64/complex128 NumPy arrays, and float32/float64 tensors: only the float64 and complex NumPy rows change. For matrix_rank a complex NumPy input now raises the same TypeError as a complex tensor already does, instead of silently using the real part.

I kept this to the four functions that use the float32 hint in linalg_impl.py rather than changing convert_to_tensor, since its hint behavior is documented and changing it would reach far beyond these functions.

Testing

  • MatrixRankNumpyInputTest: float64 NumPy input keeps the 1e-9 singular value, complex NumPy input raises TypeError.
  • LUNumpyInputTest: lu_reconstruct, lu_matrix_inverse and lu_solve keep float64 and complex128 for NumPy inputs and match NumPy to 1e-10.

Both run in graph and eager mode. They fail on tf-nightly 2.23.0-dev20261028 and pass with the patched linalg_impl.py dropped into that install. The whole linalg_ops_test.py passes with the patch (883 tests). pylint with tensorflow/tools/ci_build/pylintrc reports nothing on the changed lines. CPU only (arm64 macOS).

matrix_rank, lu_solve, lu_matrix_inverse and lu_reconstruct convert
their matrix with dtype_hint=float32 so that Python lists and integer
inputs end up as float32. The hint also applies to NumPy arrays, though:
a float64 array is converted to float32 and a complex array loses its
imaginary part (NumPy only warns). matrix_rank(np.diag([1., 1e-9]))
returns 1 while the same float64 tensor gives 2, a complex NumPy matrix
gets the rank of its real part, and lu_reconstruct on the NumPy output
of lu for a complex matrix returns a float32 matrix built from real
parts.

Convert float64 and complex NumPy values without the hint so they keep
their dtype, like tensors already do. A complex input to matrix_rank now
raises the same TypeError as a complex tensor. Lists, integer arrays and
other dtypes are converted exactly as before.

Fixes tensorflow#129739
@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Oct 30, 2026
@google-ml-butler
google-ml-butler Bot requested a review from cantonios October 30, 2026 06:21
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Oct 30, 2026

@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 introduces a helper function _convert_with_float32_hint to prevent float64 and complex NumPy inputs from being silently narrowed to float32 during tensor conversion in several linear algebra operations, including matrix_rank and LU decomposition functions. It also adds corresponding unit tests to verify precision and dtype preservation. The review feedback correctly points out that hardcoding a specific list of NumPy dtypes is fragile and suggests a more robust approach using np.issubdtype with np.floating and np.complexfloating to handle all floating-point and complex types across different environments.

Comment on lines +819 to +821
if getattr(value, 'dtype', None) in (np.float64, np.complex64, np.complex128):
return ops.convert_to_tensor(value, name=name)
return ops.convert_to_tensor(value, dtype_hint=dtypes.float32, name=name)

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

Hardcoding a specific list of NumPy dtypes like (np.float64, np.complex64, np.complex128) is fragile and environment-dependent. For example, it misses other floating/complex types such as np.float16, or platform-specific types like np.longdouble (float128) and np.clongdouble (complex256).

Using np.issubdtype with np.floating and np.complexfloating is a much more robust and idiomatic way to detect any floating-point or complex NumPy array, ensuring that we never narrow any of these high-precision or complex inputs.

Suggested change
if getattr(value, 'dtype', None) in (np.float64, np.complex64, np.complex128):
return ops.convert_to_tensor(value, name=name)
return ops.convert_to_tensor(value, dtype_hint=dtypes.float32, name=name)
dtype = getattr(value, 'dtype', None)
if isinstance(dtype, np.dtype) and (
np.issubdtype(dtype, np.floating) or
np.issubdtype(dtype, np.complexfloating)
):
return ops.convert_to_tensor(value, name=name)
return ops.convert_to_tensor(value, dtype_hint=dtypes.float32, name=name)
References
  1. Flag fragile or environment-dependent logic. (link)

@keerthanakadiri keerthanakadiri self-assigned this Oct 30, 2026
@keerthanakadiri
keerthanakadiri requested a review from a team October 30, 2026 07:43
@keerthanakadiri keerthanakadiri added comp:ops OPs related issues prtype:bugfix PR to fix a bug labels Oct 30, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Oct 30, 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.

Thanks for fixing the dtype_hint conversion in matrix_rank, lu_solve, lu_matrix_inverse, and lu_reconstruct so float64 and complex NumPy arrays keep their dtype.

Please make two small updates before we merge:

  1. Clarify the _convert_with_float32_hint docstring in tensorflow/python/ops/linalg/linalg_impl.py:813-821: The summary line says "never narrows", but int32 and int64 NumPy arrays still convert to float32. Please state specifically that float64 and complex dtypes are kept:

    def _convert_with_float32_hint(value, name):
      """Converts to tensor with a float32 hint, keeping float64 and complex.
    
      The hint alone also casts float64 and complex NumPy inputs to float32,
      silently dropping precision and imaginary parts.
      """
  2. Add np.complex64 coverage in tensorflow/python/kernel_tests/linalg/linalg_ops_test.py:426-431 and 671-685: Both new tests construct only np.complex128 arrays, leaving np.complex64 in _convert_with_float32_hint untested. Please test np.complex64 in test_complex_numpy_input_raises and test_float64_and_complex_numpy_inputs_keep_dtype, using a 1e-3 tolerance for np.complex64 in LUNumpyInputTest:

      def test_complex_numpy_input_raises(self):
        # Same as for a complex Tensor, instead of using only the real part.
        for dtype in (np.complex64, np.complex128):
          x_ = np.array([[1., 1j], [1j, -1.]], dtype=dtype)
          with self.assertRaisesRegex(TypeError, "float"):
            linalg.matrix_rank(x_)
      def test_float64_and_complex_numpy_inputs_keep_dtype(self):
        # These used to be converted to float32, dropping the imaginary part.
        rng = np.random.RandomState(0)
        z_ = rng.randn(3, 3) + 1j * rng.randn(3, 3)
        for x_, tol in [
            (rng.randn(3, 3), 1e-10),
            (z_.astype(np.complex64), 1e-3),
            (z_, 1e-10),
        ]:
          lower_upper_, perm_ = self.evaluate(linalg.lu(x_))
          rhs_ = np.ones((3, 1), dtype=x_.dtype)
          for y, expected in [
              (linalg.lu_reconstruct(lower_upper_, perm_), x_),
              (linalg.lu_matrix_inverse(lower_upper_, perm_), np.linalg.inv(x_)),
              (linalg.lu_solve(lower_upper_, perm_, rhs_),
               np.linalg.solve(x_, rhs_)),
          ]:
            self.assertEqual(y.dtype, x_.dtype)
            self.assertAllClose(expected, self.evaluate(y), rtol=tol, atol=tol)

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Oct 30, 2026
Reword the `_convert_with_float32_hint` summary: it keeps float64 and
complex inputs, but integer NumPy arrays still convert to float32, so
"never narrows" overstated it.

Run `test_complex_numpy_input_raises` and
`test_float64_and_complex_numpy_inputs_keep_dtype` for `np.complex64` as
well as `np.complex128`, with a 1e-3 tolerance for complex64.
@bodapatisaikrishna

Copy link
Copy Markdown
Contributor Author

Updated in b6e5806: reworded the _convert_with_float32_hint docstring as suggested, and the complex tests now cover np.complex64 as well as np.complex128 (1e-3 tolerance for complex64 in LUNumpyInputTest). I left the np.issubdtype suggestion from the bot out to keep this change to the dtypes the PR is about.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Oct 30, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Oct 30, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Oct 30, 2026
@copybara-service
copybara-service Bot merged commit e57bb23 into tensorflow:master Nov 2, 2026
19 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:ops OPs related issues kokoro:force-run Tests on submitted change prtype:bugfix PR to fix a bug ready to pull PR ready for merge process size:M CL Change Size: Medium

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

tf.linalg.matrix_rank and lu_* cast float64/complex NumPy inputs to float32 (wrong rank, imaginary part dropped)

4 participants