Cholesky: Add LLT::inverse() via the LAPACK POTRI sequence libeigen/eigen!2977 Co-authored-by: Rasmus Munk Larsen <rmlarsen@gmail.com>
diff --git a/Eigen/Core b/Eigen/Core index 5468550..4ed3277 100644 --- a/Eigen/Core +++ b/Eigen/Core
@@ -436,6 +436,7 @@ #include "src/Core/products/TriangularMatrixMatrix.h" #include "src/Core/products/TriangularSolverMatrix.h" #include "src/Core/products/TriangularSolverVector.h" +#include "src/Core/TriangularInPlace.h" #include "src/Core/BandMatrix.h" #include "src/Core/CoreIterators.h" #include "src/Core/ConditionEstimator.h"
diff --git a/Eigen/src/Cholesky/LLT.h b/Eigen/src/Cholesky/LLT.h index 5f3d186..65545b3 100644 --- a/Eigen/src/Cholesky/LLT.h +++ b/Eigen/src/Cholesky/LLT.h
@@ -14,6 +14,19 @@ // IWYU pragma: private #include "./InternalHeaderCheck.h" +// Smallest n at which LLT::inverse() runs the POTRI sequence on a real scalar rather than solving +// against an explicit identity. POTRI's n^3/3 runs in the unblocked TRTRI and LAUUM kernels at small +// n, the solve's 3x at the blocked TRSM rate, so a wider ISA helps the competitor more and moves the +// crossover right: on Zen 4 it is n = 32 under SSE2 and AVX2, 128 (double) to 256 (float) under +// AVX-512. Complex is not thresholded: POTRI leads from n = 8 in all twelve configurations measured. +#ifndef EIGEN_LLT_INVERSE_POTRI_THRESHOLD +#if defined(EIGEN_VECTORIZE_AVX512) +#define EIGEN_LLT_INVERSE_POTRI_THRESHOLD 256 +#else +#define EIGEN_LLT_INVERSE_POTRI_THRESHOLD 32 +#endif +#endif + namespace Eigen { namespace internal { @@ -81,6 +94,7 @@ enum { PacketSize = internal::packet_traits<Scalar>::size, AlignmentMask = int(PacketSize) - 1, UpLo = UpLo_ }; using Traits = internal::LLT_Traits<MatrixType, UpLo>; + using PlainObject = typename MatrixType::PlainObject; /** * \brief Default Constructor. @@ -168,6 +182,32 @@ return m_matrix; } + /** \returns the inverse of the matrix of which \c *this is the Cholesky decomposition. + * + * The result is computed as \f$ A^{-1} = L^{-*} L^{-1} \f$ by inverting the stored factor in place and + * squaring it, the LAPACK \c *POTRI sequence, for 2n^3/3 flops against the 2n^3 of solving with an + * explicit identity right hand side. Beyond the destination, only a block-sized scratch panel of at most + * 128x128 coefficients is used, whatever the matrix size. + * + * Fewer flops is not fewer seconds at every size: for a real scalar below + * \c EIGEN_LLT_INVERSE_POTRI_THRESHOLD (32, or 256 where AVX-512 is enabled) the POTRI sequence runs in + * its unblocked kernels while the solve against an identity runs its 3x at the blocked TRSM rate, so that + * is what this method does there. Complex scalars always take the POTRI path. The result is exactly + * self-adjoint either way: one triangle is computed and mirrored onto the other. + * + * An in-place decomposition (see the class documentation) may overwrite its own factor with the result, + * as in <tt>storage = llt.inverse()</tt>; like any other write to the referenced matrix, that leaves the + * decomposition unusable afterwards. + * + * The matrix must be positive definite, that is, info() must be \c Success. + * + * \sa solve(), MatrixBase::inverse() + */ + inline Inverse<LLT> inverse() const { + eigen_assert(m_isInitialized && "LLT is not initialized."); + return Inverse<LLT>(*this); + } + MatrixType reconstructedMatrix() const; /** \brief Reports whether previous computation was successful. @@ -560,6 +600,50 @@ matrixU().solveInPlace(bAndX); } +namespace internal { + +/***** Implementation of inverse() *****************************************************/ +template <typename DstXprType, typename MatrixType, int UpLo_> +struct Assignment<DstXprType, Inverse<LLT<MatrixType, UpLo_> >, + internal::assign_op<typename DstXprType::Scalar, typename LLT<MatrixType, UpLo_>::Scalar>, + Dense2Dense> { + using LltType = LLT<MatrixType, UpLo_>; + using SrcXprType = Inverse<LltType>; + static constexpr unsigned int kMirrorMode = UpLo_ == Lower ? StrictlyUpper : StrictlyLower; + static void run(DstXprType& dst, const SrcXprType& src, + const internal::assign_op<typename DstXprType::Scalar, typename LltType::Scalar>&) { + const LltType& llt = src.nestedExpression(); + eigen_assert(llt.info() == Success && "LLT::inverse(): the factorization failed."); + const Index size = llt.rows(); + if ((dst.rows() != size) || (dst.cols() != size)) dst.resize(size, size); + + // Complex is never thresholded; see EIGEN_LLT_INVERSE_POTRI_THRESHOLD. + constexpr Index kPotriThreshold = + NumTraits<typename LltType::Scalar>::IsComplex ? Index(0) : Index(EIGEN_LLT_INVERSE_POTRI_THRESHOLD); + // An in-place LLT<Ref<...>> may be asked to overwrite its own factor. The POTRI sequence does exactly + // that, so it takes the alias at every size; the solve fallback would read a factor that setIdentity() + // had already destroyed. extract_data() is null for a destination whose inner stride is not known to + // be 1 at compile time, which leaves the alias unknown rather than excluded, so that goes the same way. + const typename DstXprType::Scalar* dst_data = extract_data(dst); + const bool overwrites_factor = dst_data == nullptr || dst_data == llt.matrixLLT().data(); + if (overwrites_factor || size >= kPotriThreshold) { + // A = L L^*, hence A^-1 = L^-* L^-1: invert the factor (xTRTRI), then square it (xLAUUM). + dst.template triangularView<UpLo_>() = llt.matrixLLT().template triangularView<UpLo_>(); + dst.template triangularView<UpLo_>().inverseInPlace(); + internal::triangular_adjoint_square_in_place<UpLo_>(dst); + } else { + dst.setIdentity(); + llt.solveInPlace(dst); + } + // Mirror; (i, j) reads (j, i), which lies in the computed triangle and is never written here, so + // the aliasing is benign. The computed diagonal is exactly real (a squaredNorm above the + // threshold, a real scalar below it), so the result is exactly self-adjoint. + dst.template triangularView<kMirrorMode>() = dst.adjoint(); + } +}; + +} // end namespace internal + /** \returns the matrix represented by the decomposition, * i.e., it returns the product: L L^*. * This function is provided for debug purpose. */
diff --git a/Eigen/src/Core/TriangularInPlace.h b/Eigen/src/Core/TriangularInPlace.h new file mode 100644 index 0000000..09e1c3c --- /dev/null +++ b/Eigen/src/Core/TriangularInPlace.h
@@ -0,0 +1,220 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2026 Rasmus Munk Larsen <rmlarsen@gmail.com> +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 + +#ifndef EIGEN_TRIANGULARINPLACE_H +#define EIGEN_TRIANGULARINPLACE_H + +// IWYU pragma: private +#include "./InternalHeaderCheck.h" + +namespace Eigen { + +namespace internal { + +// In-place counterparts of LAPACK xTRTRI and xLAUUM. Each overwrites its operand; the only scratch is +// one block-sized panel, at most 128x128 elements whatever the matrix size, through which the in-place +// TRMM steps run Eigen's blocked kernel, the same way optimized BLAS implement xTRMM. + +// Only the lower forms exist. An upper U runs the lower kernel on Transpose<MatrixType>: with +// V = U^T, V^-1 = (U^-1)^T and V^* V = conj(U U^*) = (U U^*)^T since U U^* is self-adjoint, so the +// lower triangle of the transposed view is the upper triangle of the original in both cases. + +// Both kernels have the panel-times-trailing-block shape of the Cholesky factorization, so the block +// size tracks llt_inplace::blocked(), but each has its own floor and its own size below which the +// unblocked form still wins: TRTRI's blocked step is a TRMM plus a TRSM against a bs-wide panel, and +// its unblocked form is already a sequence of TRMVs, while LAUUM's is a TRMM plus a HERK and its +// unblocked form is a sequence of GEMVs against a strided row. Measured on Zen 4 at n = 32..512. +constexpr Index kTriangularInverseMinBlocked = 64; +constexpr Index kTriangularInverseMinBlockSize = 24; +constexpr Index kAdjointSquareMinBlocked = 128; +constexpr Index kAdjointSquareMinBlockSize = 48; + +EIGEN_DEVICE_FUNC inline Index triangular_in_place_block_size(Index size, Index min_block_size) { + const Index block_size = ((size / 8) / 8) * 8; + return numext::mini(numext::maxi(block_size, min_block_size), Index(128)); +} + +template <typename MatrixType> +using triangular_in_place_workspace = Matrix<typename MatrixType::Scalar, Dynamic, Dynamic, + (int(traits<MatrixType>::Flags) & RowMajorBit) ? RowMajor : ColMajor>; + +// Unblocked lower triangular inverse, columns bottom-up so that the trailing block already holds +// X22 = L22^-1 when column j is reached: then X(j+1:, j) = -X22 L(j+1:, j) / L(j, j), one TRMV per +// column rather than the chain of AXPYs a forward substitution per column would run. \a tmp is +// scratch of at least n - 1 entries, since the TRMV's destination is its own operand. +template <unsigned int Mode, typename MatrixType, typename VectorType> +EIGEN_DEVICE_FUNC void triangular_inverse_unblocked(MatrixType& mat, VectorType& tmp) { + using Scalar = typename MatrixType::Scalar; + constexpr bool kUnitDiag = (Mode & UnitDiag) != 0; + const Index n = mat.rows(); + eigen_internal_assert(n < 2 || tmp.size() >= n - 1); + for (Index j = n - 1; j >= 0; --j) { + Scalar xj = Scalar(1); + EIGEN_IF_CONSTEXPR (!kUnitDiag) { + xj = Scalar(1) / mat.coeff(j, j); + mat.coeffRef(j, j) = xj; + } + const Index rs = n - j - 1; + if (rs == 0) continue; + tmp.head(rs).noalias() = mat.block(j + 1, j + 1, rs, rs).template triangularView<Mode>() * mat.col(j).tail(rs); + mat.col(j).tail(rs) = -xj * tmp.head(rs); + } +} + +// Blocked lower triangular inverse, block columns bottom-up as in LAPACK xTRTRI. With +// L = [[L11, 0], [L21, L22]] the inverse is [[L11^-1, 0], [-L22^-1 L21 L11^-1, L22^-1]]; walking upwards +// makes X22 = L22^-1 available first, so the large operation is the TRMM X22 L21 rather than a solve +// against L22, and Eigen's TRMM runs closer to GEMM rate than its TRSM does on a 128-column operand. +template <unsigned int Mode, typename MatrixType> +EIGEN_DEVICE_FUNC void triangular_inverse_lower(MatrixType& mat) { + eigen_assert(mat.rows() == mat.cols()); + const Index n = mat.rows(); + if (n < kTriangularInverseMinBlocked) { + using Scalar = typename MatrixType::Scalar; + ei_declare_aligned_stack_constructed_variable(Scalar, tmp_data, numext::maxi(n, Index(1)), 0); + Map<Matrix<Scalar, Dynamic, 1> > tmp(tmp_data, n); + triangular_inverse_unblocked<Mode>(mat, tmp); + return; + } + const Index block_size = triangular_in_place_block_size(n, kTriangularInverseMinBlockSize); + // One block-sized panel, whose first column doubles as the TRMV scratch of the unblocked kernel: + // that kernel runs on L11 only after the panel's other uses in the same iteration are finished. + triangular_in_place_workspace<MatrixType> work(block_size, block_size); + for (Index k = ((n - 1) / block_size) * block_size; k >= 0; k -= block_size) { + const Index bs = numext::mini(block_size, n - k); + const Index rs = n - k - bs; + Block<MatrixType, Dynamic, Dynamic> L11(mat, k, k, bs, bs); + if (rs > 0) { + Block<MatrixType, Dynamic, Dynamic> L21(mat, k + bs, k, rs, bs); + Block<MatrixType, Dynamic, Dynamic> X22(mat, k + bs, k + bs, rs, rs); + // L21 <- X22 L21. Row panel r of the product reads only rows <= r of L21, so going upwards + // leaves every row a later panel still needs untouched. + for (Index r_end = rs; r_end > 0; r_end -= block_size) { + const Index r = numext::maxi(Index(0), r_end - block_size); + const Index h = r_end - r; + work.topLeftCorner(h, bs) = L21.middleRows(r, h); + L21.middleRows(r, h).noalias() = + X22.block(r, r, h, h).template triangularView<Mode>() * work.topLeftCorner(h, bs); + if (r > 0) L21.middleRows(r, h).noalias() += X22.block(r, 0, h, r) * L21.topRows(r); + } + L11.template triangularView<Mode>().template solveInPlace<OnTheRight>(L21); + L21 = -L21; + } + auto tmp = work.col(0); + triangular_inverse_unblocked<Mode>(L11, tmp); + } +} + +template <unsigned int Mode, bool IsLower = (int(Mode) & int(Lower)) != 0> +struct triangular_inverse_selector { + template <typename MatrixType> + EIGEN_DEVICE_FUNC static void run(MatrixType& mat) { + triangular_inverse_lower<Mode>(mat); + } +}; + +template <unsigned int Mode> +struct triangular_inverse_selector<Mode, false> { + template <typename MatrixType> + EIGEN_DEVICE_FUNC static void run(MatrixType& mat) { + Transpose<MatrixType> matt(mat); + triangular_inverse_lower<(int(Mode) & int(UnitDiag)) | int(Lower)>(matt); + } +}; + +// Unblocked lower self-adjoint square: mat <- lower(L^* L). Row i of the result reads column i of L +// below the diagonal and rows > i of the columns left of it, none of which row i's own update writes. +template <typename MatrixType> +void triangular_adjoint_square_unblocked(MatrixType& mat) { + using Scalar = typename MatrixType::Scalar; + const Index n = mat.rows(); + for (Index i = 0; i < n; ++i) { + const Scalar lii = mat.coeff(i, i); + const Index rs = n - i - 1; + mat.coeffRef(i, i) = Scalar(mat.col(i).tail(n - i).squaredNorm()); + if (i > 0) { + mat.row(i).head(i) *= numext::conj(lii); + if (rs > 0) mat.row(i).head(i).noalias() += mat.col(i).tail(rs).adjoint() * mat.bottomLeftCorner(rs, i); + } + } +} + +// Blocked lower self-adjoint square, left-looking as in LAPACK xLAUUM: block row k of the result is +// completed against the columns to its left before the trailing block rows consume the factor. +template <typename MatrixType> +void triangular_adjoint_square_lower(MatrixType& mat) { + eigen_assert(mat.rows() == mat.cols()); + const Index n = mat.rows(); + if (n < kAdjointSquareMinBlocked) { + triangular_adjoint_square_unblocked(mat); + return; + } + const Index block_size = triangular_in_place_block_size(n, kAdjointSquareMinBlockSize); + triangular_in_place_workspace<MatrixType> work(block_size, block_size); + for (Index k = 0; k < n; k += block_size) { + const Index bs = numext::mini(block_size, n - k); + const Index rs = n - k - bs; + Block<MatrixType, Dynamic, Dynamic> L11(mat, k, k, bs, bs); + if (k > 0) { + // A(k:k+bs, 0:k) = sum over rows m >= k of L(m, k:k+bs)^* L(m, 0:k), split at m = k+bs. The + // first part is the TRMM L11^* B in place, done by column panels through the workspace. + Block<MatrixType, Dynamic, Dynamic> B(mat, k, 0, bs, k); + for (Index c = 0; c < k; c += block_size) { + const Index w = numext::mini(block_size, k - c); + work.topLeftCorner(bs, w) = B.middleCols(c, w); + B.middleCols(c, w).noalias() = L11.adjoint().template triangularView<Upper>() * work.topLeftCorner(bs, w); + } + if (rs > 0) B.noalias() += mat.block(k + bs, k, rs, bs).adjoint() * mat.block(k + bs, 0, rs, k); + } + triangular_adjoint_square_unblocked(L11); + if (rs > 0) L11.template selfadjointView<Lower>().rankUpdate(mat.block(k + bs, k, rs, bs).adjoint()); + } +} + +template <int UpLo, bool IsLower = (int(UpLo) & int(Lower)) != 0> +struct triangular_adjoint_square_selector { + template <typename MatrixType> + static void run(MatrixType& mat) { + triangular_adjoint_square_lower(mat); + } +}; + +template <int UpLo> +struct triangular_adjoint_square_selector<UpLo, false> { + template <typename MatrixType> + static void run(MatrixType& mat) { + Transpose<MatrixType> matt(mat); + triangular_adjoint_square_lower(matt); + } +}; + +/** \internal Replaces the \a UpLo triangle of \a mat, holding a triangular factor T, by the same + * triangle of the self-adjoint product T^* T (\c Lower) or T T^* (\c Upper). The opposite triangle is + * neither read nor written. This is LAPACK's xLAUUM. */ +template <int UpLo, typename MatrixType> +void triangular_adjoint_square_in_place(MatrixType& mat) { + triangular_adjoint_square_selector<UpLo>::run(mat); +} + +} // end namespace internal + +#ifndef EIGEN_PARSED_BY_DOXYGEN +template <typename MatrixType, unsigned int Mode> +EIGEN_DEVICE_FUNC void TriangularViewImpl<MatrixType, Mode, Dense>::inverseInPlace() { + EIGEN_STATIC_ASSERT_LVALUE(MatrixType) + EIGEN_STATIC_ASSERT((int(Mode) & int(Upper | Lower)) != 0 && (int(Mode) & int(ZeroDiag)) == 0, PROGRAMMING_ERROR) + eigen_assert(derived().rows() == derived().cols()); + internal::triangular_inverse_selector<Mode>::run(derived().nestedExpression()); +} +#endif + +} // end namespace Eigen + +#endif // EIGEN_TRIANGULARINPLACE_H
diff --git a/Eigen/src/Core/TriangularMatrix.h b/Eigen/src/Core/TriangularMatrix.h index eeff6e2..adc75b0 100644 --- a/Eigen/src/Core/TriangularMatrix.h +++ b/Eigen/src/Core/TriangularMatrix.h
@@ -548,6 +548,20 @@ return solveInPlace<OnTheLeft>(other); } + /** Replaces the referenced triangular part by its inverse. + * + * \c *this must be square and invertible; as with solveInPlace(), no check is made and a zero on the + * diagonal yields a non-finite result. The opposite triangle is neither read nor written, and with a + * \c #UnitDiag mode the diagonal itself is left alone as well. + * + * This is the operation of the \c *TRTRI LAPACK routines. It costs n^3/3 flops, where solving against an + * explicit identity right hand side costs n^3, and its only scratch is one block-sized panel of at most + * 128x128 coefficients, independent of the matrix size. + * + * \sa TriangularView::solveInPlace(), MatrixBase::inverse() + */ + EIGEN_DEVICE_FUNC void inverseInPlace(); + /** Swaps the coefficients of the common triangular parts of two matrices */ template <typename OtherDerived> EIGEN_DEVICE_FUNC
diff --git a/benchmarks/Cholesky/CMakeLists.txt b/benchmarks/Cholesky/CMakeLists.txt index 83b1ecf..ec05343 100644 --- a/benchmarks/Cholesky/CMakeLists.txt +++ b/benchmarks/Cholesky/CMakeLists.txt
@@ -5,3 +5,7 @@ eigen_add_benchmark(bench_cholesky_double bench_cholesky.cpp DEFINITIONS SCALAR=double) eigen_add_benchmark(bench_bunchkaufman bench_bunchkaufman.cpp DEFINITIONS SCALAR=double) eigen_add_benchmark(bench_bunchkaufman_cplx bench_bunchkaufman.cpp DEFINITIONS "SCALAR=std::complex<double>") +eigen_add_benchmark(bench_llt_inverse bench_llt_inverse.cpp DEFINITIONS SCALAR=double) +eigen_add_benchmark(bench_llt_inverse_cplx bench_llt_inverse.cpp DEFINITIONS "SCALAR=std::complex<double>") +eigen_add_benchmark(bench_llt_inverse_float bench_llt_inverse.cpp DEFINITIONS SCALAR=float) +eigen_add_benchmark(bench_llt_inverse_cplxf bench_llt_inverse.cpp DEFINITIONS "SCALAR=std::complex<float>")
diff --git a/benchmarks/Cholesky/bench_llt_inverse.cpp b/benchmarks/Cholesky/bench_llt_inverse.cpp new file mode 100644 index 0000000..0dfbdb7 --- /dev/null +++ b/benchmarks/Cholesky/bench_llt_inverse.cpp
@@ -0,0 +1,110 @@ +// SPDX-FileCopyrightText: The Eigen Authors +// SPDX-License-Identifier: MPL-2.0 +// +// Micro-benchmark for inverting a symmetric positive definite matrix from its Cholesky factor. +// LLT::inverse() runs the LAPACK POTRI sequence (TRTRI then LAUUM) for 2n^3/3 flops, against the +// 2n^3 of the solve-with-an-explicit-identity form that was the only route before it existed. The +// GFLOPS counters report each routine's own operation count, so they measure utilization rather +// than the speedup; the speedup is the ratio of the wall times. + +#include <benchmark/benchmark.h> +#include <Eigen/Cholesky> +#include <Eigen/Core> + +using namespace Eigen; + +#ifndef SCALAR +#define SCALAR double +#endif + +using Scalar = SCALAR; +using MatrixType = Matrix<Scalar, Dynamic, Dynamic>; +using RealScalar = NumTraits<Scalar>::Real; + +// Flops counted as in bench_cholesky.cpp: multiply and add counted separately, complex arithmetic +// left at its real-arithmetic count so that the real and complex builds stay comparable. +static double potri_cost(int n) { return 2.0 / 3.0 * double(n) * n * n; } +static double solve_identity_cost(int n) { return 2.0 * double(n) * n * n; } +// TRTRI and LAUUM each cost n^3/3, the two halves of the POTRI sequence above. +static double potri_kernel_cost(int n) { return 1.0 / 3.0 * double(n) * n * n; } +static double trsm_identity_cost(int n) { return double(n) * n * n; } + +static MatrixType make_spd(int n) { + MatrixType a = MatrixType::Random(n, n); + return a * a.adjoint() + RealScalar(n) * MatrixType::Identity(n, n); +} + +static void set_rate(benchmark::State& state, double flops) { + state.counters["GFLOPS"] = + benchmark::Counter(flops, benchmark::Counter::kIsIterationInvariantRate, benchmark::Counter::kIs1000); +} + +static void BM_LLT_Inverse(benchmark::State& state) { + const int n = state.range(0); + const LLT<MatrixType> llt(make_spd(n)); + MatrixType inv(n, n); + for (auto _ : state) { + inv = llt.inverse(); + benchmark::DoNotOptimize(inv.data()); + benchmark::ClobberMemory(); + } + set_rate(state, potri_cost(n)); +} +BENCHMARK(BM_LLT_Inverse)->RangeMultiplier(2)->Range(8, 2048); + +static void BM_LLT_SolveIdentity(benchmark::State& state) { + const int n = state.range(0); + const LLT<MatrixType> llt(make_spd(n)); + MatrixType inv(n, n); + for (auto _ : state) { + inv = llt.solve(MatrixType::Identity(n, n)); + benchmark::DoNotOptimize(inv.data()); + benchmark::ClobberMemory(); + } + set_rate(state, solve_identity_cost(n)); +} +BENCHMARK(BM_LLT_SolveIdentity)->RangeMultiplier(2)->Range(8, 2048); + +// The two kernels LLT::inverse() is built from, and the pre-existing operation each replaces. Both +// pairs carry the same O(n^2) per-iteration setup, so the ratio within a pair is meaningful. +static void BM_TriangularInverseInPlace(benchmark::State& state) { + const int n = state.range(0); + const MatrixType factor = LLT<MatrixType>(make_spd(n)).matrixLLT(); + MatrixType x(n, n); + for (auto _ : state) { + x = factor; + x.triangularView<Lower>().inverseInPlace(); + benchmark::DoNotOptimize(x.data()); + benchmark::ClobberMemory(); + } + set_rate(state, potri_kernel_cost(n)); +} +BENCHMARK(BM_TriangularInverseInPlace)->RangeMultiplier(2)->Range(8, 2048); + +static void BM_TriangularSolveIdentity(benchmark::State& state) { + const int n = state.range(0); + const MatrixType factor = LLT<MatrixType>(make_spd(n)).matrixLLT(); + MatrixType x(n, n); + for (auto _ : state) { + x = MatrixType::Identity(n, n); + factor.triangularView<Lower>().solveInPlace(x); + benchmark::DoNotOptimize(x.data()); + benchmark::ClobberMemory(); + } + set_rate(state, trsm_identity_cost(n)); +} +BENCHMARK(BM_TriangularSolveIdentity)->RangeMultiplier(2)->Range(8, 2048); + +static void BM_TriangularAdjointSquare(benchmark::State& state) { + const int n = state.range(0); + const MatrixType factor = LLT<MatrixType>(make_spd(n)).matrixLLT(); + MatrixType x(n, n); + for (auto _ : state) { + x = factor; + internal::triangular_adjoint_square_in_place<Lower>(x); + benchmark::DoNotOptimize(x.data()); + benchmark::ClobberMemory(); + } + set_rate(state, potri_kernel_cost(n)); +} +BENCHMARK(BM_TriangularAdjointSquare)->RangeMultiplier(2)->Range(8, 2048);
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index d6c36b1..1c211af 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt
@@ -358,6 +358,7 @@ ei_add_test(ref) ei_add_test(is_same_dense) ei_add_test(triangular) +ei_add_test(triangular_in_place) ei_add_test(selfadjoint) ei_add_test(product_selfadjoint) ei_add_test(product_symm)
diff --git a/test/cholesky.cpp b/test/cholesky.cpp index 08fbb6c..856ffa5 100644 --- a/test/cholesky.cpp +++ b/test/cholesky.cpp
@@ -52,6 +52,94 @@ } } +// A^-1 from an LLT factorization. The kernels fill one triangle and mirror it, so the result is +// exactly self-adjoint, and accuracy is checked as the backward error of the corresponding solve. +template <typename MatrixType, int UpLo> +void check_llt_inverse(const MatrixType& symm) { + using Scalar = typename MatrixType::Scalar; + using RealScalar = typename NumTraits<Scalar>::Real; + using DynMatrixType = Matrix<Scalar, Dynamic, Dynamic>; + using DynVectorType = Matrix<Scalar, Dynamic, 1>; + const Index n = symm.rows(); + + const MatrixType tri = symm.template triangularView<UpLo>(); + LLT<MatrixType, UpLo> llt(tri); + VERIFY(llt.info() == Success); + + const MatrixType inv = llt.inverse(); + VERIFY_IS_EQUAL(inv.rows(), n); + VERIFY_IS_EQUAL(inv.cols(), n); + VERIFY_IS_CWISE_EQUAL(inv, inv.adjoint()); + + // |A X - I| <= c*n*eps*|A|*|X| for a Cholesky solve (Higham, Accuracy and Stability of Numerical + // Algorithms, 2nd ed., Thm 10.4). The factor 16 absorbs c and the entrywise-to-norm step; the + // largest ratio measured over this family is 2, at n = 1. + const RealScalar eps = NumTraits<RealScalar>::epsilon(); + const RealScalar residual_bound = RealScalar(16 * n) * eps * symm.norm() * inv.norm(); + VERIFY((numext::isfinite)(residual_bound)); + VERIFY((symm * inv - MatrixType::Identity(n, n)).norm() <= residual_bound); + + // The same answer as solving against an explicit identity, to within the forward error, which the + // residual bound multiplied by cond(A) <= |A|*|X| bounds in turn. + const MatrixType reference = llt.solve(MatrixType::Identity(n, n)); + const RealScalar forward_bound = residual_bound * inv.norm(); + VERIFY((numext::isfinite)(forward_bound)); + VERIFY((inv - reference).norm() <= forward_bound); + + // The destination need not be a plain object. + DynMatrixType host = DynMatrixType::Random(n + 2, n + 2); + host.bottomRightCorner(n, n) = llt.inverse(); + VERIFY((symm * host.bottomRightCorner(n, n) - MatrixType::Identity(n, n)).norm() <= residual_bound); + + // Nor need its inner stride be known at compile time. extract_data() is null for such a destination, + // which leaves the alias with the factor unknown rather than excluded, so this takes POTRI at every + // size, and the gaps between the mapped coefficients hold the kernels to the storage they were given. + using StrideType = Stride<Dynamic, Dynamic>; + const Index inner = 2, outer = 2 * n + 3; + const Index buffer_size = numext::maxi(Index(1), (n - 1) * (outer + inner) + 1); + DynVectorType buffer = DynVectorType::Random(buffer_size); + const DynVectorType before = buffer; + Map<MatrixType, 0, StrideType> strided(buffer.data(), n, n, StrideType(outer, inner)); + strided = llt.inverse(); + VERIFY_IS_CWISE_EQUAL(strided, strided.adjoint()); + VERIFY((symm * strided - MatrixType::Identity(n, n)).norm() <= residual_bound); + std::vector<bool> mapped(buffer_size, false); + for (Index j = 0; j < n; ++j) + for (Index i = 0; i < n; ++i) mapped[static_cast<std::size_t>(&strided.coeffRef(i, j) - buffer.data())] = true; + for (Index k = 0; k < buffer_size; ++k) + if (!mapped[k]) VERIFY_IS_EQUAL(buffer[k], before[k]); + + // An in-place decomposition may overwrite its own factor, whichever arm the size selects: the solve + // fallback would read the factor after setIdentity() had destroyed it, so the alias takes POTRI. + MatrixType storage = tri; + LLT<Ref<MatrixType>, UpLo> inplace(storage); + VERIFY(inplace.info() == Success); + storage = inplace.inverse(); + VERIFY_IS_CWISE_EQUAL(storage, storage.adjoint()); + VERIFY((symm * storage - MatrixType::Identity(n, n)).norm() <= residual_bound); +} + +// LLT::inverse() dispatches on EIGEN_LLT_INVERSE_POTRI_THRESHOLD, so straddle it deterministically: +// the random sizes above reach only whichever side of it EIGEN_TEST_MAX_SIZE happens to allow. Only +// real scalars are thresholded, so only they have a boundary to straddle. +template <typename Scalar> +void llt_inverse_threshold_boundary() { + static_assert(!NumTraits<Scalar>::IsComplex, "only real scalars are thresholded"); + using RealScalar = typename NumTraits<Scalar>::Real; + using MatrixType = Matrix<Scalar, Dynamic, Dynamic>; + + const Index threshold = EIGEN_LLT_INVERSE_POTRI_THRESHOLD; + const Index sizes[] = {threshold - 1, threshold, threshold + 1}; + for (Index n : sizes) { + MatrixType r = MatrixType::Random(n, n); + MatrixType symm = r * r.adjoint(); + symm.diagonal().array() += RealScalar(n); + + check_llt_inverse<MatrixType, Lower>(symm); + check_llt_inverse<MatrixType, Upper>(symm); + } +} + template <typename MatrixType> void cholesky(const MatrixType& m) { /* this test covers the following files: @@ -112,6 +200,9 @@ rcond_est = cholup.rcond(); VERIFY(rcond_est >= rcond / 10 && rcond_est <= rcond * 10); + check_llt_inverse<SquareMatrixType, Lower>(symm); + check_llt_inverse<SquareMatrixType, Upper>(symm); + MatrixType neg = -symmLo; chollo.compute(neg); VERIFY(neg.size() == 0 || chollo.info() == NumericalIssue); @@ -897,6 +988,8 @@ CALL_SUBTEST_6(cholesky_blocking_boundary<std::complex<double> >()); CALL_SUBTEST_2(cholesky_rowmajor_boundary<double>()); CALL_SUBTEST_8(cholesky_rowmajor_boundary<float>()); + CALL_SUBTEST_2(llt_inverse_threshold_boundary<double>()); + CALL_SUBTEST_8(llt_inverse_threshold_boundary<float>()); TEST_SET_BUT_UNUSED_VARIABLE(nb_temporaries); }
diff --git a/test/triangular_in_place.cpp b/test/triangular_in_place.cpp new file mode 100644 index 0000000..1b06ea5 --- /dev/null +++ b/test/triangular_in_place.cpp
@@ -0,0 +1,190 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2026 Rasmus Munk Larsen <rmlarsen@gmail.com> +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 + +#include "main.h" + +// Substitution is backward stable: the computed inverse X of a triangular T satisfies +// |T X - I| <= c*n*eps*|T|*|X| entrywise, for a small constant c (Higham, Accuracy and Stability of +// Numerical Algorithms, 2nd ed., Thm 8.5). The factors below absorb c and the entrywise-to-norm step; +// the largest ratio measured over the families tested here is 2, at n = 1. +static constexpr int kResidualFactor = 16; +// Forward error against the reference solve, bounded by the residual bound times cond(T) <= |T|*|X|. +static constexpr int kForwardFactor = 16; + +// The part of the storage that a triangularView<mode>() does not own, and that an in-place kernel must +// therefore leave bit for bit unchanged: the opposite triangle, plus the diagonal under UnitDiag. +constexpr unsigned int untouched_mode(unsigned int mode) { + return ((mode & Lower) != 0 ? unsigned(Upper) : unsigned(Lower)) | ((mode & UnitDiag) != 0 ? 0u : unsigned(ZeroDiag)); +} + +template <unsigned int Mode, typename MatrixType, typename OperandType> +void check_triangular_inverse(const MatrixType& t, OperandType& x, bool well_conditioned) { + using Scalar = typename MatrixType::Scalar; + using RealScalar = typename NumTraits<Scalar>::Real; + using DenseType = Matrix<Scalar, Dynamic, Dynamic>; + + const Index n = t.rows(); + const RealScalar eps = NumTraits<RealScalar>::epsilon(); + + x = t; + x.template triangularView<Mode>().inverseInPlace(); + + constexpr unsigned int kUntouched = untouched_mode(Mode); + VERIFY_IS_CWISE_EQUAL(x.template triangularView<kUntouched>().toDenseMatrix(), + t.template triangularView<kUntouched>().toDenseMatrix()); + + const DenseType td = t.template triangularView<Mode>().toDenseMatrix(); + const DenseType xd = x.template triangularView<Mode>().toDenseMatrix(); + const RealScalar residual = (td * xd - DenseType::Identity(n, n)).norm(); + const RealScalar residual_bound = RealScalar(kResidualFactor * n) * eps * td.norm() * xd.norm(); + VERIFY((numext::isfinite)(residual_bound)); + VERIFY(residual <= residual_bound); + + if (!well_conditioned) return; + MatrixType reference = MatrixType::Identity(n, n); + t.template triangularView<Mode>().solveInPlace(reference); + const DenseType referenced = reference.template triangularView<Mode>().toDenseMatrix(); + const RealScalar forward_bound = RealScalar(kForwardFactor * n) * eps * td.norm() * xd.norm() * xd.norm(); + VERIFY((numext::isfinite)(forward_bound)); + VERIFY((xd - referenced).norm() <= forward_bound); +} + +// Strictly diagonally dominant, so cond(T) stays O(1) and the forward comparison is meaningful. The +// scaling also holds with a unit diagonal, where the stored diagonal is ignored. +template <typename MatrixType> +MatrixType well_conditioned_triangular(Index n) { + using Scalar = typename MatrixType::Scalar; + using RealScalar = typename NumTraits<Scalar>::Real; + MatrixType t = MatrixType::Random(n, n) / RealScalar(n + 1); + t.diagonal().array() += Scalar(1); + return t; +} + +// Unscaled off-diagonals, so |T^-1| can grow exponentially in n; only the residual bound applies. +template <typename MatrixType> +MatrixType ill_conditioned_triangular(Index n) { + using Scalar = typename MatrixType::Scalar; + MatrixType t = MatrixType::Random(n, n); + t.diagonal().array() += Scalar(2); + return t; +} + +template <typename MatrixType, typename OperandType> +void check_inverse_all_modes(const MatrixType& t, OperandType& x, bool well_conditioned) { + check_triangular_inverse<Lower>(t, x, well_conditioned); + check_triangular_inverse<Upper>(t, x, well_conditioned); + check_triangular_inverse<UnitLower>(t, x, well_conditioned); + check_triangular_inverse<UnitUpper>(t, x, well_conditioned); +} + +template <typename MatrixType> +void triangular_inverse_all_modes(Index n) { + MatrixType x(n, n); + check_inverse_all_modes(well_conditioned_triangular<MatrixType>(n), x, /*well_conditioned=*/true); + check_inverse_all_modes(ill_conditioned_triangular<MatrixType>(n), x, /*well_conditioned=*/false); +} + +// The destination of LLT::inverse() need not be a plain object, so run the kernel through a block of a +// larger matrix: a non-zero offset and an outer stride that does not match the block width. +template <typename MatrixType> +void triangular_inverse_on_block(Index n) { + const Index row_offset = 2, col_offset = 3; + MatrixType host = MatrixType::Random(n + 3, n + 5); + MatrixType expected = host; + Block<MatrixType> x(host, row_offset, col_offset, n, n); + + check_triangular_inverse<Lower>(well_conditioned_triangular<MatrixType>(n), x, /*well_conditioned=*/true); + + // Nothing outside the block moved. + expected.block(row_offset, col_offset, n, n) = x; + VERIFY_IS_CWISE_EQUAL(host, expected); +} + +// An operand whose inner stride is a run-time value, which is what a Map or Ref with a dynamic inner +// stride hands the blocked kernels: their TRSM and TRMM steps must reach each panel through that +// value, since the compile-time InnerStrideAtCompileTime they also carry is Dynamic. +template <typename MatrixType> +void triangular_inverse_on_strided_map(Index n) { + using Scalar = typename MatrixType::Scalar; + using VectorType = Matrix<Scalar, Dynamic, 1>; + using StrideType = Stride<Dynamic, Dynamic>; + const Index inner = 2, outer = 2 * n + 3; + const Index buffer_size = numext::maxi(Index(1), (n - 1) * (outer + inner) + 1); + VectorType buffer = VectorType::Random(buffer_size); + const VectorType before = buffer; + Map<MatrixType, 0, StrideType> x(buffer.data(), n, n, StrideType(outer, inner)); + + check_triangular_inverse<Lower>(well_conditioned_triangular<MatrixType>(n), x, /*well_conditioned=*/true); + check_triangular_inverse<Upper>(well_conditioned_triangular<MatrixType>(n), x, /*well_conditioned=*/true); + + // Nothing in the gaps between the mapped coefficients moved. + std::vector<bool> mapped(buffer_size, false); + for (Index j = 0; j < n; ++j) + for (Index i = 0; i < n; ++i) mapped[static_cast<std::size_t>(&x.coeffRef(i, j) - buffer.data())] = true; + for (Index k = 0; k < buffer_size; ++k) + if (!mapped[k]) VERIFY_IS_EQUAL(buffer[k], before[k]); +} + +// internal::triangular_adjoint_square_in_place() is what LLT::inverse() uses to turn L^-1 into +// L^-* L^-1. It is not public API, but it needs coverage of its own: a Cholesky factor always has a +// real diagonal, so the conjugations in the kernel are unobservable through LLT. +template <int UpLo, typename MatrixType> +void adjoint_square_in_place(Index n) { + using Scalar = typename MatrixType::Scalar; + using RealScalar = typename NumTraits<Scalar>::Real; + using DenseType = Matrix<Scalar, Dynamic, Dynamic>; + + const RealScalar eps = NumTraits<RealScalar>::epsilon(); + const MatrixType t = ill_conditioned_triangular<MatrixType>(n); + MatrixType a = t; + internal::triangular_adjoint_square_in_place<UpLo>(a); + + const DenseType td = t.template triangularView<UpLo>().toDenseMatrix(); + const DenseType expected = UpLo == Lower ? DenseType(td.adjoint() * td) : DenseType(td * td.adjoint()); + const DenseType computed = a.template triangularView<UpLo>().toDenseMatrix(); + // n accumulations of products of entries of T, so the rounding error is bounded by ~n*eps*|T|^2. + const RealScalar bound = RealScalar(kResidualFactor * n) * eps * td.norm() * td.norm(); + VERIFY((numext::isfinite)(bound)); + VERIFY((computed - expected.template triangularView<UpLo>().toDenseMatrix()).norm() <= bound); + + constexpr unsigned int kUntouched = untouched_mode(UpLo); + VERIFY_IS_CWISE_EQUAL(a.template triangularView<kUntouched>().toDenseMatrix(), + t.template triangularView<kUntouched>().toDenseMatrix()); +} + +template <typename MatrixType> +void adjoint_square_both_triangles(Index n) { + adjoint_square_in_place<Lower, MatrixType>(n); + adjoint_square_in_place<Upper, MatrixType>(n); +} + +EIGEN_DECLARE_TEST(triangular_in_place) { + // 31/32 straddles the unblocked-to-blocked switch, 40 and 65 are not multiples of the block size, + // and at 256 the heuristic first picks a block big enough for the nested kernels to block in turn. + const Index sizes[] = {0, 1, 2, 3, 7, 16, 31, 32, 33, 40, 64, 65, 128, 256}; + for (int i = 0; i < g_repeat; i++) { + for (Index n : sizes) { + EIGEN_UNUSED_VARIABLE(n); // the part-6 build compiles no subtest that takes n + CALL_SUBTEST_1(triangular_inverse_all_modes<MatrixXd>(n)); + CALL_SUBTEST_2(triangular_inverse_all_modes<MatrixXcd>(n)); + CALL_SUBTEST_3(triangular_inverse_all_modes<MatrixXf>(n)); + CALL_SUBTEST_4((triangular_inverse_all_modes<Matrix<double, Dynamic, Dynamic, RowMajor>>(n))); + CALL_SUBTEST_5(triangular_inverse_on_block<MatrixXd>(n)); + CALL_SUBTEST_5(triangular_inverse_on_strided_map<MatrixXd>(n)); + CALL_SUBTEST_7(adjoint_square_both_triangles<MatrixXd>(n)); + CALL_SUBTEST_8(adjoint_square_both_triangles<MatrixXcd>(n)); + CALL_SUBTEST_9(adjoint_square_both_triangles<MatrixXf>(n)); + CALL_SUBTEST_10((adjoint_square_both_triangles<Matrix<double, Dynamic, Dynamic, RowMajor>>(n))); + } + CALL_SUBTEST_6((triangular_inverse_all_modes<Matrix<double, 1, 1>>(1))); + CALL_SUBTEST_6(triangular_inverse_all_modes<Matrix4d>(4)); + CALL_SUBTEST_6((triangular_inverse_all_modes<Matrix<std::complex<float>, 8, 8>>(8))); + } +}