LAPACK: Factor the upper triangle in xSYTRF/xHETRF without touching the lower triangle libeigen/eigen!3671 Closes #3410 Co-authored-by: Rasmus Munk Larsen <rmlarsen@gmail.com> Co-authored-by: florian360 <5298202-florian360@users.noreply.gitlab.com>
diff --git a/Eigen/src/Cholesky/BunchKaufman.h b/Eigen/src/Cholesky/BunchKaufman.h index 539eb54..c213fbe 100644 --- a/Eigen/src/Cholesky/BunchKaufman.h +++ b/Eigen/src/Cholesky/BunchKaufman.h
@@ -526,6 +526,21 @@ const Index n = mat.rows(); const RealScalar alpha = bunch_kaufman_alpha<RealScalar>(); Index info = 0; + // A row-major `mat` (the transpose that bunch_kaufman<Upper> passes) stores a column with a stride. The 2x2 + // update then works by rows, from contiguous copies of the two conjugated factor columns. Below 16 rows the + // copies cost more than the strided column updates do. The copies go on the stack; where they do not fit there, + // the update stays by columns, so that this kernel never allocates on the heap. + constexpr bool is_row_major = MatrixType::IsRowMajor && bool(has_direct_access<MatrixType>::value) && + int(MatrixType::InnerStrideAtCompileTime) == 1; + constexpr Index kMinRowsByRows = 16; +#if defined(EIGEN_ALLOCA) && !defined(EIGEN_NO_ALLOCA) + constexpr std::size_t kStackScalars = std::size_t(EIGEN_STACK_ALLOCATION_LIMIT) / sizeof(Scalar); +#else + constexpr std::size_t kStackScalars = 0; +#endif + const Index max_rs = n - k0 - 2; // the most rows a 2x2 pivot updates + const bool use_rows = is_row_major && max_rs >= kMinRowsByRows && std::size_t(2 * max_rs) <= kStackScalars; + ei_declare_aligned_stack_constructed_variable_if(use_rows, Scalar, scratch, use_rows ? 2 * max_rs : 0, nullptr); Index k = k0; while (k < n) { @@ -636,19 +651,55 @@ const RealScalar t = RealScalar(1) / denom; auto c0 = mat.col(k).tail(rs); auto c1 = mat.col(k + 1).tail(rs); - for (Index j = 0; j < rs; ++j) { - const Scalar u0 = c0.coeff(j); - const Scalar u1 = c1.coeff(j); - const Scalar l0 = t * numext::divide(ak * u0 - u1, cjd); - const Scalar l1 = t * numext::divide(akm1 * u1 - u0, d21); - const Index len = rs - j; - mat.col(k + 2 + j).tail(len) -= numext::conj(l0) * c0.tail(len) + numext::conj(l1) * c1.tail(len); - c0.coeffRef(j) = l0; - c1.coeffRef(j) = l1; - // Keep the updated diagonal exactly real (the correction is Hermitian; roundoff would - // otherwise leave a tiny imaginary part). - EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsComplex) { - mat.coeffRef(k + 2 + j, k + 2 + j) = Scalar(numext::real(mat.coeff(k + 2 + j, k + 2 + j))); + if (use_rows && rs >= kMinRowsByRows) { + // The same update by rows, which are contiguous here: with cl = conj(l), + // A22(i, 0:i) -= u0_i*cl0(0:i)^T + u1_i*cl1(0:i)^T. + using Packet = typename packet_traits<Scalar>::type; + constexpr Index PacketSize = unpacket_traits<Packet>::size; + Scalar* cl0 = scratch; + Scalar* cl1 = scratch + rs; + for (Index i = 0; i < rs; ++i) { + const Scalar u0 = c0.coeff(i); + const Scalar u1 = c1.coeff(i); + const Scalar l0 = t * numext::divide(ak * u0 - u1, cjd); + const Scalar l1 = t * numext::divide(akm1 * u1 - u0, d21); + c0.coeffRef(i) = l0; + c1.coeffRef(i) = l1; + cl0[i] = numext::conj(l0); + cl1[i] = numext::conj(l1); + Scalar* row = &mat.coeffRef(k + 2 + i, k + 2); + const Index len = i + 1; + Index j = 0; + EIGEN_IF_CONSTEXPR (packet_traits<Scalar>::Vectorizable) { + const Packet p0 = pset1<Packet>(u0), p1 = pset1<Packet>(u1); + const Index vectorized_end = len - len % PacketSize; + for (; j < vectorized_end; j += PacketSize) { + Packet r = ploadu<Packet>(row + j); + r = pnmadd(p0, ploadu<Packet>(cl0 + j), r); + r = pnmadd(p1, ploadu<Packet>(cl1 + j), r); + pstoreu(row + j, r); + } + } + for (; j < len; ++j) row[j] -= u0 * cl0[j] + u1 * cl1[j]; + EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsComplex) { + row[i] = Scalar(numext::real(row[i])); + } + } + } else { + for (Index j = 0; j < rs; ++j) { + const Scalar u0 = c0.coeff(j); + const Scalar u1 = c1.coeff(j); + const Scalar l0 = t * numext::divide(ak * u0 - u1, cjd); + const Scalar l1 = t * numext::divide(akm1 * u1 - u0, d21); + const Index len = rs - j; + mat.col(k + 2 + j).tail(len) -= numext::conj(l0) * c0.tail(len) + numext::conj(l1) * c1.tail(len); + c0.coeffRef(j) = l0; + c1.coeffRef(j) = l1; + // Keep the updated diagonal exactly real (the correction is Hermitian; roundoff would + // otherwise leave a tiny imaginary part). + EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsComplex) { + mat.coeffRef(k + 2 + j, k + 2 + j) = Scalar(numext::real(mat.coeff(k + 2 + j, k + 2 + j))); + } } } }
diff --git a/benchmarks/Cholesky/bench_bunchkaufman.cpp b/benchmarks/Cholesky/bench_bunchkaufman.cpp index cb70a0a..efbe399 100644 --- a/benchmarks/Cholesky/bench_bunchkaufman.cpp +++ b/benchmarks/Cholesky/bench_bunchkaufman.cpp
@@ -51,6 +51,22 @@ } BENCHMARK(BM_BunchKaufman)->RangeMultiplier(2)->Range(8, 2048); +// The upper triangle is factorized through a transpose, so the kernel sees a row-major matrix. +static void BM_BunchKaufman_Upper(benchmark::State& state) { + const int n = state.range(0); + MatrixType A = make_indefinite(n); + const int r = internal::random<int>(0, n - 1); + Scalar acc = 0; + for (auto _ : state) { + BunchKaufman<MatrixType, Upper> bk(A); + acc += bk.matrixLDLT().coeff(r, r); + benchmark::DoNotOptimize(acc); + } + state.counters["GFLOPS"] = benchmark::Counter( + symmetric_factorization_cost(n), benchmark::Counter::kIsIterationInvariantRate, benchmark::Counter::kIs1000); +} +BENCHMARK(BM_BunchKaufman_Upper)->RangeMultiplier(2)->Range(8, 2048); + static void BM_BunchKaufman_Solve(benchmark::State& state) { const int n = state.range(0); MatrixType A = make_indefinite(n);
diff --git a/lapack/CMakeLists.txt b/lapack/CMakeLists.txt index 6c06f10..f3016bd 100644 --- a/lapack/CMakeLists.txt +++ b/lapack/CMakeLists.txt
@@ -143,10 +143,11 @@ # Checks of Eigen's routines that need no Fortran compiler. if(EIGEN_BUILD_TESTING) + find_package(Threads REQUIRED) function(eigen_add_lapack_cxx_test name source library) add_executable(${name} testing/${source}.cpp) target_include_directories(${name} PRIVATE "${Eigen_SOURCE_DIR}/test") - target_link_libraries(${name} ${library}) + target_link_libraries(${name} ${library} Threads::Threads) if(MSVC) # lapack_wrappers.cpp can exceed the COFF section limit (C1128). target_compile_options(${name} PRIVATE "-bigobj")
diff --git a/lapack/cholesky.inc b/lapack/cholesky.inc index cf16030..97335dc9 100644 --- a/lapack/cholesky.inc +++ b/lapack/cholesky.inc
@@ -163,13 +163,30 @@ Eigen::internal::bunch_kaufman<Eigen::Lower>::blocked(A, transpositions, subdiag, workspace); *info = bunch_kaufman_to_lapack(A, transpositions, subdiag, ipiv); } else { - // J A J in place: the upper triangle becomes the lower one that the kernel factors, and the strictly lower - // triangle, which the kernel does not touch, returns to its place when the reversal is undone. The last of equal - // pivot candidates in the reversed order is xSYTRF's first in the original order. - A.reverseInPlace(); - Eigen::internal::bunch_kaufman<Eigen::Lower>::blocked</*LastOnTies=*/true>(A, transpositions, subdiag, workspace); - const EIGEN_BLAS_INT reversed_info = bunch_kaufman_to_lapack(A, transpositions, subdiag, ipiv); - A.reverseInPlace(); + // Reflect the upper triangle across the anti-diagonal. Its transpose then exposes J A J + // to the lower kernel, with positive strides and without accessing the unused triangle. + // The reflection runs in 8 x 8 tiles: one side of each swap walks along a row, and the 8 cache lines a tile + // touches there fit one L1 cache set even when the leading dimension is a multiple of the page size. + const auto reflect_upper = [&] { + const Eigen::Index size = A.rows(), ld = A.outerStride(), tile = 8; + Scalar *a = A.data(); + for (Eigen::Index j0 = 0; j0 < size; j0 += tile) + for (Eigen::Index i0 = 0; i0 <= j0 + tile - 1 && i0 < size - 1 - j0; i0 += tile) { + const Eigen::Index j1 = std::min(j0 + tile, size); + for (Eigen::Index j = j0; j < j1; ++j) { + const Eigen::Index i1 = std::min(std::min(i0 + tile, j + 1), size - 1 - j); + Scalar *src = a + j * ld; // A(i, j) + Scalar *dst = a + (size - 1) * ld + (size - 1 - j); // A(size-1-j, size-1-i) is dst[-i * ld] + for (Eigen::Index i = i0; i < i1; ++i) std::swap(src[i], dst[-i * ld]); + } + } + }; + reflect_upper(); + auto reversed = A.transpose(); + Eigen::internal::bunch_kaufman<Eigen::Lower>::blocked</*LastOnTies=*/true>(reversed, transpositions, subdiag, + workspace); + const EIGEN_BLAS_INT reversed_info = bunch_kaufman_to_lapack(reversed, transpositions, subdiag, ipiv); + reflect_upper(); std::reverse(ipiv, ipiv + *n); for (EIGEN_BLAS_INT i = 0; i < *n; ++i) ipiv[i] = reversed_pivot(ipiv[i], *n); *info = reversed_info == 0 ? 0 : *n + 1 - reversed_info;
diff --git a/lapack/testing/lapack_wrappers.cpp b/lapack/testing/lapack_wrappers.cpp index 2fe83d7..5d016e6 100644 --- a/lapack/testing/lapack_wrappers.cpp +++ b/lapack/testing/lapack_wrappers.cpp
@@ -11,6 +11,9 @@ // ||dA|| <= c n eps ||A|| (Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., Thms 10.3, 19.4); the // factor c at each site is set from the measured errors of the four scalar types and carries a margin of at least 4. +#include <atomic> +#include <thread> + #include "main.h" #include "../lapack.h" @@ -483,6 +486,84 @@ } } +// With LDA > N the factorization works on the leading N rows and leaves the rest of the array alone. The sizes +// straddle the 8 x 8 tiles in which UPLO = 'U' reflects the upper triangle. A zero diagonal makes the first pivot +// 2 x 2, which at N = 23 and 40 has the 16 rows below it that the update by rows needs. +template <typename Scalar> +void test_bunch_kaufman_padded_lda() { + for (char uplo : {'L', 'U'}) { + for (Int n : {1, 7, 8, 9, 16, 23, 40, 70}) { + for (bool zero_diagonal : {false, true}) { + if (zero_diagonal && n == 1) continue; // singular + Mat<Scalar> A0 = random_hermitian<Scalar>(n); + if (zero_diagonal) A0.diagonal().setZero(); + Mat<Scalar> A = A0; + poison_opposite(A, uplo); + const Int pad = 3; + Int size = n, lda = n + pad, lwork = n, info = -99; + Mat<Scalar> padded = Mat<Scalar>::Constant(lda, n, make_nan<Scalar>()); + padded.topRows(n) = A; + const Mat<Scalar> before = padded; + std::vector<Int> ipiv(n, 0); + std::vector<Scalar> work(lwork); + Lapack<Scalar>::bktrf(&uplo, &size, rp(padded.data()), &lda, ipiv.data(), rp(work.data()), &lwork, &info); + VERIFY_IS_EQUAL(info, 0); + check_ipiv(uplo, ipiv); + VERIFY(same_bits(Mat<Scalar>(padded.bottomRows(pad)), Mat<Scalar>(before.bottomRows(pad)))); + const Mat<Scalar> F = padded.topRows(n); + VERIFY(opposite_untouched(F, A, uplo)); + check_bk_factor(uplo, A0, F, ipiv); + check_bktrs(uplo, A0, F, ipiv); + } + } + } +} + +// Two Hermitian matrices in one (N + 1) x N array, one in the upper triangle of its leading N rows and one in the +// lower triangle of its trailing N rows, factored at the same time. Neither call may move the other's entries, not +// even to put them back before it returns (#3410). Both runs use the same array, because the rounding of a kernel +// can depend on the alignment of its operands. +template <typename Scalar> +void test_bunch_kaufman_shared_array() { + const Int n = 300; + Mat<Scalar> shared(n + 1, n); + shared.topRows(n).template triangularView<Upper>() = random_hermitian<Scalar>(n); + shared.bottomRows(n).template triangularView<Lower>() = random_hermitian<Scalar>(n); + const Mat<Scalar> input = shared; + const auto factor = [&shared, n](char uplo, std::vector<Int>& ipiv, Int& info) { + Int size = n, lda = n + 1, lwork = n; + std::vector<Scalar> work(lwork); + Scalar* a = shared.data() + (uplo == 'U' ? 0 : 1); + Lapack<Scalar>::bktrf(&uplo, &size, rp(a), &lda, ipiv.data(), rp(work.data()), &lwork, &info); + }; + + std::vector<Int> expected_ipiv_upper(n, 0), expected_ipiv_lower(n, 0); + Int expected_info_upper = -99, expected_info_lower = -99; + factor('U', expected_ipiv_upper, expected_info_upper); + factor('L', expected_ipiv_lower, expected_info_lower); + VERIFY_IS_EQUAL(expected_info_upper, 0); + VERIFY_IS_EQUAL(expected_info_lower, 0); + const Mat<Scalar> expected = shared; + + for (int round = 0; round < 8; ++round) { + shared = input; + std::vector<Int> ipiv_upper(n, 0), ipiv_lower(n, 0); + Int info_upper = -99, info_lower = -99; + std::atomic<bool> started(false); + std::thread lower([&] { + started.store(true); + factor('L', ipiv_lower, info_lower); + }); + while (!started.load()) std::this_thread::yield(); + factor('U', ipiv_upper, info_upper); + lower.join(); + VERIFY_IS_EQUAL(info_upper, 0); + VERIFY_IS_EQUAL(info_lower, 0); + VERIFY(ipiv_upper == expected_ipiv_upper && ipiv_lower == expected_ipiv_lower); + VERIFY(same_bits(shared, expected)); + } +} + // The reference xHETRF reads only the real part of the diagonal. template <typename Scalar> void test_hetrf_ignores_imaginary_diagonal() { @@ -1269,6 +1350,8 @@ for (Int i = 0; i < g_repeat; ++i) { LW_FOR_ALL_SCALARS(test_pstrf); LW_FOR_ALL_SCALARS(test_bunch_kaufman); + LW_FOR_ALL_SCALARS(test_bunch_kaufman_padded_lda); + LW_FOR_ALL_SCALARS(test_bunch_kaufman_shared_array); LW_FOR_ALL_SCALARS(test_hetrf_ignores_imaginary_diagonal); LW_FOR_ALL_SCALARS(test_bunch_kaufman_reference_pivots); LW_FOR_ALL_SCALARS(test_bunch_kaufman_scaled_2x2);
diff --git a/test/bunchkaufman.cpp b/test/bunchkaufman.cpp index 86ee9ca..a6273cf 100644 --- a/test/bunchkaufman.cpp +++ b/test/bunchkaufman.cpp
@@ -786,13 +786,13 @@ // on a problem of that size performs no heap allocation. n is chosen above the panel width so the // blocked path (the one that uses the workspace) runs. (Uses the default stack-allocation limit so the // trailing-update GEMM's small blocking buffers stay on the stack rather than the heap.) -template <typename Scalar> +template <typename Scalar, int UpLo> void bunchkaufman_no_malloc() { using MatrixType = Matrix<Scalar, Dynamic, Dynamic>; const Index n = internal::bunch_kaufman_blocksize<Scalar>() + 36; const MatrixType M = MatrixType::Random(n, n); const MatrixType A = M + M.adjoint(); - BunchKaufman<MatrixType> bk(n); // pre-allocates m_matrix, m_transpositions, m_subdiag, m_workspace + BunchKaufman<MatrixType, UpLo> bk(n); // pre-allocates m_matrix, m_transpositions, m_subdiag, m_workspace internal::set_is_malloc_allowed(false); bk.compute(A); internal::set_is_malloc_allowed(true); @@ -891,6 +891,8 @@ CALL_SUBTEST_8(bunchkaufman_near_max_scale<MatrixXcf>()); // No-malloc regression: the size constructor pre-allocates the panel workspace. - CALL_SUBTEST_8(bunchkaufman_no_malloc<double>()); - CALL_SUBTEST_8(bunchkaufman_no_malloc<std::complex<double> >()); + CALL_SUBTEST_8((bunchkaufman_no_malloc<double, Lower>())); + CALL_SUBTEST_8((bunchkaufman_no_malloc<std::complex<double>, Lower>())); + CALL_SUBTEST_8((bunchkaufman_no_malloc<double, Upper>())); + CALL_SUBTEST_8((bunchkaufman_no_malloc<std::complex<double>, Upper>())); }
diff --git a/test/nomalloc.cpp b/test/nomalloc.cpp index c0ab2d1..7d49e02 100644 --- a/test/nomalloc.cpp +++ b/test/nomalloc.cpp
@@ -167,6 +167,26 @@ jSVD.compute(A); } +// A fixed-size Bunch-Kaufman factorization stays off the heap in either triangle and storage order. The upper +// triangle and the row-major lower one give the kernel a row-major matrix, whose 2x2 pivots would update by rows from +// scratch copies; with EIGEN_STACK_ALLOCATION_LIMIT = 0 those copies have no stack to go on. A zero diagonal makes +// the first pivot 2x2, with 18 rows below it. +template <typename Scalar, int UpLo, int Options> +void bunch_kaufman_fixed_no_malloc() { + using MatrixType = Eigen::Matrix<Scalar, 20, 20, Options>; + for (bool zero_diagonal : {false, true}) { + const MatrixType M = MatrixType::Random(); + MatrixType A = M + M.adjoint(); + if (zero_diagonal) A.diagonal().setZero(); + Eigen::BunchKaufman<MatrixType, UpLo> bk; + bk.compute(A); + VERIFY_IS_EQUAL(bk.info(), Eigen::Success); + Eigen::internal::set_is_malloc_allowed(true); + VERIFY_IS_APPROX(A, bk.reconstructedMatrix()); + Eigen::internal::set_is_malloc_allowed(false); + } +} + template <typename Scalar> void selfadjoint_eigensolver_large_fixed_no_malloc() { using Matrix = Eigen::Matrix<Scalar, 96, 96>; @@ -296,6 +316,10 @@ CALL_SUBTEST_4(ctms_decompositions<float>()); CALL_SUBTEST_9(selfadjoint_eigensolver_large_fixed_no_malloc<float>()); CALL_SUBTEST_10(selfadjoint_eigensolver_large_fixed_no_malloc<double>()); + CALL_SUBTEST_14((bunch_kaufman_fixed_no_malloc<double, Upper, ColMajor>())); + CALL_SUBTEST_14((bunch_kaufman_fixed_no_malloc<double, Lower, RowMajor>())); + CALL_SUBTEST_14((bunch_kaufman_fixed_no_malloc<std::complex<float>, Upper, ColMajor>())); + CALL_SUBTEST_14((bunch_kaufman_fixed_no_malloc<std::complex<float>, Lower, ColMajor>())); CALL_SUBTEST_5(test_zerosized()); CALL_SUBTEST_13(gemv_static_buffer());