Core: Fix scalar math edge cases in complex division, sign, log1p, norms and tanh libeigen/eigen!3571 Co-authored-by: Rasmus Munk Larsen <rmlarsen@gmail.com>
diff --git a/Eigen/src/Core/Dot.h b/Eigen/src/Core/Dot.h index 0304120..1d55994 100644 --- a/Eigen/src/Core/Dot.h +++ b/Eigen/src/Core/Dot.h
@@ -474,11 +474,55 @@ namespace internal { +// The p-th root of a nonnegative sum of p-th powers. RealScalar(1) / p is 0 for an integer RealScalar, so an integer +// root is truncated to the integer type, like the square root in norm(): it is the largest r with r^p <= sum. +template <typename RealScalar> +EIGEN_DEVICE_FUNC inline RealScalar lp_norm_root(const RealScalar& sum, int p, std::false_type /* IsInteger */) { + return numext::pow(sum, RealScalar(1) / p); +} + +// Whether base^p <= limit, without overflowing. +EIGEN_DEVICE_FUNC inline bool lp_norm_power_at_most(unsigned long long base, int p, unsigned long long limit) { + unsigned long long power = 1; + for (int i = 0; i < p; ++i) { + if (base != 0 && power > limit / base) return false; + power *= base; + } + return true; +} + +// Built-in integers: an estimate from double, which is off by at most a few units, is corrected by comparing exactly +// with the powers of its neighbors; pow(64., 1. / 3) = 3.9999999999999996 would otherwise truncate to 3. +template <typename RealScalar> +EIGEN_DEVICE_FUNC inline RealScalar lp_norm_integer_root(const RealScalar& sum, int p, + std::true_type /* is_integral */) { + // p <= 0 is outside the domain, and no root is at most the sum there: the loops below would not end. 1 / 0 is not + // evaluated either. + if (p <= 0) return numext::pow(sum, p == 0 ? RealScalar(0) : RealScalar(1) / p); + const unsigned long long s = static_cast<unsigned long long>(sum); + unsigned long long root = static_cast<unsigned long long>(numext::pow(static_cast<double>(s), 1.0 / p)); + while (lp_norm_power_at_most(root + 1, p, s)) ++root; + while (!lp_norm_power_at_most(root, p, s)) --root; + return static_cast<RealScalar>(root); +} + +// Other integer types: the estimate from double, truncated. +template <typename RealScalar> +EIGEN_DEVICE_FUNC inline RealScalar lp_norm_integer_root(const RealScalar& sum, int p, + std::false_type /* is_integral */) { + return static_cast<RealScalar>(numext::floor(numext::pow(static_cast<double>(sum), 1.0 / p))); +} + +template <typename RealScalar> +EIGEN_DEVICE_FUNC inline RealScalar lp_norm_root(const RealScalar& sum, int p, std::true_type /* IsInteger */) { + return lp_norm_integer_root(sum, p, bool_constant<std::is_integral<RealScalar>::value>()); +} + template <typename Derived, int p> struct lpNorm_selector { using RealScalar = typename NumTraits<typename traits<Derived>::Scalar>::Real; EIGEN_DEVICE_FUNC static inline RealScalar run(const MatrixBase<Derived>& m) { - return numext::pow(m.cwiseAbs().array().pow(p).sum(), RealScalar(1) / p); + return lp_norm_root(m.cwiseAbs().array().pow(p).sum(), p, bool_constant<NumTraits<RealScalar>::IsInteger>()); } }; @@ -516,6 +560,10 @@ * * In all cases, if \c *this is empty, then the value 0 is returned. * + * For the built-in integer scalar types the root is truncated to the integer type, as norm() does for \a p = 2: the + * result is the largest integer whose \a p-th power does not exceed the sum, which is exact for every sum that the type + * can hold. For other integer types it is truncated from an estimate in double. + * * \note For matrices, this function does not compute the <a * href="https://en.wikipedia.org/wiki/Operator_norm">operator-norm</a>. That is, if \c *this is a matrix, then its * coefficients are interpreted as a 1D vector. Nonetheless, you can easily compute the 1-norm and \f$\infty\f$-norm
diff --git a/Eigen/src/Core/MathFunctions.h b/Eigen/src/Core/MathFunctions.h index 0eb48f1..88e877b 100644 --- a/Eigen/src/Core/MathFunctions.h +++ b/Eigen/src/Core/MathFunctions.h
@@ -937,12 +937,36 @@ EIGEN_DEVICE_FUNC static inline Scalar run(const Scalar& a) { using real_type = typename NumTraits<Scalar>::Real; EIGEN_USING_STD(abs); - real_type aa = abs(a); - if (aa == real_type(0)) return Scalar(0); + EIGEN_USING_STD(sqrt); + const real_type re = numext::real(a); + const real_type im = numext::imag(a); + if (numext::is_exactly_zero(re) && numext::is_exactly_zero(im)) return Scalar(0); + // |z| lies in [m, sqrt(2) m] for m = max(|re|, |im|): it overflows only for m > max / sqrt(2) and is rounded to the + // subnormal grid for m < min. Then u = z / m, with max(|Re u|, |Im u|) = 1, gives sign(z) = u / sqrt(|u|^2). The + // trigger is on the components, as in psign_impl. Non-finite z keeps z / |z|. Under -ffast-math only m > max / 2 + // is known to give a unit result (tested from 0.6 max). |z| is formed only after the rescaling branch: for large m + // it would raise a spurious overflow, and a NaN component must not reach the 0 / 0 of the rescaling. + if ((isfinite_impl<real_type>)(re) && (isfinite_impl<real_type>)(im)) { + const real_type abs_re = abs(re); + const real_type abs_im = abs(im); + const real_type m = abs_re < abs_im ? abs_im : abs_re; + const real_type half_highest = NumTraits<real_type>::highest() / real_type(2); + if (EIGEN_PREDICT_FALSE(m < (numext::numeric_limits<real_type>::min)() || m > half_highest)) { + // For large m, z / m is formed as (z / 4) / (m / 4): -ffast-math rewrites z / m as z * (1 / m), and 1 / m is + // subnormal for m near max and flushed. The barrier keeps m / 4 from being folded back into the quotient. + const real_type scale = m > half_highest ? real_type(0.25) : real_type(1); + real_type scaled_m = m * scale; + volatile_barrier(scaled_m); + const real_type u_re = (re * scale) / scaled_m; + const real_type u_im = (im * scale) / scaled_m; + const real_type norm = sqrt(u_re * u_re + u_im * u_im); + return Scalar(u_re / norm, u_im / norm); + } + } + const real_type aa = abs(a); // Divide rather than multiply by 1/aa: the reciprocal overflows for subnormal aa and is itself - // subnormal, hence inexact, for aa near the top of the range. psign_impl for complex packets - // divides for the same reason. - return Scalar(numext::real(a) / aa, numext::imag(a) / aa); + // subnormal, hence inexact, for aa near the top of the range. + return Scalar(re / aa, im / aa); } }; @@ -1234,7 +1258,8 @@ } // |x - y|, as the packet path computes it: abs keeps the +0 of (+0, -0) and the NaN of (inf, inf). -template <typename T, bool IsInteger = NumTraits<T>::IsInteger> +template <typename T, bool IsInteger = NumTraits<T>::IsInteger, + bool IsSignedIntegral = std::is_integral<T>::value && std::is_signed<T>::value> struct absdiff_impl { EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE T run(const T& x, const T& y) { EIGEN_USING_STD(abs); @@ -1244,10 +1269,20 @@ // Unsigned x - y wraps, so integers order the operands. template <typename T> -struct absdiff_impl<T, true> { +struct absdiff_impl<T, true, false> { EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE T run(const T& x, const T& y) { return x > y ? x - y : y - x; } }; +// A signed integer subtracts in the unsigned type, since |x - y| > max overflows the signed one. +template <typename T> +struct absdiff_impl<T, true, true> { + EIGEN_DEVICE_FUNC static EIGEN_ALWAYS_INLINE T run(const T& x, const T& y) { + using U = std::make_unsigned_t<T>; + const U ux = static_cast<U>(x), uy = static_cast<U>(y); + return static_cast<T>(static_cast<U>(x > y ? ux - uy : uy - ux)); + } +}; + } // end namespace internal /**************************************************************************** @@ -2526,10 +2561,15 @@ const RealScalar y = z.imag(); // log|1 + z| = log1p(x (2 + x) + y^2) / 2. Rounding |1 + z| instead loses the real part to cancellation near // |1 + z| = 1, and with it the relative accuracy of log1p(z) for small z off the real axis. - if (numext::abs(x) < RealScalar(0.5) && numext::abs(y) < RealScalar(0.5) && !numext::is_exactly_zero(y)) { + const bool is_small = numext::abs(x) < RealScalar(0.5) && numext::abs(y) < RealScalar(0.5); + if (is_small && !numext::is_exactly_zero(y)) { return std::complex<RealScalar>(numext::log1p(x * (RealScalar(2) + x) + y * y) / RealScalar(2), numext::atan2(y, RealScalar(1) + x)); } + // The correction in std_fallback::log1p, z log(u) / (u - 1) for u = 1 + z, presumes log(u) ~ u - 1, so small z. For + // |z| >= 1/2 it only adds error, up to ~1e2 ulps in the argument for |x| >= 1e4 in float, where the quotient's + // imaginary part cancels; log(u) is accurate there. + if (!is_small) return numext::log(std::complex<RealScalar>(RealScalar(1) + x, y)); return std_fallback::log1p(z); } }; @@ -2648,6 +2688,38 @@ return std::complex<T>((a_real * b_real + a_imag * b_imag) / norm, (a_imag * b_real - a_real * b_imag) / norm); } +// x / y as a scalar division, which the optimizer cannot pack with another one. Clang 14 packs the two quotients of +// complex_divide_smith_large into one divps, whose spare lanes divide the denominator by itself (or another value that +// is not an operand), so an infinite denominator raises FE_INVALID where both quotients are zeros. +template <typename T> +EIGEN_DEVICE_FUNC EIGEN_DONT_INLINE T complex_divide_scalar_quotient(T x, T y) { + return x / y; +} + +// Smith's quotient where a numerator or the denominator has overflowed: a (b) is scaled by 1/4 where a component +// exceeds highest / 4, and the quotient by the inverse scale. rscale and iscale are Smith's ratios for b. +template <typename T> +EIGEN_DEVICE_FUNC EIGEN_DONT_INLINE std::complex<T> complex_divide_smith_large(const std::complex<T>& a, + const std::complex<T>& b, T rscale, + T iscale) { + const T quarter_highest = NumTraits<T>::highest() / T(4); + const T a_real = numext::real(a); + const T a_imag = numext::imag(a); + const T b_real = numext::real(b); + const T b_imag = numext::imag(b); + const bool large_a = numext::abs(a_real) > quarter_highest || numext::abs(a_imag) > quarter_highest; + const bool large_b = numext::abs(b_real) > quarter_highest || numext::abs(b_imag) > quarter_highest; + const T a_scale = large_a ? T(0.25) : T(1); + const T b_scale = large_b ? T(0.25) : T(1); + const T scaled_denominator = (b_real * b_scale) * rscale + (b_imag * b_scale) * iscale; + const T unscale = (large_a ? T(4) : T(1)) * b_scale; + const T real_quotient = + complex_divide_scalar_quotient((a_real * a_scale) * rscale + (a_imag * a_scale) * iscale, scaled_denominator); + const T imag_quotient = + complex_divide_scalar_quotient((a_imag * a_scale) * rscale - (a_real * a_scale) * iscale, scaled_denominator); + return std::complex<T>(real_quotient * unscale, imag_quotient * unscale); +} + template <typename T> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE std::complex<T> complex_divide_smith(const std::complex<T>& a, const std::complex<T>& b) { @@ -2676,8 +2748,19 @@ rscale = b_real / b_imag; } const T denominator = b_real * rscale + b_imag * iscale; - return std::complex<T>((a_real * rscale + a_imag * iscale) / denominator, - (a_imag * rscale - a_real * iscale) / denominator); + const T numerator_real = a_real * rscale + a_imag * iscale; + const T numerator_imag = a_imag * rscale - a_real * iscale; + // The numerators are at most 2 max(|a_r|, |a_i|) and the denominator lies in [m, 2 m] for m = max(|b_r|, |b_i|), so + // any of them can overflow where the quotient does not, as in pdiv_complex, which this follows. Each is tested on its + // own, by a test that raises no exception for a NaN: a test of their sum raises FE_OVERFLOW, and FE_INVALID + // for inf - inf, where no term overflows. The tests are folded under -ffinite-math-only, where division then behaves + // as before the guard (no rescaling). + const int overflowed = + int((numext::isinf)(numerator_real)) | int((numext::isinf)(numerator_imag)) | int((numext::isinf)(denominator)); + if (EIGEN_PREDICT_FALSE(overflowed != 0)) { + return complex_divide_smith_large(a, b, rscale, iscale); + } + return std::complex<T>(numerator_real / denominator, numerator_imag / denominator); } template <typename T>
diff --git a/Eigen/src/Core/StableNorm.h b/Eigen/src/Core/StableNorm.h index edb8afa..260094f 100644 --- a/Eigen/src/Core/StableNorm.h +++ b/Eigen/src/Core/StableNorm.h
@@ -154,8 +154,54 @@ return typename Derived::RealScalar(0); } +// floor(sqrt(sum x_i^2)), saturated at the highest value of the type. The sum is accumulated in double: squaring in +// the integer type, as norm() does, overflows where the norm is representable. For a sum s < 2^53 (exact in double) the +// root is corrected to the exact floor, since sqrt(n^2 - 1) rounds up to n; beyond it, it is a truncated estimate. A +// single coefficient gives |x|, exact where x is not representable in double. +template <typename Derived> +inline typename Derived::RealScalar integer_l2_norm(const Derived& vec, std::true_type /* is_integral */) { + using RealScalar = typename Derived::RealScalar; + decltype(auto) components = vec.realView(); + if (components.size() == 1) { + const RealScalar x = components.coeff(0, 0); + return (NumTraits<RealScalar>::IsSigned && x == NumTraits<RealScalar>::lowest()) ? NumTraits<RealScalar>::highest() + : numext::abs(x); + } + const double sum = components.template cast<double>().squaredNorm(); + const double root = numext::floor(numext::sqrt(sum)); + if (root >= static_cast<double>(NumTraits<RealScalar>::highest())) return NumTraits<RealScalar>::highest(); + unsigned long long result = static_cast<unsigned long long>(root); + if (sum < 9007199254740992.0) { // 2^53 + const unsigned long long squares = static_cast<unsigned long long>(sum); + while (result * result > squares) --result; + while ((result + 1) * (result + 1) <= squares) ++result; + } + return static_cast<RealScalar>(result); +} + +// Other integer types: norm(). +template <typename Derived> +inline typename Derived::RealScalar integer_l2_norm(const Derived& vec, std::false_type /* is_integral */) { + return vec.norm(); +} + +template <typename Derived> +inline typename Derived::RealScalar integer_l2_norm(const Derived& vec) { + return integer_l2_norm(vec, bool_constant<std::is_integral<typename Derived::RealScalar>::value>()); +} + +// The scaling below guards floating-point accumulation against over- and underflow, and is meaningless for integers. +template < + typename Derived, + std::enable_if_t<NumTraits<typename Derived::Scalar>::IsInteger && Derived::MaxSizeAtCompileTime != 0, int> = 0> +typename Derived::RealScalar stable_norm_impl(const Derived& vec) { + return integer_l2_norm(vec); +} + template <typename VectorType, - std::enable_if_t<VectorType::IsVectorAtCompileTime && VectorType::MaxSizeAtCompileTime != 0, int> = 0> + std::enable_if_t<VectorType::IsVectorAtCompileTime && VectorType::MaxSizeAtCompileTime != 0 && + !NumTraits<typename VectorType::Scalar>::IsInteger, + int> = 0> typename VectorType::RealScalar stable_norm_impl(const VectorType& vec) { Index n = vec.size(); if (EIGEN_PREDICT_FALSE(n == 1)) return numext::abs(vec.coeff(0)); @@ -172,7 +218,9 @@ } template <typename MatrixType, - std::enable_if_t<!MatrixType::IsVectorAtCompileTime && MatrixType::MaxSizeAtCompileTime != 0, int> = 0> + std::enable_if_t<!MatrixType::IsVectorAtCompileTime && MatrixType::MaxSizeAtCompileTime != 0 && + !NumTraits<typename MatrixType::Scalar>::IsInteger, + int> = 0> typename MatrixType::RealScalar stable_norm_impl(const MatrixType& mat) { using RealScalar = typename MatrixType::RealScalar; using Accumulator = typename stable_norm_accumulator<RealScalar>::type; @@ -224,7 +272,12 @@ } }; -template <typename Derived> +template <typename Derived, std::enable_if_t<NumTraits<typename traits<Derived>::Scalar>::IsInteger, int> = 0> +inline typename NumTraits<typename traits<Derived>::Scalar>::Real blueNorm_impl(const EigenBase<Derived>& vec) { + return integer_l2_norm(vec.derived()); +} + +template <typename Derived, std::enable_if_t<!NumTraits<typename traits<Derived>::Scalar>::IsInteger, int> = 0> inline typename NumTraits<typename traits<Derived>::Scalar>::Real blueNorm_impl(const EigenBase<Derived>& _vec) { using RealScalar = typename Derived::RealScalar; using Accumulator = typename stable_norm_accumulator<RealScalar>::type; @@ -289,6 +342,20 @@ return RealScalar(scale * numext::sqrt(sumsq)); } +template <typename Derived> +inline typename Derived::RealScalar hypot_norm_impl(const Derived& vec, std::true_type /* IsInteger */) { + return integer_l2_norm(vec); +} + +template <typename Derived> +inline typename Derived::RealScalar hypot_norm_impl(const Derived& vec, std::false_type /* IsInteger */) { + using RealScalar = typename Derived::RealScalar; + using Accumulator = typename stable_norm_accumulator<RealScalar>::type; + // Component reduction avoids rounded complex magnitudes and permits promoted accumulation. + return RealScalar(redux_with_identity(vec.realView().template cast<Accumulator>().cwiseAbs(), + scalar_hypot_op<Accumulator>(), Accumulator(0))); +} + } // end namespace internal /** \returns the \em l2 norm of \c *this avoiding underflow and overflow. @@ -300,6 +367,10 @@ * For architecture/scalar types supporting vectorization, this version * is faster than blueNorm(). Otherwise the blueNorm() is much faster. * + * For integer scalar types there is nothing to scale. The result is the square root of the sum of squares, truncated + * to the integer type and saturated at its highest value; the sum is accumulated in \c double, so that it does not + * overflow where norm() does. The truncated root is exact where the sum is below \f$ 2^{53} \f$. + * * \sa norm(), blueNorm(), hypotNorm() */ template <typename Derived> @@ -317,6 +388,8 @@ * For architecture/scalar types without vectorization, this version * is much faster than stableNorm(). Otherwise the stableNorm() is faster. * + * For integer scalar types this is the same as stableNorm(). + * * \sa norm(), stableNorm(), hypotNorm() */ template <typename Derived> @@ -327,14 +400,13 @@ /** \returns the \em l2 norm of \c *this avoiding underflow and overflow. * This version use a concatenation of hypot() calls, and it is very slow. * + * For integer scalar types this is the same as stableNorm(). + * * \sa norm(), stableNorm() */ template <typename Derived> inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real MatrixBase<Derived>::hypotNorm() const { - using Accumulator = typename internal::stable_norm_accumulator<RealScalar>::type; - // Component reduction avoids rounded complex magnitudes and permits promoted accumulation. - return RealScalar(internal::redux_with_identity(derived().realView().template cast<Accumulator>().cwiseAbs(), - internal::scalar_hypot_op<Accumulator>(), Accumulator(0))); + return internal::hypot_norm_impl(derived(), internal::bool_constant<NumTraits<Scalar>::IsInteger>()); } } // end namespace Eigen
diff --git a/Eigen/src/Core/arch/Default/GenericPacketMathFunctions.h b/Eigen/src/Core/arch/Default/GenericPacketMathFunctions.h index 7220e64..7ae0e82 100644 --- a/Eigen/src/Core/arch/Default/GenericPacketMathFunctions.h +++ b/Eigen/src/Core/arch/Default/GenericPacketMathFunctions.h
@@ -933,6 +933,21 @@ l = pselect(a_min_zero_mask, a_max, l); // Step 2 compute a / abs(a). RealPacket sign_as_real = pandnot(pdiv(a.v, l), a_max_zero_mask); + // l overflows only for a_max > highest / sqrt(2), and is inexact for subnormal a_max. Elements with a_max < min or + // a_max > highest / 2, as in the scalar sign_impl, are recomputed as (a / a_max) / sqrt(1 + r^2), whose first + // factor has max(|Re|, |Im|) = 1; the others keep a / l. A NaN component gives NaN in both, as the scalar version + // does. Non-finite a_max keeps a / l. + const RealPacket cst_min = pset1<RealPacket>((numext::numeric_limits<RealScalar>::min)()); + const RealPacket cst_highest = pset1<RealPacket>(NumTraits<RealScalar>::highest()); + const RealPacket cst_half_highest = pset1<RealPacket>(NumTraits<RealScalar>::highest() / RealScalar(2)); + const RealPacket extreme = por(pandnot(pcmp_lt(a_max, cst_min), a_max_zero_mask), pcmp_lt(cst_half_highest, a_max)); + if (EIGEN_PREDICT_FALSE(predux_any(extreme))) { + RealPacket unit_sign = pdiv(pdiv(a.v, a_max), psqrt(pmadd(r, r, cst_one))); + const RealPacket a_nan = pisnan(a.v); + const RealPacket any_nan = por(a_nan, pcplxflip(Packet(a_nan)).v); + unit_sign = pselect(any_nan, padd(a.v, pcplxflip(a).v), unit_sign); + sign_as_real = pselect(pand(extreme, pcmp_le(a_max, cst_highest)), unit_sign, sign_as_real); + } Packet sign; sign.v = sign_as_real; return sign;
diff --git a/Eigen/src/Core/arch/Default/GenericPacketMathTrig.h b/Eigen/src/Core/arch/Default/GenericPacketMathTrig.h index b54d917..484ae07 100644 --- a/Eigen/src/Core/arch/Default/GenericPacketMathTrig.h +++ b/Eigen/src/Core/arch/Default/GenericPacketMathTrig.h
@@ -623,14 +623,31 @@ // Hyperbolic Functions //---------------------------------------------------------------------- +// Whether a scalar a * b + c is fused is up to the compiler (GCC contracts it across statements whatever +// scalar_madd_uses_fma says), and the rational approximations of tanh below first reach 1 at different arguments when +// it is, and stay within a few ulps of 1 beyond it. A scalar therefore returns +-1 for |x| >= clamp, which is no +// smaller than either point (the error at the clamp is stated at ptanh_float and ptanh_double). Packets use pmadd, +// which is deterministic. +template <typename T> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T ptanh_saturate(const T&, const T& tanh_x, const T&, std::false_type) { + return tanh_x; +} +template <typename T> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T ptanh_saturate(const T& x, const T& tanh_x, const T& clamp, std::true_type) { + return numext::abs(x) >= clamp ? numext::copysign(T(1), x) : tanh_x; +} + #if EIGEN_FAST_MATH /** \internal \returns the hyperbolic tan of \a a (coeff-wise) - Doesn't do anything fancy, just a 9/8-degree rational interpolant which - is accurate up to a couple of ulps in the (approximate) range [-8, 8], - outside of which tanh(x) = +/-1 in single precision. The input is clamped - to the range [-c, c]. The value c is chosen as the smallest value where - the approximation evaluates to exactly 1. + Doesn't do anything fancy, just a 9/8-degree rational interpolant. The input + is clamped to the range [-c, c], where c is the smallest argument at which + the approximation evaluates to exactly 1: c = 7.91 without FMA, 8.02 with. + That is short of where tanh rounds to 1 (x > 9.01), so at c the result + exceeds tanh(c) by 2 exp(-2c) = 4.5 (3.6) ulp of float below 1 (computed + from the formula, not measured). Measured maximum error, with + test/ulp_accuracy against MPFR over all floats in [1e-3, 9.5], in ulps of + float: 6 at x = 4.9 on SSE2 (no FMA), 5 at x = 4.1 on AVX2 with FMA. This implementation works on both scalars and packets. */ @@ -643,8 +660,7 @@ #ifdef EIGEN_VECTORIZE_FMA constexpr float kClamp = 8.01773357391357422f; #else - constexpr bool kUsesFma = is_scalar<T>::value && scalar_madd_uses_fma<T>::value; - constexpr float kClamp = kUsesFma ? 8.01773357391357422f : 7.90738964080810547f; + constexpr float kClamp = is_scalar<T>::value ? 8.01773357391357422f : 7.90738964080810547f; #endif const T plus_clamp = pset1<T>(kClamp); const T minus_clamp = pset1<T>(-kClamp); @@ -674,7 +690,7 @@ p = pmadd(x3, p, x); // Divide the numerator by the denominator. - return pdiv(p, q); + return ptanh_saturate(a_x, pdiv(p, q), plus_clamp, bool_constant<is_scalar<T>::value>()); } #else @@ -726,11 +742,15 @@ #endif // EIGEN_FAST_MATH /** \internal \returns the hyperbolic tan of \a a (coeff-wise) - This uses a 19/18-degree rational interpolant which - is accurate up to a couple of ulps in the (approximate) range [-18.7, 18.7], - outside of which tanh(x) = +/-1 in double precision. The input is clamped - to the range [-c, c]. The value c is chosen as the smallest value where - the approximation evaluates to exactly 1. + This uses a 19/18-degree rational interpolant. The input is clamped to the + range [-c, c], where c is the smallest argument at which the approximation + evaluates to exactly 1: c = 17.71 without FMA, 17.66 with. That is short of + where tanh rounds to 1 (x > 19.06), so at c the result exceeds tanh(c) by + 2 exp(-2c) = 7.4 (8.2) ulp of double below 1 (computed from the formula, not + measured). Measured maximum error, with test/ulp_accuracy against MPFR + sampled in geometric steps of 1e-7 on [1e-3, 8] and 1e-8 on [8, 19.5], in + ulps of double: 10 at x = 14.2 on SSE2 (no FMA), 8 at x = 16.0 on AVX2 with + FMA. This implementation works on both scalars and packets. */ @@ -743,8 +763,7 @@ #ifdef EIGEN_VECTORIZE_FMA constexpr double kClamp = 17.6610191624600077; #else - constexpr bool kUsesFma = is_scalar<T>::value && scalar_madd_uses_fma<T>::value; - constexpr double kClamp = kUsesFma ? 17.6610191624600077 : 17.714196154005176; + constexpr double kClamp = 17.714196154005176; #endif const T plus_clamp = pset1<T>(kClamp); const T minus_clamp = pset1<T>(-kClamp); @@ -781,7 +800,7 @@ p = pmadd(x3, p, x); // Divide the numerator by the denominator. - return pdiv(p, q); + return ptanh_saturate(a_x, pdiv(p, q), plus_clamp, bool_constant<is_scalar<T>::value>()); } template <typename Packet>
diff --git a/Eigen/src/Core/functors/UnaryFunctors.h b/Eigen/src/Core/functors/UnaryFunctors.h index 2bb1ba5..87553a4 100644 --- a/Eigen/src/Core/functors/UnaryFunctors.h +++ b/Eigen/src/Core/functors/UnaryFunctors.h
@@ -441,8 +441,22 @@ } template <typename Packet> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& a) const { - // pldexp clamps exponents, so a saturating conversion to Scalar is safe. - return internal::pldexp(a, pset1<Packet>(static_cast<Scalar>(m_exponent))); + // A nonzero finite a lies in [2^(emin - digits), 2^emax), so |e| > B = emax - emin + digits overflows or underflows + // as B + 1 does, and converting e to Scalar is exact where it matters if B < 2^digits: float, double and half + // (B = 40 < 2^11), but not bfloat16 (B = 261 > 2^8, where odd |e| in [257, 261] would round). Those are applied in + // two steps, e - 256 sign(e) and then 256 sign(e), which round once. Locals, not class constants, keep a custom + // Scalar with non-constexpr NumTraits compiling; for float, double and half they fold. + const int digits = NumTraits<Scalar>::digits(); + const int bound = NumTraits<Scalar>::max_exponent() - NumTraits<Scalar>::min_exponent() + digits; + const Scalar exponent = static_cast<Scalar>(m_exponent); + const int pow2_digits = 1 << (digits < 24 ? digits : 24); // 2^digits; the cap at 2^24 avoids overflowing int + const bool exact = bound < pow2_digits; + if (exact || m_exponent > bound || m_exponent < -bound || static_cast<double>(exponent) == m_exponent) { + return internal::pldexp(a, pset1<Packet>(exponent)); + } + const int step = m_exponent < 0 ? -pow2_digits : pow2_digits; + return internal::pldexp(internal::pldexp(a, pset1<Packet>(static_cast<Scalar>(m_exponent - step))), + pset1<Packet>(static_cast<Scalar>(step))); } private: @@ -570,12 +584,16 @@ } private: - // 0: float, double or long double; 1: std::complex of one of them; 2: any other scalar, user types included. + // 0: float, double, long double, half or bfloat16; 1: std::complex of a floating-point type; 2: any other scalar, + // user types included. static constexpr int kKind = - std::is_floating_point<Scalar>::value ? 0 + (std::is_floating_point<Scalar>::value || std::is_same<Scalar, half>::value || + std::is_same<Scalar, bfloat16>::value) + ? 0 : std::is_floating_point<RealScalar>::value && std::is_same<Scalar, std::complex<RealScalar>>::value ? 1 : 2; - // std::log2 is exact at powers of two, like plog2; log2(e) * log(a) can be an ulp off there. complex_log2 takes the + // std::log2 is exact at powers of two, like plog2; log2(e) * log(a) can be an ulp off there, and two off for half and + // bfloat16, which round both factors. numext::log2 of half and bfloat16 goes through float. complex_log2 takes the // real part log2|a| from std::log2, like plog2 on complex packets. EIGEN_DEVICE_FUNC static Scalar run(const Scalar& a, std::integral_constant<int, 0>) { return numext::log2(a); } EIGEN_DEVICE_FUNC static Scalar run(const Scalar& a, std::integral_constant<int, 1>) { @@ -1250,7 +1268,7 @@ return bitwise_unary_impl<Scalar>::run_not(a); } template <typename Packet> - EIGEN_STRONG_INLINE Packet packetOp(const Packet& a) const { + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet packetOp(const Packet& a) const { return pandnot(ptrue(a), a); } };
diff --git a/doc/CoeffwiseMathFunctionsTable.dox b/doc/CoeffwiseMathFunctionsTable.dox index e288bc4..163c0fb 100644 --- a/doc/CoeffwiseMathFunctionsTable.dox +++ b/doc/CoeffwiseMathFunctionsTable.dox
@@ -733,7 +733,7 @@ <tr><th colspan="5">Hyperbolic</th></tr> <tr><td>sinh</td> <td>2</td> <td>0.008</td> <td>99.2%</td> <td></td></tr> <tr><td>cosh</td> <td>2</td> <td>0.014</td> <td>98.6%</td> <td></td></tr> -<tr><td>tanh</td> <td>6</td> <td>0.030</td> <td>97.2%</td> <td></td></tr> +<tr><td>tanh</td> <td>6</td> <td>0.030</td> <td>97.2%</td> <td>\ref CoeffwiseMathFunctionsAccuracy_note8 "8"</td></tr> <tr><td>asinh</td> <td>2</td> <td>0.165</td> <td>83.5%</td> <td></td></tr> <tr><td>acosh</td> <td>3</td> <td>0.074</td> <td>92.6%</td> <td></td></tr> <tr><td>atanh</td> <td>2</td> <td>0.004</td> <td>99.6%</td> <td></td></tr> @@ -770,7 +770,7 @@ <tr><th colspan="5">Hyperbolic</th></tr> <tr><td>sinh</td> <td>2</td> <td>0.001</td> <td>99.9%</td> <td></td></tr> <tr><td>cosh</td> <td>2</td> <td>0.003</td> <td>99.7%</td> <td></td></tr> -<tr><td>tanh</td> <td>8</td> <td>0.008</td> <td>99.3%</td> <td></td></tr> +<tr><td>tanh</td> <td>10</td> <td>0.008</td> <td>99.3%</td> <td>\ref CoeffwiseMathFunctionsAccuracy_note8 "8"</td></tr> <tr><td>asinh</td> <td>2</td> <td>0.199</td> <td>80.2%</td> <td></td></tr> <tr><td>acosh</td> <td>3</td> <td>0.098</td> <td>90.3%</td> <td></td></tr> <tr><td>atanh</td> <td>2</td> <td><0.001</td> <td>>99.9%</td> <td></td></tr> @@ -845,6 +845,16 @@ instruction. The last step is taken on the square root itself with a fused residual: the max error is 1 ULP, and 99.5% of the float and 99.4% of the double results are exact. +\anchor CoeffwiseMathFunctionsAccuracy_note8 +<b>8. tanh near saturation:</b> +The vectorized tanh clamps its argument where its rational approximation first evaluates to exactly 1, which is short of +where tanh rounds to 1 (|x| > 9.01 in float, |x| > 19.06 in double). At the clamp the result exceeds the true value +by 2 exp(-2c), computed from the formula: 4.5 ULP in float without FMA (c = 7.91) and 3.6 with FMA (c = 8.02), 7.4 ULP +in double without FMA (c = 17.71) and 8.2 with FMA (c = 17.66). The maximum errors in the tables are measured with +<tt>ulp_accuracy</tt> against MPFR on SSE2: 6 ULP in float (exhaustive over [1e-3, 9.5], at |x| = 4.9) and 10 ULP in +double, which samples a finer step (1e-8 above |x| = 8, at |x| = 14.2) than the 10<sup>-6</sup> of the other double +entries. With AVX2 and FMA the same measurements give 5 ULP in float and 8 ULP in double. + */ }
diff --git a/test/array_cwise.cpp b/test/array_cwise.cpp index 7c96f58..8e1b881 100644 --- a/test/array_cwise.cpp +++ b/test/array_cwise.cpp
@@ -232,6 +232,70 @@ */ } +// The scalar tanh approximations return +-1 where tanh rounds to it, whether or not the compiler fuses their +// multiply-adds (GCC does, with FMA available, even when Eigen is not vectorized). +inline float scalar_tanh_approximation(float x) { return internal::ptanh_float(x); } +inline double scalar_tanh_approximation(double x) { return internal::ptanh_double(x); } + +template <typename Scalar> +void tanh_saturation_test() { + const Scalar inf = NumTraits<Scalar>::infinity(), highest = NumTraits<Scalar>::highest(); + const Scalar rounds_to_one = std::is_same<Scalar, float>::value ? Scalar(9.1) : Scalar(19.1); + for (const Scalar x : {rounds_to_one, Scalar(2) * rounds_to_one, Scalar(100), Scalar(1e10), highest, inf}) { + VERIFY_IS_EQUAL(scalar_tanh_approximation(x), Scalar(1)); + VERIFY_IS_EQUAL(scalar_tanh_approximation(-x), Scalar(-1)); + VERIFY_IS_EQUAL(numext::tanh(x), Scalar(1)); + VERIFY_IS_EQUAL(numext::tanh(-x), Scalar(-1)); + } + // The approximation never exceeds 1 in magnitude on the way to saturation. + for (Scalar x = Scalar(0.5); x < rounds_to_one; x += Scalar(0.0125)) { + VERIFY(numext::abs(scalar_tanh_approximation(x)) <= Scalar(1)); + VERIFY(numext::abs(scalar_tanh_approximation(-x)) <= Scalar(1)); + } + VERIFY((numext::isnan)(scalar_tanh_approximation(NumTraits<Scalar>::quiet_NaN()))); +} + +// log2 of half and bfloat16 is exact at powers of two, subnormal ones included, on the scalar path (size 1) and in the +// packet body and tail. +template <typename Scalar> +void log2_narrow_test() { +#if EIGEN_ARCH_ARM // 32-bit ARM flushes subnormals. + const int min_exp = NumTraits<Scalar>::min_exponent() - 1; +#else + const int min_exp = NumTraits<Scalar>::min_exponent() - NumTraits<Scalar>::digits(); // 2^-24 and 2^-133 +#endif + const int max_exp = NumTraits<Scalar>::max_exponent() - 1; + for (const Index size : {Index(1), 2 * Index(internal::packet_traits<Scalar>::size) + 1}) { + for (int e = min_exp; e <= max_exp; ++e) { + const ArrayX<Scalar> x = ArrayX<Scalar>::Constant(size, Scalar(std::ldexp(1.0f, e))); + const ArrayX<Scalar> y = x.log2(); + for (Index i = 0; i < size; ++i) VERIFY_IS_EQUAL(float(y(i)), float(e)); + } + } +} + +// |x - y| of signed integers that differ by more than the maximum wraps modulo 2^digits, as pabsdiff does. +template <typename Scalar> +void absolute_difference_integer_test() { + using Unsigned = std::make_unsigned_t<Scalar>; + const Scalar lowest = (std::numeric_limits<Scalar>::min)(), highest = (std::numeric_limits<Scalar>::max)(); + const Scalar values[] = {lowest, Scalar(lowest + 1), Scalar(-1), Scalar(0), Scalar(1), Scalar(highest - 1), highest}; + const Index n = Index(sizeof(values) / sizeof(values[0])); + const Index size = n * n; + ArrayX<Scalar> x(size), y(size), expected(size); + for (Index i = 0; i < n; ++i) { + for (Index j = 0; j < n; ++j) { + x(i * n + j) = values[i]; + y(i * n + j) = values[j]; + const Unsigned a = Unsigned(values[i]), b = Unsigned(values[j]); + expected(i * n + j) = Scalar(Unsigned(values[i] > values[j] ? a - b : b - a)); + } + } + const ArrayX<Scalar> got = x.absolute_difference(y); + VERIFY_IS_CWISE_EQUAL(got, expected); + for (Index k = 0; k < size; ++k) VERIFY_IS_EQUAL(numext::absdiff(x(k), y(k)), expected(k)); +} + template <typename Scalar> void ldexp_test() { const std::vector<Scalar> vals = special_values<Scalar>(); @@ -246,19 +310,24 @@ const int digits = std::numeric_limits<Scalar>::digits; const int max_exp = std::numeric_limits<Scalar>::max_exponent; // Include denormals, saturation, and unrepresentable 2^e scale factors. - const int exponents[] = {0, - 1, - -1, - digits - 1, - 1 - digits, - max_exp - 1, - 1 - max_exp, - max_exp + digits, - -(max_exp + digits), - 2 * max_exp, - -2 * max_exp, - (std::numeric_limits<int>::max)(), - (std::numeric_limits<int>::min)()}; + std::vector<int> exponents = {0, + 1, + -1, + digits - 1, + 1 - digits, + max_exp - 1, + 1 - max_exp, + max_exp + digits, + -(max_exp + digits), + 2 * max_exp, + -2 * max_exp, + (std::numeric_limits<int>::max)(), + (std::numeric_limits<int>::min)(), + 70000, + -70000}; + // Every exponent that matters for subnormal inputs and near-overflow results, including those that bfloat16 cannot + // represent as a Scalar (odd |e| > 256). + for (int exponent = -300; exponent <= 300; ++exponent) exponents.push_back(exponent); bool all_pass = true; for (const int exponent : exponents) { @@ -266,10 +335,13 @@ const Array<Scalar, Dynamic, 1> global_result = Eigen::ldexp(x, exponent); for (Index i = 0; i < x.size(); ++i) { // double covers every tested Scalar, so one conversion back gives the exact reference. - const double expected = static_cast<double>(static_cast<Scalar>(std::ldexp(static_cast<double>(x(i)), exponent))); + const double exact = std::ldexp(static_cast<double>(x(i)), exponent); + const double expected = static_cast<double>(static_cast<Scalar>(exact)); #if EIGEN_ARCH_ARM - // Work around 32-bit ARM flush-to-zero mode: skip cases with subnormal results. - if (expected != 0.0 && std::abs(expected) < static_cast<double>((std::numeric_limits<Scalar>::min)())) continue; + // Work around 32-bit ARM flush-to-zero mode: skip cases with subnormal results. Tininess is detected before + // rounding, so a result below the smallest normal that rounds up to it, such as (2 - 2^-23) * 2^-127, is + // flushed too. + if (expected != 0.0 && std::abs(exact) < static_cast<double>((std::numeric_limits<Scalar>::min)())) continue; #endif for (const Scalar& result : {method_result(i), global_result(i)}) { const double actual = static_cast<double>(result); @@ -285,6 +357,31 @@ VERIFY(all_pass); } +// A custom scalar whose NumTraits members are plain functions, not constexpr (as for mpfr::mpreal), still has ldexp. +struct NonConstexprReal { + NonConstexprReal() : value(0) {} + explicit NonConstexprReal(double v) : value(v) {} + double value; +}; +inline NonConstexprReal ldexp(const NonConstexprReal& x, int exponent) { + return NonConstexprReal(std::ldexp(x.value, exponent)); +} +namespace Eigen { +template <> +struct NumTraits<NonConstexprReal> : GenericNumTraits<NonConstexprReal> { + static int digits() { return 53; } + static int min_exponent() { return -1021; } + static int max_exponent() { return 1024; } +}; +} // namespace Eigen + +void ldexp_custom_scalar_test() { + ArrayX<NonConstexprReal> x(5); + for (Index i = 0; i < x.size(); ++i) x(i) = NonConstexprReal(double(i) + 0.5); + const ArrayX<NonConstexprReal> y = x.ldexp(3); + for (Index i = 0; i < x.size(); ++i) VERIFY_IS_EQUAL(y(i).value, 8.0 * (double(i) + 0.5)); +} + template <typename Base, typename Exponent, bool ExpIsInteger = NumTraits<Exponent>::IsInteger> struct ref_pow { static Base run(Base base, Exponent exponent) { @@ -1870,8 +1967,13 @@ for (int i = 0; i < g_repeat; i++) { CALL_SUBTEST_34(ldexp_test<float>()); CALL_SUBTEST_35(ldexp_test<double>()); + CALL_SUBTEST_34(tanh_saturation_test<float>()); + CALL_SUBTEST_35(tanh_saturation_test<double>()); CALL_SUBTEST_36(ldexp_test<Eigen::half>()); CALL_SUBTEST_37(ldexp_test<Eigen::bfloat16>()); + CALL_SUBTEST_36(log2_narrow_test<Eigen::half>()); + CALL_SUBTEST_37(log2_narrow_test<Eigen::bfloat16>()); + CALL_SUBTEST_37(ldexp_custom_scalar_test()); } for (int i = 0; i < g_repeat; i++) { CALL_SUBTEST_23(typed_logicals_test(ArrayX<int>(internal::random<int>(1, EIGEN_TEST_MAX_SIZE)))); @@ -1890,6 +1992,10 @@ CALL_SUBTEST_27(typed_logicals_test(ArrayX<std::complex<double>>(internal::random<int>(1, EIGEN_TEST_MAX_SIZE)))); CALL_SUBTEST_42(bool_logical_ops<>()); CALL_SUBTEST_43(modulus_tests()); + CALL_SUBTEST_43(absolute_difference_integer_test<int8_t>()); + CALL_SUBTEST_43(absolute_difference_integer_test<int16_t>()); + CALL_SUBTEST_43(absolute_difference_integer_test<int32_t>()); + CALL_SUBTEST_43(absolute_difference_integer_test<int64_t>()); } for (int i = 0; i < g_repeat; i++) {
diff --git a/test/fastmath.cpp b/test/fastmath.cpp index 49e11a7..e46bea4 100644 --- a/test/fastmath.cpp +++ b/test/fastmath.cpp
@@ -9,6 +9,7 @@ // SPDX-License-Identifier: MPL-2.0 #include "main.h" +#include "fp_control.h" #include <Eigen/QR> #include <iomanip> #include <vector> @@ -603,7 +604,46 @@ } } +template <typename Scalar> +EIGEN_DONT_INLINE Scalar fastmath_scalar_sign(const Scalar& z) { + return numext::sign(z); +} + +// The scalar numext::sign of z with max(|Re z|, |Im z|) above highest / 2 tests the components, not an inf |z|, and +// divides by m / 4 behind a barrier, because -ffast-math turns z / m into z * (1 / m) and 1 / m is flushed there. The +// operands come from a volatile scale, so that nothing is folded at compile time, and subnormals are flushed. +// Array::sign() is not checked: its packet path is wrong near overflow under -ffast-math. Only m >= 0.6 max is covered; +// the scalar result under -ffast-math can still be 0 or NaN for sqrt(max) < |z| <= max / 2 and for |z| < sqrt(min). +template <typename RealScalar> +void check_complex_sign_overflow() { + using Scalar = std::complex<RealScalar>; + // Subnormals are flushed, as in a program linked with -ffast-math, which a test linked without it would not do. + ScopedFlushToZero flush_to_zero(FlushToZeroMode::Both); + volatile RealScalar unit = RealScalar(1); + const RealScalar highest = (std::numeric_limits<RealScalar>::max)() * unit; + const RealScalar h = RealScalar(0.75) * highest; + // The quotient, the square root and the final quotient round at most 0.5 ulp each (about 1.5 eps together), and the + // constant sqrt_half rounds 0.5 ulp more; 8 eps leaves margin. Not a measured maximum. + const RealScalar tol = RealScalar(8) * NumTraits<RealScalar>::epsilon(); + const RealScalar sqrt_half = RealScalar(0.70710678118654752440); + // A NaN result must fail: under -ffast-math a comparison with a NaN is not reliable, but the bits of a nonnegative + // float order like its value, and those of a NaN lie above every finite one. + using Bits = typename numext::get_integer_by_size<sizeof(RealScalar)>::unsigned_type; + const auto close = [&](const Scalar& x, const Scalar& y) { + const RealScalar bound = tol * numext::abs(y); + return numext::bit_cast<Bits>(numext::abs(numext::real(x) - numext::real(y))) <= numext::bit_cast<Bits>(bound) && + numext::bit_cast<Bits>(numext::abs(numext::imag(x) - numext::imag(y))) <= numext::bit_cast<Bits>(bound); + }; + VERIFY(close(fastmath_scalar_sign(Scalar(highest, highest)), Scalar(sqrt_half, sqrt_half))); + VERIFY(close(fastmath_scalar_sign(Scalar(-highest, highest)), Scalar(-sqrt_half, sqrt_half))); + VERIFY(close(fastmath_scalar_sign(Scalar(h, -h)), Scalar(sqrt_half, -sqrt_half))); + VERIFY(close(fastmath_scalar_sign(Scalar(RealScalar(0.6) * highest, unit)), Scalar(RealScalar(1), RealScalar(0)))); +} + EIGEN_DECLARE_TEST(fastmath) { + CALL_SUBTEST_14(check_complex_sign_overflow<float>()); + CALL_SUBTEST_15(check_complex_sign_overflow<double>()); + std::cout << "*** float *** \n\n"; check_inf_nan<float>(true); std::cout << "*** double ***\n\n";
diff --git a/test/numext.cpp b/test/numext.cpp index 4c1c0e3..0e2a364 100644 --- a/test/numext.cpp +++ b/test/numext.cpp
@@ -929,12 +929,65 @@ VERIFY_IS_EQUAL(numext::sign(T(zero, r)), T(zero, one)); } - // Off the axes the magnitude is only as accurate as abs() itself, which cannot resolve |z| for a z - // whose components are at the bottom of the subnormal range; from the smallest normal upwards it can. - for (Real r : {(std::numeric_limits<Real>::min)(), one, (std::numeric_limits<Real>::max)() / Real(2)}) { - const T s = numext::sign(T(r, r)); - VERIFY_IS_APPROX(numext::abs(s), one); - VERIFY_IS_EQUAL(numext::real(s), numext::imag(s)); + // Off the axes, sign(z) = (x, y) / m / sqrt(1 + (min(|x|, |y|) / m)^2) for m = max(|x|, |y|), also where |z| + // overflows (z = (max, max)) or is subnormal, which abs() cannot resolve. + const Real eps = NumTraits<Real>::epsilon(); + const Real denorm_min = std::numeric_limits<Real>::denorm_min(); + const Real highest = (std::numeric_limits<Real>::max)(); + const Real sqrt_half = Real(0.70710678118654752440); + const Real two_over_sqrt5 = Real(0.89442719099991587856), one_over_sqrt5 = Real(0.44721359549995793928); + struct Case { + Real x, y, sign_x, sign_y; + }; + const Case cases[] = {{(std::numeric_limits<Real>::min)(), (std::numeric_limits<Real>::min)(), sqrt_half, sqrt_half}, + {one, one, sqrt_half, sqrt_half}, + {highest / Real(2), highest / Real(2), sqrt_half, sqrt_half}, + {highest, highest, sqrt_half, sqrt_half}, + {-highest, highest, -sqrt_half, sqrt_half}, + {highest, -highest / Real(2), two_over_sqrt5, -one_over_sqrt5}, + {denorm_min, denorm_min, sqrt_half, sqrt_half}, + {-denorm_min, denorm_min, -sqrt_half, sqrt_half}, + {Real(6) * denorm_min, Real(3) * denorm_min, two_over_sqrt5, one_over_sqrt5}, + {Real(2) * denorm_min, -Real(4) * denorm_min, one_over_sqrt5, -two_over_sqrt5}}; + const auto check = [&](const T& value, const Case& c) { + VERIFY(numext::abs(numext::real(value) - c.sign_x) <= Real(4) * eps); + VERIFY(numext::abs(numext::imag(value) - c.sign_y) <= Real(4) * eps); + }; + // Array::sign() takes the packet path in the body and the scalar path in the remainder. + Array<T, Dynamic, 1> z(19), s_array; + for (const Case& c : cases) { + check(numext::sign(T(c.x, c.y)), c); +#if EIGEN_ARCH_ARM // 32-bit ARM flushes subnormals in packet operations. + if (numext::abs(c.x) < (std::numeric_limits<Real>::min)()) continue; +#endif + z.setConstant(T(c.x, c.y)); + s_array = z.sign(); + check(s_array(0), c); + check(s_array(s_array.size() - 1), c); + } + + // Lane isolation: extreme, NaN and infinite elements next to ordinary ones, at every lane position, agree with the + // scalar function (NaN in either component gives NaN in both). + const Real nan = NumTraits<Real>::quiet_NaN(), inf = NumTraits<Real>::infinity(); + std::vector<T> lanes = {T(highest, highest), T(nan, highest), T(highest, nan), T(inf, one), T(3, 4), + T(-highest, one), T(one, -highest), T(zero, zero), T(-inf, -inf), T(one, 2)}; +#if !EIGEN_ARCH_ARM // 32-bit ARM flushes subnormals in packet operations. + lanes.push_back(T(denorm_min, denorm_min)); + lanes.push_back(T(nan, denorm_min)); + lanes.push_back(T(-denorm_min, nan)); + lanes.push_back(T(Real(6) * denorm_min, Real(3) * denorm_min)); +#endif + const auto same = [&](const Real& x, const Real& y) { + return ((numext::isnan)(x) && (numext::isnan)(y)) || x == y || numext::abs(x - y) <= Real(4) * eps; + }; + for (size_t shift = 0; shift < lanes.size(); ++shift) { + for (Index i = 0; i < z.size(); ++i) z(i) = lanes[(size_t(i) + shift) % lanes.size()]; + s_array = z.sign(); + for (Index i = 0; i < z.size(); ++i) { + const T expected = numext::sign(z(i)); + VERIFY(same(numext::real(s_array(i)), numext::real(expected))); + VERIFY(same(numext::imag(s_array(i)), numext::imag(expected))); + } } } @@ -994,6 +1047,23 @@ } } +// log1p(z) for |z| of at least 1, where 1 + z is accurate: the argument is atan2(y, 1 + x) to a few ulps, however large +// |x| is. W is wider than T. +template <typename T, typename W> +void check_complex_log1p_large() { + const T eps = NumTraits<T>::epsilon(); + const T big = (std::numeric_limits<T>::max)() / T(4); + for (const T x : {T(3), -T(5), T(1e3), -T(1e5), T(1e10), -T(1e10), T(1e20), big, -big}) { + for (const T y : {T(1), -T(0.25), T(1e-3) * x, T(1e-10) * x, big / T(2)}) { + const std::complex<T> got = numext::log1p(std::complex<T>(x, y)); + const W ref_re = std::log(std::hypot(W(1) + W(x), W(y))); + const W ref_im = std::atan2(W(y), W(1) + W(x)); + VERIFY(numext::abs(W(got.imag()) - ref_im) <= W(4) * W(eps) * numext::abs(ref_im)); + VERIFY(numext::abs(W(got.real()) - ref_re) <= W(4) * W(eps) * numext::abs(ref_re)); + } + } +} + // C99 Annex G: a nonzero finite numerator over a zero divisor gives an infinity, and a finite one over an infinite // divisor gives zero, also where the divisor's parts have equal magnitudes. scalar_quotient_op is the coefficient-wise // quotient's scalar path. @@ -1016,6 +1086,101 @@ } } +// Quotients that are representable although Smith's numerator a_r + a_i d / c or denominator c + d^2 / c is not: the +// operands lie above max / 2 or the divisor's parts are. Both the scalar and the packet (Array) path must give them. +template <typename T> +void check_complex_divide_extreme() { + using Complex = std::complex<T>; + const T zero(0), half(0.5), one(1); + const T highest = (std::numeric_limits<T>::max)(); + const T h = T(0.75) * highest, big = T(0.9) * highest, lowest = (std::numeric_limits<T>::min)(); + struct Case { + Complex a, b, quotient; + }; + const Case cases[] = {{Complex(h, h), Complex(h, h), Complex(one, zero)}, + {Complex(h, -h), Complex(h, h), Complex(zero, -one)}, + {Complex(-h, h), Complex(h, -h), Complex(-one, zero)}, + {Complex(h, zero), Complex(h, h), Complex(half, -half)}, + {Complex(-h, zero), Complex(h, h), Complex(-half, half)}, + {Complex(zero, h), Complex(-h, h), Complex(half, -half)}, + {Complex(highest, highest), Complex(T(2), T(2)), Complex(highest / T(2), zero)}, + {Complex(highest, -highest), Complex(T(2), T(2)), Complex(zero, -highest / T(2))}, + {Complex(big, zero), Complex(big, zero), Complex(one, zero)}, + {Complex(zero, big), Complex(zero, -big), Complex(-one, zero)}, + {Complex(lowest, lowest), Complex(T(2) * lowest, T(2) * lowest), Complex(half, zero)}, + {Complex(lowest, zero), Complex(zero, -T(2) * lowest), Complex(zero, half)}}; + const T tol = T(8) * NumTraits<T>::epsilon(); + Array<Complex, Dynamic, 1> a(19), b(19), q; + for (const Case& c : cases) { + a.setConstant(c.a); + b.setConstant(c.b); + q = a / b; + for (const Complex& value : {numext::divide(c.a, c.b), internal::scalar_quotient_op<Complex, Complex>()(c.a, c.b), + q(0), q(q.size() - 1)}) { + VERIFY(numext::abs(value.real() - c.quotient.real()) <= tol * numext::abs(c.quotient)); + VERIFY(numext::abs(value.imag() - c.quotient.imag()) <= tol * numext::abs(c.quotient)); + } + } + // Random quotients of operands near the top of the range: a = q b with 0.25 <= |q| < 1 and the parts of b up to + // max / 2. + for (int i = 0; i < 50; ++i) { + const Complex b_big(internal::random<T>(T(-0.5), T(0.5)) * highest, internal::random<T>(T(-0.5), T(0.5)) * highest); + const Complex q_ref(internal::random<T>(T(-0.7), T(0.7)), internal::random<T>(T(-0.7), T(0.7))); + if (numext::abs(b_big) < T(0.2) * highest || numext::abs(q_ref) < T(0.25)) continue; + const Complex a_big = q_ref * b_big; + a.setConstant(a_big); + b.setConstant(b_big); + q = a / b; + for (const Complex& value : {numext::divide(a_big, b_big), q(0), q(q.size() - 1)}) { + VERIFY(numext::abs(value - q_ref) <= tol * numext::abs(q_ref)); + } + } +} + +// The unscaled quotient is right where no numerator overflows. |a_r| + |a_i| = highest + ulp / 2 at a tie does overflow +// the sum a_r + a_i of Smith's numerator for b = 1 + i, but the quotient does not: it rounds to 2^(emax - 1). A +// subnormal component beside a large one survives division by one. Those two are the regression checks; the assertions +// on the zero signs of a division by an infinity pin the existing behavior and do not guard the rework. +template <typename T> +void check_complex_divide_ties_and_zero_signs() { + using Complex = std::complex<T>; + const T zero(0), one(1); + const T highest = (std::numeric_limits<T>::max)(); + const T denorm_min = std::numeric_limits<T>::denorm_min(); + const T inf = std::numeric_limits<T>::infinity(); + const int ulp_exponent = NumTraits<T>::max_exponent() - NumTraits<T>::digits(); // ulp(highest) = 2^ulp_exponent + const T ulp = numext::ldexp(one, ulp_exponent); + const Complex tie(highest - ulp, T(1.5) * ulp); + const Complex one_plus_i(one, one); + const T tol = T(8) * NumTraits<T>::epsilon(); + const Complex expected(numext::ldexp(one, NumTraits<T>::max_exponent() - 1), + -numext::ldexp(one, NumTraits<T>::max_exponent() - 1)); + for (const Complex& q : + {numext::divide(tie, one_plus_i), internal::scalar_quotient_op<Complex, Complex>()(tie, one_plus_i)}) { + VERIFY(numext::abs(q - expected) <= tol * numext::abs(expected)); + } + const T tiny_cases[] = {denorm_min, -denorm_min}; +#if !EIGEN_ARCH_ARM // 32-bit ARM flushes subnormals. + for (const T tiny : tiny_cases) { + const Complex q = numext::divide(Complex(tiny, highest), Complex(one, zero)); + VERIFY_IS_EQUAL(q.real(), tiny); + VERIFY_IS_EQUAL(q.imag(), highest); + // Plain Smith's quotient by an infinite divisor: 0 with the sign of the numerator component. + for (const T large : {one, -one}) { + const Complex r = numext::divide(Complex(tiny, large), Complex(inf, zero)); + VERIFY_IS_EQUAL(r.real(), T(tiny / inf)); + VERIFY_IS_EQUAL((std::signbit)(r.real()), (std::signbit)(tiny)); + VERIFY_IS_EQUAL(r.imag(), zero); + VERIFY_IS_EQUAL((std::signbit)(r.imag()), (std::signbit)(large)); + } + } +#else + (void)tiny_cases; + (void)inf; + (void)denorm_min; +#endif +} + #if EIGEN_COMP_MSVC #pragma float_control(precise, on, push) #pragma fenv_access(on) @@ -1054,6 +1219,52 @@ const int exceptions = complex_divide_exceptions(Complex(T(1), T(0)), b); if (exceptions >= 0) VERIFY_IS_EQUAL(exceptions, 0); } + + // The test for an overflowed numerator or denominator raises nothing where no term overflows, although their sum + // does (the terms are at most 2 max|a| and 2 max|b|), and nothing for an infinite or NaN operand whose quotient + // is infinite or NaN without an invalid operation. + const T highest = (std::numeric_limits<T>::max)(), infinity = NumTraits<T>::infinity(); + const T nan = NumTraits<T>::quiet_NaN(), one(1); + const Complex cases[][2] = {{Complex(highest / 4, zero), Complex(highest, zero)}, + {Complex(T(0.6) * highest, T(0.6) * highest), Complex(one, zero)}, + {Complex(highest, highest), Complex(one, zero)}, + {Complex(highest, zero), Complex(highest, zero)}, + {Complex(highest / 2, highest / 2), Complex(-one, zero)}, + {Complex(T(0.6) * highest, zero), Complex(zero, T(0.6) * highest)}, + {Complex(infinity, one), Complex(one, one)}, + {Complex(nan, one), Complex(one, one)}, + {Complex(one, one), Complex(infinity, one)}}; + for (const auto& operands : cases) { + const int exceptions = complex_divide_exceptions(operands[0], operands[1]); + if (exceptions >= 0) VERIFY_IS_EQUAL(exceptions, 0); + } +} + +// The exceptions numext::sign(z) raises, or -1 where the environment cannot be held. +template <typename T> +EIGEN_DONT_INLINE int complex_sign_exceptions(const std::complex<T>& z) { + const T operands[2] = {z.real(), z.imag()}; + T result[2]; + return fp_exceptions_raised_by_staged<2, 2>(FE_OVERFLOW | FE_UNDERFLOW | FE_INVALID | FE_DIVBYZERO, operands, result, + [](const T* in, T* out) { + const std::complex<T> s = numext::sign(std::complex<T>(in[0], in[1])); + out[0] = s.real(); + out[1] = s.imag(); + }); +} + +// |z| is not formed where it overflows (z = (max, max), whose sign is finite), and a NaN component raises nothing +// (the rescaling for m = 0 would divide 0 by 0). +template <typename T> +void check_complex_sign_exceptions() { + using Complex = std::complex<T>; + const T highest = (std::numeric_limits<T>::max)(), nan = NumTraits<T>::quiet_NaN(), zero(0), one(1); + for (const Complex z : {Complex(highest, highest), Complex(-highest, highest), Complex(highest, zero), + Complex(T(0.6) * highest, T(0.6) * highest), Complex(one, one), Complex(zero, nan), + Complex(nan, zero), Complex(nan, nan), Complex(one, nan), Complex(zero, zero)}) { + const int exceptions = complex_sign_exceptions(z); + if (exceptions >= 0) VERIFY_IS_EQUAL(exceptions, 0); + } } // numext::fma(a, b, c) for half or bfloat16, and whether it raised FE_INVALID (-1 where the environment cannot be @@ -1910,8 +2121,14 @@ CALL_SUBTEST_1(check_complex_divide<float>()); CALL_SUBTEST_1(check_complex_divide<double>()); + CALL_SUBTEST_1(check_complex_divide_extreme<float>()); + CALL_SUBTEST_1(check_complex_divide_extreme<double>()); + CALL_SUBTEST_1(check_complex_divide_ties_and_zero_signs<float>()); + CALL_SUBTEST_1(check_complex_divide_ties_and_zero_signs<double>()); CALL_SUBTEST_1(check_complex_divide_exceptions<float>()); CALL_SUBTEST_1(check_complex_divide_exceptions<double>()); + CALL_SUBTEST_1(check_complex_sign_exceptions<float>()); + CALL_SUBTEST_1(check_complex_sign_exceptions<double>()); CALL_SUBTEST_1(check_narrow_fma_nonfinite<half>()); CALL_SUBTEST_1(check_narrow_fma_nonfinite<bfloat16>()); @@ -1919,8 +2136,10 @@ CALL_SUBTEST_1(check_complex_fuzzy<double>()); CALL_SUBTEST_1((check_complex_log1p_accuracy<float, double>())); + CALL_SUBTEST_1((check_complex_log1p_large<float, double>())); if (std::numeric_limits<long double>::digits > std::numeric_limits<double>::digits) { CALL_SUBTEST_1((check_complex_log1p_accuracy<double, long double>())); + CALL_SUBTEST_1((check_complex_log1p_large<double, long double>())); } CALL_SUBTEST_1(check_complex_digits<float>());
diff --git a/test/stable_norm.cpp b/test/stable_norm.cpp index 0369162..1acd003 100644 --- a/test/stable_norm.cpp +++ b/test/stable_norm.cpp
@@ -860,6 +860,143 @@ } } +// For integer scalars every norm is the l2 (lp) norm truncated to the integer type, as norm() is, and 0 for empty +// inputs. The scaling in stableNorm() and blueNorm() and the real hypot in hypotNorm() are meaningless for integers; +// those three also return the norm where norm() overflows in squaring. +template <typename Scalar> +void integer_norms() { + using Vec = Matrix<Scalar, Dynamic, 1>; + using Mat = Matrix<Scalar, Dynamic, Dynamic>; + const auto check_l2 = [](const auto& m, Scalar expected) { + VERIFY_IS_EQUAL(m.norm(), expected); + VERIFY_IS_EQUAL(m.stableNorm(), expected); + VERIFY_IS_EQUAL(m.blueNorm(), expected); + VERIFY_IS_EQUAL(m.hypotNorm(), expected); + VERIFY_IS_EQUAL(m.template lpNorm<2>(), expected); + }; + Vec v(2); + v << 3, 4; + check_l2(v, 5); + v << -3, 4; + check_l2(v, 5); + v << 1, 1; + check_l2(v, 1); // truncated sqrt(2) + Vec w(3); + w << 1, 2, 2; + check_l2(w, 3); + check_l2(Vec(Vec::Constant(1, Scalar(-7))), 7); + check_l2((Matrix<Scalar, 2, 2>() << 1, 2, 2, 4).finished(), 5); + check_l2(Vec(Vec::Zero(5)), 0); + + VERIFY_IS_EQUAL(w.template lpNorm<1>(), 5); + VERIFY_IS_EQUAL(w.template lpNorm<Infinity>(), 2); + VERIFY_IS_EQUAL(w.template lpNorm<3>(), 2); // cbrt(17) = 2.57 + VERIFY_IS_EQUAL(w.template lpNorm<4>(), 2); // 33^(1/4) = 2.40 + Vec u(2); + u << 3, 0; + VERIFY_IS_EQUAL(u.template lpNorm<3>(), 3); // pow(27, 1/3.) is 3 + u << 4, 0; + VERIFY_IS_EQUAL(u.template lpNorm<3>(), 4); // pow(64, 1/3.) is 3.9999999999999996 + u << -4, 3; + VERIFY_IS_EQUAL(u.template lpNorm<3>(), 4); // cbrt(91) = 4.50 + VERIFY_IS_EQUAL(u.template lpNorm<5>(), 4); // 1267^(1/5) = 4.17 + VERIFY_IS_EQUAL(u.array().template lpNorm<3>(), 4); + + // The root is exact beyond the 53 bits of double. For r = 2^18 + 1, a sum of cubes r^3 - 1 has floor(cbrt) = r - 1. + if (sizeof(Scalar) >= 8) { + // In int64_t, so that the branch compiles without overflow for the narrower integer scalars too. + const int64_t r = 262145; + int64_t remainder = r * r * r - 1; + std::vector<Scalar> parts; + while (remainder > 0) { + int64_t c = int64_t(std::cbrt(double(remainder))); + while ((c + 1) * (c + 1) * (c + 1) <= remainder) ++c; + while (c * c * c > remainder) --c; + parts.push_back(Scalar(c)); + remainder -= c * c * c; + } + Vec cubes(Index(parts.size())); + for (Index i = 0; i < cubes.size(); ++i) cubes(i) = parts[size_t(i)]; + VERIFY_IS_EQUAL(cubes.cwiseAbs2().cwiseProduct(cubes.cwiseAbs()).sum(), Scalar(r * r * r - 1)); + VERIFY_IS_EQUAL(cubes.template lpNorm<3>(), Scalar(r - 1)); + Vec at_root(1); + at_root << Scalar(r); // r^3 does not exceed the sum + VERIFY_IS_EQUAL(at_root.template lpNorm<3>(), Scalar(r)); + } + + // The squares overflow the integer type, but the norm is representable: the l2 family accumulates in double, and + // norm() (which squares in Scalar) is not compared. For (3a, 4a) the sum 25 a^2 is below 2^53 for int16_t and int, + // and the double sum is exact for int64_t, so that the result is exactly 5a. + { + const int64_t a = sizeof(Scalar) == 2 ? 5000 : (sizeof(Scalar) == 4 ? 10000000 : 2000000000); + const auto check_l2_family = [](const auto& m, Scalar expected) { + VERIFY_IS_EQUAL(m.stableNorm(), expected); + VERIFY_IS_EQUAL(m.blueNorm(), expected); + VERIFY_IS_EQUAL(m.hypotNorm(), expected); + }; + Vec big(2); + big << Scalar(3 * a), Scalar(-4 * a); + check_l2_family(big, Scalar(5 * a)); + VERIFY_IS_EQUAL((big.array() * Scalar(1)).matrix().stableNorm(), Scalar(5 * a)); + // A norm above the highest value saturates. + const Scalar highest = NumTraits<Scalar>::highest(), lowest = NumTraits<Scalar>::lowest(); + Vec huge(2); + huge << highest, highest; + check_l2_family(huge, highest); + // One coefficient is its absolute value, without a square. + for (const Scalar x : + {Scalar(a), Scalar(-a), Scalar(sizeof(Scalar) == 2 ? 200 : 50000), highest, Scalar(lowest + 1)}) { + const Scalar expected = x < 0 ? Scalar(-x) : x; + const Matrix<Scalar, 1, 1> single = Matrix<Scalar, 1, 1>::Constant(x); + const Vec single_dynamic = Vec::Constant(1, x); + check_l2_family(single, expected); + VERIFY_IS_EQUAL(single_dynamic.stableNorm(), expected); + VERIFY_IS_EQUAL(single_dynamic.hypotNorm(), expected); + } + VERIFY_IS_EQUAL(Vec::Constant(1, lowest).stableNorm(), highest); // |lowest| is not representable + if (sizeof(Scalar) == 8) { + const Scalar beyond_double = Scalar((int64_t(1) << 60) + 1); // not representable in double + VERIFY_IS_EQUAL(Vec::Constant(1, beyond_double).stableNorm(), beyond_double); + VERIFY_IS_EQUAL(Vec::Constant(1, Scalar(-beyond_double)).hypotNorm(), beyond_double); + } + // The truncation is exact where sqrt(n^2 - 1) rounds up to n in double: (n - 1)^2 + (2 k)^2 = n^2 - 1 for + // n = 2 k^2 + 1, with n^2 below 2^53 for k = 6000. + if (sizeof(Scalar) >= 4) { + const int64_t k = 6000, n = 2 * k * k + 1; + Vec edge(2); + edge << Scalar(n - 1), Scalar(-2 * k); + check_l2_family(edge, Scalar(n - 1)); + } + } + + // A p outside the documented domain terminates. + { + const Vec twos = Vec::Constant(5, Scalar(2)); + VERIFY(twos.template lpNorm<0>() == twos.template lpNorm<0>()); + VERIFY(twos.template lpNorm<-2>() == twos.template lpNorm<-2>()); + } + + // Empty inputs: 0 for every p. + for (const Index rows : {Index(0), Index(3)}) { + const Mat empty = Mat::Zero(rows, rows == 0 ? 3 : 0); + check_l2(empty, 0); + VERIFY_IS_EQUAL(empty.template lpNorm<1>(), 0); + VERIFY_IS_EQUAL(empty.template lpNorm<3>(), 0); + VERIFY_IS_EQUAL(empty.template lpNorm<4>(), 0); + VERIFY_IS_EQUAL(empty.template lpNorm<Infinity>(), 0); + } + VERIFY_IS_EQUAL(Vec().stableNorm(), 0); + VERIFY_IS_EQUAL((Matrix<Scalar, 0, 1>().template lpNorm<3>()), 0); + VERIFY_IS_EQUAL((Matrix<Scalar, 0, 1>().blueNorm()), 0); + + // Random vectors, as long as the squared norm fits: the norm family agrees with norm(). + const Scalar bound = std::is_same<Scalar, int16_t>::value ? 5 : 100; + Vec r = Vec::Random(internal::random<int>(1, 30)).unaryExpr([&](Scalar x) { return Scalar(x % bound); }).eval(); + VERIFY_IS_EQUAL(r.stableNorm(), r.norm()); + VERIFY_IS_EQUAL(r.blueNorm(), r.norm()); + VERIFY_IS_EQUAL(r.hypotNorm(), r.norm()); +} + EIGEN_DECLARE_TEST(stable_norm) { CALL_SUBTEST_1(test_empty<>()); CALL_SUBTEST_1(stable_normalization_empty_reductions<float>()); @@ -918,4 +1055,7 @@ CALL_SUBTEST_13(stable_norm_expression_and_stride<>()); CALL_SUBTEST_13(stable_normalize_no_malloc<>()); CALL_SUBTEST_13(stable_normalize_custom_scalar<>()); + CALL_SUBTEST_13(integer_norms<int>()); + CALL_SUBTEST_13(integer_norms<int64_t>()); + CALL_SUBTEST_13(integer_norms<int16_t>()); }