Integer and bool inputs give wrong values in several activations, with no error
Summary
Several activation functions build their float constants in the dtype of the input. For an integer or bool input, a constant like 0.5 becomes 0, and the function returns wrong values with no error. #23545 and #23530 fix this for hard_sigmoid, hard_silu and gelu, one op and one backend at a time. The same cause stays in the other activations. This issue proposes one shared rule.
Reproduction
Master at 0b29b7f41, x = np.arange(-3, 5, dtype="int32"), JAX as the reference:
| Op | numpy | JAX |
|---|---|---|
ops.leaky_relu(x) |
int32 [0, 0, 0, 0, 1, 2, 3, 4] |
[-0.6, -0.4, -0.2, 0, 1, 2, 3, 4] |
ops.selu(x) |
float64 [-0.95, -0.865, -0.632, 0, 1, 2, 3, 4] |
[-1.671, -1.52, -1.111, 0, 1.051, 2.101, 3.152, 4.203] |
ops.sparse_sigmoid(x) |
int32 [0, 0, 0, 0, 1, 1, 1, 1] |
[0, 0, 0, 0.5, 1, 1, 1, 1] |
ops.sparse_plus(x) |
int32 [0, 0, 0, 0, 1, 2, 3, 4] |
[0, 0, 0, 0.25, 1, 2, 3, 4] |
ops.soft_shrink(x) |
int32 [-2, -1, 0, 0, 0, 1, 2, 3] |
[-2.5, -1.5, -0.5, 0, 0.5, 1.5, 2.5, 3.5] |
ops.threshold(x, 0.5, -0.5) |
int32 [0, 0, 0, 0, 1, 2, 3, 4] |
[-0.5, -0.5, -0.5, -0.5, 1, 2, 3, 4] |
ops.elu(x, alpha=0.5) |
float64 [-0, -0, -0, 0, 1, 2, 3, 4] |
[-0.475, -0.432, -0.316, 0, 1, 2, 3, 4] |
ops.celu(x, alpha=0.5) |
float64 [0, 0, 0, nan, nan, nan, nan, nan] |
[-0.499, -0.491, -0.432, 0, 1, 2, 3, 4] |
layers.LeakyReLU()(x) |
int32 [0, 0, 0, 0, 1, 2, 3, 4] |
[-0.9, -0.6, -0.3, 0, 1, 2, 3, 4] |
layers.ReLU(negative_slope=0.1)(x) |
int32 [0, 0, 0, 0, 1, 2, 3, 4] |
[-0.3, -0.2, -0.1, 0, 1, 2, 3, 4] |
Bool input np.array([True, False, True]) on numpy:
ops.gelugives float16[1.762, 0, 1.762]; JAX gives[0.841, 0, 0.841]. #23558 correctedgelufor integers, but not for bool.ops.selugives float16[1, 0, 1]; JAX gives[1.051, 0, 1.051].ops.sparse_sigmoid,ops.sparse_plusandops.threshold(x, 0.5, -0.5)give[1, 1, 1]; JAX gives[1, 0.5, 1],[1, 0.25, 1]and[1, -0.5, 1].ops.soft_shrinkgives[1, 0, 1]; JAX gives[0.5, 0, 0.5].
Other backends, same int32 input:
- OpenVINO:
leaky_relu,layers.LeakyReLU()andlayers.ReLU(negative_slope=0.1)give[0, 0, 0, 0, 1, 2, 3, 4].sparse_sigmoidgives all zeros.sparse_plusgives[0, 0, 0, 0, 1, 2, 3, 4].soft_shrinkreturns the input unchanged.threshold(x, 0.5, -0.5)gives[0, 0, 0, 0, 1, 2, 3, 4].selu,celuandgelustop with an error. - TensorFlow:
soft_shrinkgives int32[-2, -1, 0, 0, 0, 1, 2, 3]. The other ops stop with aTypeErroror anInvalidArgumentError. - torch:
threshold(x, 0.5, -0.5)gives int32[0, 0, 0, 0, 1, 2, 3, 4]. The other ops stop with aNotImplementedError.
Layers do not prevent this. The dtype policy keeps an integer input as an integer, so layers.LeakyReLU() on an int32 tensor gives the values above on numpy and OpenVINO, and the correct values on JAX and TensorFlow.
Cause
The backends write float values in the dtype of x. In keras/src/backend/numpy/ops/nn.py: np.array(negative_slope, x.dtype) (line 113), np.array(0.5 * (x + 1), x.dtype) (line 50), np.array(alpha, x.dtype) (lines 134 and 172), np.array(scale, x.dtype) (line 142) and np.array(default_value, dtype=x.dtype) (line 209). In keras/src/backend/openvino/ops/nn.py: get_ov_output(0.5, et) (line 126), get_ov_output(threshold, et) (lines 68 and 319), get_ov_output(0.25, et) (line 303) and get_ov_output(alpha, x.get_element_type()) (lines 31 and 153). For an integer dtype, 0.5 becomes 0.
Proposal
One rule for the whole family: promote integer and bool inputs to floatx(), and do not touch float inputs. This is the rule that exp uses in every backend:
if "int" in ori_dtype or ori_dtype == "bool":
x = cast(x, config.floatx())and the rule in Exp.compute_output_spec.
- Apply the cast in each backend, as
expdoes. Add the_promote_to_floathelper from #23545 to eachkeras/src/backend/<backend>/ops/nn.py. Call it in the 22 float-only activations:sigmoid,sparse_sigmoid,softplus,softsign,soft_shrink,sparse_plus,silu,squareplus,log_sigmoid,leaky_relu,hard_sigmoid,hard_silu,elu,selu,gelu,celu,glu,tanh_shrink,hard_shrink,softmax,log_softmaxandsparsemax. The JAX backend needs the cast too. On master, JAX raises aTypeErrorfor int32sigmoid,siluandglu, and gives NaN for uint8softmax. - In
keras/src/ops/nn.py, apply only the dtype rule, in thecompute_output_specof these 22 ops. The backend-agnostic_squareplusfallback casts its result to the input dtype, so it needs the cast too. - On numpy, the helper converts only inputs that are not arrays.
convert_to_tensorchanges a float64 array to float32, and it raises for float8.soft_shrink,sparse_plus,hard_sigmoid,hard_silu,softmaxandlog_softmaxdo not callconvert_to_tensoron master, so they keep float64 and float8 inputs. For the same reason,silu,glu,log_sigmoidandselucall private versions ofsigmoid,softplusandeluthat do not convert again. The helper replaces the numpygelucheck from #23558. thresholdkeeps an integer input dtype whenthresholdanddefault_valueare integer scalars. Check this withisinstance(v, numbers.Integral), which includes NumPy integer scalars such asnp.int32(1). The result is then exact: on master,ops.threshold(x, 1, 0)returns int32 with the correct values on all five backends. If the check does not include NumPy scalars,ops.threshold(x, np.int32(1), 0)changes to float32, and OpenVINO raises aRuntimeErrorfor it. For other scalars, and for bool input, the rule above applies.relu,relu6andhard_tanhdo not change. Their results are exact in the integer dtype. #23751 tracks the integer and bool results of these three ops on each backend.- On OpenVINO,
soft_shrinkandhard_shrinkcomparexwiththresholdand-threshold(greater,lessandselect) instead ofabs.convert_to_numpycompiles withINFERENCE_PRECISION_HINTset tof32. With this hint, the CPU plugin returnsAbs(Convert(c))unchanged for an int32 constantc. For example,ops.abs(ops.cast(x, "float32"))returns[-3, -1, 0, 2]for an int32x = [-3, -1, 0, 2]. - With
abs, the cast makeshard_shrinkgive[0, 0, 0, 0, 1, 2, 3, 4]for the int32xof the reproduction, andsoft_shrinkgive[0, 0, 0, 0, 0.5, 1.5, 2.5, 3.5]. On master,hard_shrinkgives the correct int32 values. The same problem gives wrongsoft_shrinkandhard_shrinkvalues on master for a float16 or bfloat16 input that comes fromops.cast. - In
keras/src/activations/activations.py,ReLU.static_callcallsbackend.ops.nn.leaky_reludirectly, so the backend cast covers that path. #23751 tracks the path withthresholdormax_value, which does not callleaky_relu.ReLU.compute_output_specgivesfloatx()for an integer or bool input whennegative_slope != 0. Without this change,activations.relu(x, negative_slope=0.1)gives a float32 eager result and an int32 symbolic result.Mish.static_callcallsbackend.ops.nn.softplusandbackend.ops.nn.tanhdirectly, and needs the same cast and spec. - Add one parametrized case to
NNOpsDtypeTestover the integer dtypes andboolfor the 22 ops. Compare the values with the result for the same values as float32. JAX is not a reference for this, because of the JAX results above. Also check that float16, float32 and float64 inputs keep their dtype (float64 not on numpy, see above). Checkthresholdwith integer and float scalars.
Put the cast in the backends, not in the keras.ops.nn entry points (the function and Operation.call). With the cast in the entry points, int32 and bool give the correct values on numpy, JAX, TensorFlow and torch under floatx="float32". Two problems stay:
- Callers that do not go through
keras.ops.nndo not get the cast.activations.mishon int32 returns float64 on numpy, and raisesNotImplementedErroron torch,InvalidArgumentErroron TensorFlow andRuntimeErroron OpenVINO.backend.ops.nn.leaky_reluon int32 gives truncated int32 values on numpy and OpenVINO. The review on #23721 gives the rule. Internal code andDynamicBackendcall the backend ops directly, so "All backend ops have to do the validation independently." - Under
floatx="float64", numpy returns float32 for the 17 ops that callconvert_to_tensor, butcompute_output_specgives float64. The numpy backend callsconvert_to_tensoragain after the cast.
A prototype of this fix changes the five backend nn.py files, keras/src/ops/nn.py, keras/src/activations/activations.py and keras/src/backend/common/backend_utils.py. For int8, int16, int32, int64, uint8 and bool inputs, the 22 ops and threshold(x, 0.5, -0.5) give the correct values. The eager and symbolic dtype is floatx(). This is true on all five backends, for floatx float32, bfloat16, float16 and float64 (float64 on JAX with jax_enable_x64).
Float16, bfloat16, float32 and float64 inputs give the same dtypes and values as on master. The only change is the OpenVINO soft_shrink and hard_shrink values above, which become correct. keras/src/ops/nn_test.py and keras/src/activations/activations_test.py have no new failures. On JAX with floatx="bfloat16", a NumPy integer input still gives float32, because convert_to_tensor already returns float32 for it (#23703).
cast(x, backend.result_type(x.dtype, float)), the rule in #23530 and in the first revision of #23545, is not the rule for this. It changes float64 to float32 on torch, numpy and OpenVINO, it rejects float8, and with floatx="bfloat16" it gives float16. Refer to the review on #23545. The current revision of #23545 adds a _promote_to_float helper with the rule above in each backend. This proposal applies that helper in every backend, for the whole family.
The float16 result under floatx="bfloat16" comes from _lattice_result_type, which resolves a weak float with the precision floatx()[-2:]. #23712 tracks that root cause. #23708 applies the rule above to rms_normalization and layer_normalization, and normalize in #23565 needs it too, so the whole family uses one rule.
Related
- #23545 (
hard_sigmoid,hard_silu), #23530 (gelu), #23558 (numpygelu, integers only) - #23642 moved the backend files to
keras/src/backend/<backend>/ops/ - #23751: the same rule for the other float-valued ops. Its PR 1 contains the fix for this issue and defines the rule once, as
float_output_dtypeinkeras/src/backend/common/dtypes.py. - #23754: the cast of integer and bool inputs to
compute_dtypein the layers, for examplelayers.LeakyReLU.
Source: keras-team/keras