Repository navigation
Keep float64 and complex NumPy inputs in matrix_rank and lu_* - #129741
copybara-service[bot] merged 2 commits into
Conversation
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
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| 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
- Flag fragile or environment-dependent logic. (link)
dmiltr3
left a comment
There was a problem hiding this comment.
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:
-
Clarify the
_convert_with_float32_hintdocstring intensorflow/python/ops/linalg/linalg_impl.py:813-821: The summary line says"never narrows", butint32andint64NumPy arrays still convert tofloat32. Please state specifically thatfloat64andcomplexdtypes 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. """
-
Add
np.complex64coverage intensorflow/python/kernel_tests/linalg/linalg_ops_test.py:426-431and671-685: Both new tests construct onlynp.complex128arrays, leavingnp.complex64in_convert_with_float32_hintuntested. Please testnp.complex64intest_complex_numpy_input_raisesandtest_float64_and_complex_numpy_inputs_keep_dtype, using a1e-3tolerance fornp.complex64inLUNumpyInputTest: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)
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.
|
Updated in b6e5806: reworded the |
Fixes #129739.
matrix_rank,lu_solve,lu_matrix_inverseandlu_reconstructconvert their matrix withdtype_hint=dtypes.float32. The hint is there so lists and integer inputs become float32, butconvert_to_tensoralso applies it to NumPy arrays whenever the cast is possible:I added a small
_convert_with_float32_hinthelper 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. Formatrix_ranka complex NumPy input now raises the sameTypeErroras 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.pyrather than changingconvert_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 raisesTypeError.LUNumpyInputTest:lu_reconstruct,lu_matrix_inverseandlu_solvekeep 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.pydropped into that install. The wholelinalg_ops_test.pypasses with the patch (883 tests). pylint withtensorflow/tools/ci_build/pylintrcreports nothing on the changed lines. CPU only (arm64 macOS).