torch: float64 `Dense` returns float32 since #23225, and float64 handling on torch is inconsistent
Summary
On the torch backend, a float64 Dense layer now returns float32. #23225 routes the torch binary ops through dtypes.result_type, and result_type maps float64 to float32 on all backends except TensorFlow. The activations and the RNN layers keep float64. A float64 model on torch thus mixes the two dtypes, with no warning.
Reproduction
torch backend, master at 0b29b7f41. keras.config.set_floatx("float64") gives the same results.
import numpy as np
import keras
from keras import layers, ops
x = np.ones((2, 4), "float64")
layers.Dense(3, dtype="float64")(x).dtype # float32 (kernel float64, compute_dtype float64)
a = ops.convert_to_tensor(np.array([3.0, 4.0], "float64"), "float64")
ops.add(a, a).dtype # float32
ops.multiply(a, a).dtype # float32
ops.sigmoid(a).dtype # float64
ops.tanh(a).dtype # float64
layers.LSTM(4, dtype="float64")(np.random.randn(2, 3, 2)).dtype # float64Before #23225 (commit 19d533a9d), Dense(3, dtype="float64") returned float64 and ops.add returned float64. ops.matmul already returned float32 for two float64 inputs, and Dense(3, use_bias=False, dtype="float64") already returned float32. The native bias add promoted the float32 matmul result back to float64, so the float64 output hid a float32 matmul.
TensorFlow returns float64 for all of these, before and after #23225.
Cause
keras/src/backend/common/dtypes.py maps float64 to float32 in BIT64_TO_BIT32_DTYPE for all backends except TensorFlow, "to be aligned with JAX's default behavior". JAX disables 64-bit by default. torch supports float64 natively. #23225 applies result_type to add, subtract, multiply, divide, power, mod, fmod and other binary ops in the torch backend, which makes the downcast consistent for those ops. The unary ops (sigmoid, tanh, exp) and the RNN kernels call torch directly and keep float64.
Effect
set_floatx("float64")on torch gives float32 outputs fromDense, with no warning.- Layers that combine the two paths see mixed dtypes. The first revision of #23545 showed this: a float64
LSTMwithhard_sigmoidstopped withRuntimeError: expected m1 and m2 to have the same dtype, but got: float != double.
Two consistent rules
- torch and NumPy keep float64, like TensorFlow: add torch and NumPy to the TensorFlow exception in
BIT64_TO_BIT32_DTYPE. OpenVINO keeps the float32 mapping. The binary ops,matmulandDensethen return float64 for float64 inputs. The dtype tests compare the float64 cases with JAX with 64-bit types enabled (see "Tests for rule 1"). Rule 1 also needs a small torch change for NumPy float64 scalars (see "Effects of rule 1"). - torch follows the JAX default: all ops return float32 for float64 inputs, and
set_floatx("float64")raises or warns on torch.
Rule 1 matches the native float64 support of torch and the current behavior of the unary ops and the RNN layers. Rule 1 is a breaking change: on torch and NumPy, float64 inputs give float64 results, not float32 results.
# keras/src/backend/common/dtypes.py
- "float64": "float64" if config.backend() == "tensorflow" else "float32",
+ # TensorFlow, torch and NumPy compute float64 natively. JAX disables
+ # 64-bit types by default, and the OpenVINO CPU plugin computes float64
+ # in float32.
+ "float64": (
+ "float64"
+ if config.backend() in ("tensorflow", "torch", "numpy")
+ else "float32"
+ ),NumPy
NumPy has the same inconsistency as torch. On NumPy at d5edb34b5, with float64 inputs:
Dense,Dense(use_bias=False),EinsumDenseandConv2Dreturn float32. Their symbolic outputs are float64.ops.add,ops.matmul,ops.sigmoid,ops.tanhandops.expreturn float32. The symbolic dtype ofops.sigmoidandops.expis float64.SimpleRNN,LayerNormalizationandBatchNormalizationreturn float64 with float32 precision.model.predictreturns float32, andmodel.outputs[0].dtypeis float64.
With NumPy in the exception, all these results are float64, and the eager and symbolic dtypes are the same. Only Conv2D keeps float32 precision: the NumPy backend computes the convolution with jax.lax.conv_general_dilated, and JAX disables 64-bit types by default. #23750 tracks this case (C4).
OpenVINO
Do not add OpenVINO to the exception. The OpenVINO CPU plugin computes float64 graphs in float32. Its OPTIMIZATION_CAPABILITIES are FP32, FP16, INT8, BIN and EXPORT_IMPORT, without FP64. On master, ops.abs of a float64 -inf gives 3.4028234663852886e+38. With OpenVINO in the exception:
- All float64 results of the probe below have float32 precision.
ops.addof the float64 values[-inf, 1e300]and[0, 0]gives[-3.4028234663852886e+38, 3.4028234663852886e+38].numpy_test.py::NumpyTwoInputOpsCorrectnessTest::test_divide_no_nanand the twomath_test.py::MathOpsCorrectnessTest::test_lgamma_operation_edge_casestests fail with+inf location mismatch. They pass without OpenVINO in the exception.
Results of rule 1
The probe calls 17 ops and 9 layers with float64 inputs and dtype="float64". The ops are add, subtract, multiply, divide, power, maximum, hypot, matmul, einsum, where, sigmoid, tanh, exp, sqrt, log, sum and mean. The layers are Dense, Dense(use_bias=False), Dense with hard_sigmoid, EinsumDense, Conv2D, SimpleRNN, LSTM, LayerNormalization and BatchNormalization. The probe compares the eager dtype with the symbolic dtype, and the values with a NumPy float64 reference (no reference for LSTM). master is at d5edb34b5.
| Backend | Code | Eager dtype is not the symbolic dtype | float32 results | float64 results with float32 precision¹ | predict / model.outputs |
|---|---|---|---|---|---|
| torch (CPU) | master |
11² | 13 | 4³ | float32 / float64 |
| torch (CPU) | Rule 1 | 0 | 0 | 0 | float64 / float64 |
| NumPy | master |
9 | 21 | 3 | float32 / float64 |
| NumPy | torch in the exception, NumPy not | 9 | 21 | 3 | float32 / float64 |
| NumPy | Rule 1 | 0 | 0 | 1 (Conv2D) |
float64 / float64 |
| TensorFlow | master and rule 1 |
0 | 0 | 0 | float64 / float64 |
| JAX (64-bit off) | master and rule 1 |
12 | 26 | 0 | float32 / float64 |
| OpenVINO | master and rule 1 |
9 | 15 | 10 | Not run⁴ |
| OpenVINO | OpenVINO in the exception | 0 | 0 | 25 | Not run⁴ |
- Relative error from 9e-9 to 2.3e-7. The float64 results with float64 precision have a relative error below 1e-15.
einsum,where,tanh,sqrt,logandsumgive float64 (eager) and float32 (symbolic).Dense,Dense(use_bias=False),Densewithhard_sigmoid,EinsumDenseandConv2Dgive float32 (eager) and float64 (symbolic).ops.mean,SimpleRNN,LayerNormalizationandBatchNormalization.- The OpenVINO backend does not support
fit.
On torch, NumPy and TensorFlow, set_floatx("float64") gives the same counts, except NumPy without NumPy in the exception: 8, 22 and 3. With rule 1, nn_test.py, math_test.py, linalg_test.py and the BatchNormalization, LayerNormalization and SimpleRNN tests have no new failures on torch and NumPy.
Tests for rule 1
Rule 1 changes these tests:
keras/src/ops/numpy_test.py: add float64 toBINARY_DTYPESon TensorFlow, torch and NumPy. #23225 added it on torch only. InNumpyDtypeTest.setUp, enablejax_enable_x64only when the test name containsfloat64, and restore it withaddCleanup. The JAX reference then gives float64 for the float64 cases. Importjaxat module level, asmath_test.pyandimage_test.pydo.keras/src/backend/common/dtypes_test.py: runtest_result_type_with_float64on TensorFlow, torch and NumPy, and skip it on JAX and OpenVINO. Add a test forresult_type("int32", float)andresult_type(float, float)withset_floatx("float64").keras/src/layers/core/dense_test.py: add a float64Densetest for the eager dtype, the symbolic dtype and the values.
Results of numpy_test.py -k Dtype:
| Code | Tests | torch (CPU) | NumPy | TensorFlow |
|---|---|---|---|---|
master |
master |
4002 pass | 5320 pass | 4547 pass |
master |
Changed | 248 fail, 3754 pass | 302 fail, 5320 pass | 4822 pass |
| Rule 1 | master |
248 fail, 3754 pass | 5320 pass | 4547 pass |
| Rule 1 | Changed | 4002 pass | 5622 pass | 4822 pass |
| Rule 1 | Changed, jax_enable_x64 for the full class |
651 fail | Not run | 730 fail |
All failures in the second and third rows are float64 cases. A class-wide jax_enable_x64, as in the #23225 review, gives no float64 failures. It changes the JAX reference for the dtype=None cases, the Python scalar cases and the int64 results (for example arange, argmax and sum of integers). The dtypes_test.py and dense_test.py changes pass on TensorFlow, torch and NumPy, and skip on JAX and OpenVINO.
Effects of rule 1
NumPy float64 scalars on torch. torch convert_to_tensor (keras/src/backend/torch/ops/core.py:351) converts a np.float64 scalar like a Python float, because np.float64 is a subclass of float. The result dtype is floatx. compute_output_spec and convert_to_tensors_of_same_dtype use the float64 dtype of the scalar. Also, torch where (keras/src/backend/torch/ops/numpy.py:2174) uses torch type promotion, in which a 0-d tensor does not change the result dtype.
With rule 1, 12 torch ops give float32 (eager) and float64 (symbolic) for a float32 tensor and a np.float64 scalar: copysign, heaviside, float_power, nextafter, where, outer, inner, dot, tensordot, kron, append and einsum. where with a float64 0-d tensor has the same mismatch. ops.add, ops.multiply and ops.maximum with the same scalar give float64. On master, all these cases give float32 (eager and symbolic). This torch change fixes the mismatches:
# keras/src/backend/torch/ops/core.py, convert_to_tensor
+ if isinstance(x, np.generic):
+ # NumPy scalars carry a dtype. `np.float64` is also a Python `float`,
+ # so convert it as an array to keep its dtype.
+ x = np.asarray(x)
if isinstance(x, (bool, int, float, complex)): # keras/src/backend/torch/ops/numpy.py, where
if x1 is not None and x2 is not None:
- x1 = convert_to_tensor(x1)
- x2 = convert_to_tensor(x2)
+ x1, x2, _ = convert_to_tensors_of_same_dtype(x1, x2)
return torch.where(condition, x1, x2)A second probe calls 30 binary ops with a float32 tensor and a float64 operand. The float64 operand is a np.float64 scalar, a float64 0-d tensor, a float64 tensor or a float64 NumPy array (116 cases). The table gives the number of cases in which the eager dtype is not the symbolic dtype:
| Backend | master |
Rule 1 | Rule 1 and the torch change |
|---|---|---|---|
| torch (CPU) | 11⁵ | 13 | 0 |
| NumPy | 0 | 0 | 0 |
| TensorFlow | 0 | 0 | Not changed |
outer,kronandappendwith a float64 0-d tensor, tensor or NumPy array give float64 (eager) and float32 (symbolic).wherewith a float64 tensor or NumPy array gives the same dtypes. Rule 1 fixes these cases.
With the torch change, numpy_test.py -k Dtype and core_test.py pass on torch. The tests for the change call add, maximum, copysign, outer and append with a float32 tensor and a np.float64 scalar. They also call where with a np.float64 scalar and with a float64 0-d tensor. Without the torch change, the copysign, outer, append and where tests fail on torch.
Result dtype of mixed operands. On torch and NumPy, a float32 tensor with a NumPy float64 scalar (np.sqrt(2.0), np.float64(0.5)) or a float64 NumPy array gives float64. On master, it gives float32. TensorFlow on master, and JAX with jax_enable_x64, give float64. A Python float keeps float32.
torch MPS. MPS does not support float64. These calls return float32 on master. With rule 1, they raise TypeError: Cannot convert a MPS Tensor to float64 dtype as the MPS framework doesn't support float64. Please use float32 instead.
x = ops.convert_to_tensor(np.array([0.5, 1.0, 2.0], "float32")) # On MPS.
ops.multiply(x, np.sqrt(2.0))
ops.add(x, np.float64(0.5))
ops.add(x, np.ones(3))
ops.subtract(np.ones(3), x)
ops.add(np.ones(3), np.ones(3))#23701 does not prevent these errors, because convert_to_tensors_of_same_dtype passes dtype="float64" explicitly. fit, evaluate and predict with float64 NumPy data, and Normalization.adapt, still work on MPS.
Related
- #23223 (the report that #23225 fixed), #23225
- #23545 (float64 activations on torch, review comments)
- #23701 (torch MPS float64 inputs, open)
- #23750 (part C) applies rule 1 also to int64, uint64 and complex128, and to JAX with
jax_enable_x64.
Source: keras-team/keras