diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 5e87768..7ee4d9a 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -13,8 +13,12 @@ concurrency: cancel-in-progress: ${{ startsWith(github.ref, 'refs/pull/') }} jobs: test: - name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ matrix.arch }} - ${{ github.event_name }} + name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ matrix.arch }} runs-on: ${{ matrix.os }} + timeout-minutes: 60 + permissions: # needed to allow julia-actions/cache to delete the old caches it created + actions: write + contents: read strategy: fail-fast: false matrix: @@ -26,46 +30,51 @@ jobs: arch: - x64 steps: - - uses: actions/checkout@v4 - - uses: julia-actions/setup-julia@v2 + - uses: actions/checkout@v7 + - uses: julia-actions/setup-julia@v3 with: version: ${{ matrix.version }} arch: ${{ matrix.arch }} - - uses: julia-actions/cache@v2 - with: - cache-registries: "true" - cache-compiled: "true" + - uses: julia-actions/cache@v3 - uses: julia-actions/julia-buildpkg@v1 - uses: julia-actions/julia-runtest@v1 + env: + # the threaded factorizations need several threads to be exercised + JULIA_NUM_THREADS: 4 - uses: julia-actions/julia-processcoverage@v1 - - uses: codecov/codecov-action@v5 + - uses: codecov/codecov-action@v7 with: - token: ${{ secrets.CODECOV_TOKEN }} files: lcov.info + token: ${{ secrets.CODECOV_TOKEN }} + fail_ci_if_error: false docs: name: Documentation runs-on: ubuntu-latest + timeout-minutes: 60 permissions: + actions: write # needed to allow julia-actions/cache to delete the old caches it created contents: write statuses: write steps: - - uses: actions/checkout@v4 - - uses: julia-actions/setup-julia@v2 + - uses: actions/checkout@v7 + - uses: julia-actions/setup-julia@v3 with: version: '1' - - name: Configure doc environment - run: | - julia --project=docs/ -e ' - using Pkg - Pkg.develop(PackageSpec(path=pwd())) - Pkg.instantiate()' - - uses: julia-actions/julia-buildpkg@v1 + - uses: julia-actions/cache@v3 + # instantiates `docs/` and runs `docs/make.jl`, whose `makedocs` also runs the doctests - uses: julia-actions/julia-docdeploy@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - run: | - julia --project=docs -e ' - using Documenter: DocMeta, doctest - using HMatrices - DocMeta.setdocmeta!(HMatrices, :DocTestSetup, :(using HMatrices); recursive=true) - doctest(HMatrices)' + runic: + name: Runic formatting + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: julia-actions/setup-julia@v3 + with: + version: '1' + - uses: julia-actions/cache@v3 + # checks every Julia file of the repository + - uses: fredrikekre/runic-action@v1 + with: + version: '1' diff --git a/.github/workflows/CompatHelper.yml b/.github/workflows/CompatHelper.yml index cba9134..145bedd 100644 --- a/.github/workflows/CompatHelper.yml +++ b/.github/workflows/CompatHelper.yml @@ -3,14 +3,44 @@ on: schedule: - cron: 0 0 * * * workflow_dispatch: +permissions: + contents: write + pull-requests: write jobs: CompatHelper: runs-on: ubuntu-latest steps: - - name: Pkg.add("CompatHelper") - run: julia -e 'using Pkg; Pkg.add("CompatHelper")' - - name: CompatHelper.main() + - name: Check if Julia is already available in the PATH + id: julia_in_path + run: which julia + continue-on-error: true + - name: Install Julia, but only if it is not already available in the PATH + uses: julia-actions/setup-julia@v3 + with: + version: '1' + arch: ${{ runner.arch }} + if: steps.julia_in_path.outcome != 'success' + - name: Add the General registry via Git + run: | + import Pkg + ENV["JULIA_PKG_SERVER"] = "" + Pkg.Registry.add("General") + shell: julia --color=yes {0} + - name: Install CompatHelper + run: | + import Pkg + name = "CompatHelper" + uuid = "aa819f21-2bde-4658-8897-bab36330d9b7" + version = "3" + Pkg.add(; name, uuid, version) + shell: julia --color=yes {0} + - name: Run CompatHelper + run: | + import CompatHelper + CompatHelper.main() + shell: julia --color=yes {0} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # an SSH key, so that the pull requests CompatHelper opens trigger CI (those opened + # with GITHUB_TOKEN do not); the Documenter deploy key serves COMPATHELPER_PRIV: ${{ secrets.DOCUMENTER_KEY }} - run: julia -e 'using CompatHelper; CompatHelper.main()' diff --git a/.github/workflows/FormatCheck.yml b/.github/workflows/FormatCheck.yml deleted file mode 100644 index 3721fa5..0000000 --- a/.github/workflows/FormatCheck.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: format-check - -on: - push: - branches: - - 'main' - tags: '*' - pull_request: - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: julia-actions/setup-julia@v2 - with: - version: '1' - - name: Install Runic - run: julia -e 'using Pkg; Pkg.add("Runic")' - - name: Check formatting - run: julia -e 'using Runic; exit(Runic.main(["--check", "--diff", "src", "test"]))' diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index c78a70b..fc725cc 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -1,82 +1,31 @@ name: Run benchmarks +# Compare the benchmarks of `benchmark/benchmarks.jl` (taken from the pull request) between +# the default branch and the pull request, on a GitHub-hosted runner, and post the ratios +# as a comment. The absolute times of these shared machines are noisy, but both revisions +# run in the same job, so their ratios are meaningful. on: pull_request: + types: [labeled, opened, reopened, synchronize] permissions: pull-requests: write -env: - PACKAGE_NAME: HMatrices +concurrency: + group: benchmark-${{ github.event.pull_request.number }} + cancel-in-progress: true jobs: Benchmark: - runs-on: self-hosted - # run if PR has `run benchmark` label - if: contains(github.event.pull_request.labels.*.name, 'run benchmark') + runs-on: ubuntu-latest + # only for pull requests labeled `run benchmark`, from branches of this repository + if: >- + contains(github.event.pull_request.labels.*.name, 'run benchmark') && + (github.event.action != 'labeled' || github.event.label.name == 'run benchmark') && + github.event.pull_request.head.repo.full_name == github.repository steps: - - uses: actions/checkout@v4 - - uses: julia-actions/setup-julia@latest + - uses: MilesCranmer/AirspeedVelocity.jl@action-v1 with: - version: 1 - - uses: julia-actions/cache@v2 - - - name: Build AirspeedVelocity - env: - JULIA_NUM_THREADS: 8 - OPENBLAS_NUM_THREADS: 1 - run: | - # Lightweight build step, as sometimes the runner runs out of memory: - julia -e 'ENV["JULIA_PKG_PRECOMPILE_AUTO"]=0; import Pkg; Pkg.add(;url="https://github.com/MilesCranmer/AirspeedVelocity.jl.git")' - julia -e 'ENV["JULIA_PKG_PRECOMPILE_AUTO"]=0; import Pkg; Pkg.build("AirspeedVelocity")' - - - name: Add ~/.julia/bin to PATH - run: | - echo "$HOME/.julia/bin" >> $GITHUB_PATH - - - name: Run benchmarks - run: | - echo $PATH - ls -l ~/.julia/bin - mkdir results - benchpkg ${{env.PACKAGE_NAME}} --rev="${{github.event.pull_request.base.sha}},${{github.event.pull_request.head.sha}}" --url=${{github.event.repository.clone_url}} --bench-on="${{github.event.pull_request.head.sha}}" --output-dir=results/ --tune - - - name: Create plots from benchmarks - run: | - mkdir -p plots - benchpkgplot ${{env.PACKAGE_NAME}} --rev="${{github.event.pull_request.base.sha}},${{github.event.pull_request.head.sha}}" --npart=10 --format=pdf --input-dir=results/ --output-dir=plots/ - - - name: Upload plot as artifact - uses: actions/upload-artifact@v4 - with: - name: plots - path: plots - - - name: Create markdown table from benchmarks - run: | - benchpkgtable ${{env.PACKAGE_NAME}} --rev="${{github.event.pull_request.base.sha}},${{github.event.pull_request.head.sha}}" --input-dir=results/ --ratio > table.md - echo '### Benchmark Results' > body.md - echo '' >> body.md - echo '' >> body.md - cat table.md >> body.md - echo '' >> body.md - echo '' >> body.md - echo '### Benchmark Plots' >> body.md - echo 'A plot of the benchmark results have been uploaded as an artifact to the workflow run for this PR.' >> body.md - echo 'Go to "Actions"->"Run benchmarks"->[the most recent run]->"Artifacts" (at the bottom).' >> body.md - - - name: Find Comment - uses: peter-evans/find-comment@v3 - id: fcbenchmark - with: - issue-number: ${{github.event.pull_request.number}} - comment-author: "github-actions[bot]" - body-includes: Benchmark Results - - - name: Comment on PR - uses: peter-evans/create-or-update-comment@v4 - with: - comment-id: ${{steps.fcbenchmark.outputs.comment-id}} - issue-number: ${{github.event.pull_request.number}} - body-path: body.md - edit-mode: replace + julia-version: "1" + bench-on: ${{ github.event.pull_request.head.sha }} + exeflags: "--threads=4" diff --git a/Project.toml b/Project.toml index c218ca5..ae75a82 100644 --- a/Project.toml +++ b/Project.toml @@ -1,10 +1,11 @@ name = "HMatrices" uuid = "8646bddf-ab1c-4fa7-9c51-ba187d647618" -version = "0.2.13" +version = "0.3" [deps] LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7" +Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" RecipesBase = "3cdcf5f2-1ef4-517c-9805-6587b60abb01" SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" @@ -13,6 +14,7 @@ Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2" [compat] LinearAlgebra = "1" Printf = "1" +Random = "1" RecipesBase = "1.1" SparseArrays = "1" StaticArrays = "1.2" diff --git a/benchmark/Project.toml b/benchmark/Project.toml index 9a3dc9c..81a4e32 100644 --- a/benchmark/Project.toml +++ b/benchmark/Project.toml @@ -2,6 +2,5 @@ BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf" HMatrices = "8646bddf-ab1c-4fa7-9c51-ba187d647618" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" -LoopVectorization = "bdcacae8-1622-11e9-2a5c-532679323890" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" diff --git a/benchmark/benchmarks.jl b/benchmark/benchmarks.jl index b4d1d6d..c96fdea 100644 --- a/benchmark/benchmarks.jl +++ b/benchmark/benchmarks.jl @@ -1,115 +1,117 @@ -# import Pkg -# Pkg.activate(@__DIR__) - +# The benchmark suite, run by AirspeedVelocity on pull requests labeled `run benchmark` +# (see `.github/workflows/benchmark.yml`). The script of the pull request is run on both +# the base and the head revisions, so it must only use functions which exist in both. +# +# Run it locally with e.g. +# benchpkg HMatrices --path=. --rev=main,dirty --script=benchmark/benchmarks.jl --add=StaticArrays --exeflags="--threads=4" +# With `HMATRICES_BENCHMARK_BLAS=AppleAccelerate` (or `MKL`), and that package added with +# `--add`, it is loaded to replace the default BLAS. using HMatrices -using HMatrices: PartialACA, TSVD +using HMatrices: ClusterTree, CardinalitySplitter, StrongAdmissibilityStd, PartialACA, TSVD using BenchmarkTools -using Random using LinearAlgebra -using LoopVectorization # for vectorized kernels +using Random using StaticArrays -include(joinpath(HMatrices.PROJECT_ROOT, "test", "testutils.jl")) - -const SUITE = BenchmarkGroup() - -BenchmarkTools.DEFAULT_PARAMETERS.gcsample = true +let blas = get(ENV, "HMATRICES_BENCHMARK_BLAS", "") + isempty(blas) || @eval using $(Symbol(blas)) +end +# the parallelism comes from the blocks, not from BLAS BLAS.set_num_threads(1) +@info "Benchmarking on $(Threads.nthreads()) threads" BLAS.get_config() -#=========================================================================================== +const SUITE = BenchmarkGroup() -Benchmark the compression using: - - aca - - partial aca - - tsvd +""" + fibonacci_sphere(n) + +Quasi-uniform distribution of `n` points on the unit sphere. +""" +function fibonacci_sphere(n) + ϕ = (1 + sqrt(5)) / 2 + return map(1:n) do i + z = 1 - (2i - 1) / n + r = sqrt(1 - z^2) + θ = 2π * i / ϕ + return SVector(r * cos(θ), r * sin(θ), z) + end +end -===========================================================================================# +""" + single_layer_sphere(n; k = 0) + +Nyström-like discretization of the Laplace (`k = 0`) or Helmholtz single-layer operator +on the unit sphere, with `n` quasi-uniform points of equal weights. The diagonal is the +integral of the static part of the kernel over a disk of the area of a point. +""" +function single_layer_sphere(n; k = 0) + X = fibonacci_sphere(n) + w = 4π / n + a = sqrt(w / π) + f = if iszero(k) + (x, y) -> x == y ? a / 2 : w / (4π * norm(x - y)) + else + (x, y) -> begin + x == y && return complex(a / 2, k * w / (4π)) + d = norm(x - y) + return w * exp(im * k * d) / (4π * d) + end + end + return KernelMatrix(f, X, X) +end -SUITE["Compressors"] = BenchmarkGroup(["aca", "compression", "rkmatrix"]) +const ATOL = 1.0e-6 # tolerance of the factorizations +const ADM = StrongAdmissibilityStd(3) +const COMP = PartialACA(; rtol = 1.0e-8) # compressor of the assembly -rtol = 1.0e-6 -N = 1000 -X = rand(SVector{3, Float64}, N) -Y = map(x -> x + SVector(3, 3, 3), X) -K = laplace_matrix(X, Y) -irange = 1:N -jrange = 1:N +cluster(X) = ClusterTree(X, CardinalitySplitter(; nmax = 50)) -compressors = [PartialACA(; rtol = rtol), TSVD(; rtol = rtol)] +#=========================================================================================== +Compression of a single block of well-separated clusters +===========================================================================================# -for comp in compressors - SUITE["Compressors"][string(comp)] = @benchmarkable $comp($K, $irange, $jrange) +let N = 1000, rtol = 1.0e-6 + Random.seed!(1) + X = rand(SVector{3, Float64}, N) + Y = map(x -> x + SVector(3, 3, 3), X) + K = KernelMatrix((x, y) -> 1 / (4π * norm(x - y)), X, Y) + compressors = Dict("PartialACA" => PartialACA(; rtol), "TSVD" => TSVD(; rtol)) + if isdefined(HMatrices, :RandomizedSVD) + compressors["RandomizedSVD"] = HMatrices.RandomizedSVD(; rtol) + end + G = SUITE["compressors"] = BenchmarkGroup() + for (name, comp) in compressors + G[name] = @benchmarkable $comp($K, 1:$N, 1:$N) + end end #=========================================================================================== - -Problem parameters - +Assembly, products and factorizations of the single-layer operator on the sphere ===========================================================================================# -N = 50_000 -nmax = 200 -eta = 3 -rtol = 1.0e-4 -radius = 1 - -X = points_on_cylinder(N, radius) -splitter = HMatrices.CardinalitySplitter(nmax) -Xclt = HMatrices.ClusterTree(X, splitter) -adm = HMatrices.StrongAdmissibilityStd(eta) -comp = HMatrices.PartialACA(; rtol) - -step = 1.75 * π * radius / sqrt(N) -k = 2 * π / (10 * step) # 10 pts per wavelength - -kernels = Dict( - "Laplace" => laplace_matrix(X, X), - "Laplace vectorized" => LaplaceMatrixVec(X, X), -) +let n = 20_000 + K = single_layer_sphere(n) + clt = cluster(K.X) + H = assemble_hmatrix(K, clt, clt; adm = ADM, comp = COMP) + Hh = assemble_hmatrix(Hermitian(K), clt, clt; adm = ADM, comp = COMP) + F = lu(H; atol = ATOL) + x, y = rand(n), zeros(n) + G = SUITE["Laplace"] = BenchmarkGroup() + for threads in (false, true) + G["assemble threads=$threads"] = @benchmarkable assemble_hmatrix($K, $clt, $clt; adm = ADM, comp = COMP, threads = $threads) samples = 3 evals = 1 + G["mul! threads=$threads"] = @benchmarkable mul!($y, $H, $x, 1, 0; threads = $threads) + G["lu threads=$threads"] = @benchmarkable lu!(M; atol = ATOL, threads = $threads) setup = (M = deepcopy($H)) samples = 3 evals = 1 + G["cholesky threads=$threads"] = @benchmarkable cholesky!(M; atol = ATOL, threads = $threads) setup = (M = deepcopy($Hh)) samples = 3 evals = 1 + end + G["solve"] = @benchmarkable $F \ $x +end -for (name, K) in kernels - SUITE[name] = BenchmarkGroup([name, N]) - for threads in (true, false) - # assemble - SUITE[name]["assemble threads=$threads"] = @benchmarkable assemble_hmatrix( - $K, - $Xclt, - $Xclt; - adm = $adm, - comp = $comp, - threads = $threads, - ) samples = 4 evals = 1 - # gemv and LU times for the same kernel should be the same (it only - # cares about the hmatrix), so benchmark only one of them - if occursin("vectorized", name) - # Matrix vector product. The assembly is considered in a - # setup-phase. A single sample but multiple evaluations to amortize - # the setup cost - SUITE[name]["gemv threads=$threads"] = - @benchmarkable mul!(y, H, x; threads = $threads) setup = ( - H = assemble_hmatrix( - $K, - $Xclt, - $Xclt; - adm = $adm, - comp = $comp, - threads = true, - ); - x = randn($N); - y = zeros($N) - ) samples = 1 evals = 50 - # LU factorization. The assemble is considered in a setup-phase. - SUITE[name]["LU threads=$threads"] = - @benchmarkable lu!(H, $comp; threads = $threads) setup = ( - H = assemble_hmatrix( - $K, - $Xclt, - $Xclt; - adm = $adm, - comp = $comp, - threads = true, - ) - ) samples = 4 evals = 1 - end +let n = 8_000 + K = single_layer_sphere(n; k = 8) + clt = cluster(K.X) + H = assemble_hmatrix(K, clt, clt; adm = ADM, comp = COMP) + G = SUITE["Helmholtz"] = BenchmarkGroup() + for threads in (false, true) + G["lu threads=$threads"] = @benchmarkable lu!(M; atol = ATOL, threads = $threads) setup = (M = deepcopy($H)) samples = 3 evals = 1 end end diff --git a/docs/Project.toml b/docs/Project.toml index 28f75c3..5838095 100644 --- a/docs/Project.toml +++ b/docs/Project.toml @@ -1,5 +1,12 @@ [deps] Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4" +HMatrices = "8646bddf-ab1c-4fa7-9c51-ba187d647618" IterativeSolvers = "42fd0dbc-a981-5370-80f2-aaf504508153" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" + +[sources] +HMatrices = {path = ".."} + +[compat] +Documenter = "1" diff --git a/docs/src/index.md b/docs/src/index.md index c5d87a7..7554908 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -92,7 +92,8 @@ H = assemble_hmatrix(K, X, Y; atol = 1e-6, threads = false) ``` The keyword arguments of [`assemble_hmatrix`](@ref) control the accuracy of the -low-rank blocks (`atol`, `rtol` and `rank`), which blocks are compressed (`eta`), and +low-rank blocks (`atol`, `rtol` and `rank`, for a partial ACA, see +[`PartialACA`](@ref)), which blocks are compressed (`eta`), and the size of the smallest clusters (`nmax`). If `K` is a `Hermitian` matrix, wrapping it as `Hermitian(K)` assembles only half of it and allows for a Cholesky factorization. When `K` is a [`KernelMatrix`](@ref), the points can be omitted (see the @@ -168,21 +169,17 @@ hierarchical Cholesky factorization is available for an `H` assembled from a `Hermitian` matrix): ```@example assemble-basic -F = lu(H;atol=1e-6) +F = lu(H; atol = 1e-6, threads = false) ``` -Note that unliked the matrix-vector product, factoring `H` is not *exact* in the -sense that `lu(H) ≠ lu(Matrix(H))`. The accuracy of the approximation can be -controlled through the keyword arguments `atol`, `rtol` and `rank`, which are used -in the various intermediate truncations performed during the -factorization. See [`lu`](@ref) for more details. - -!!! important "Truncation error" - The parameters `atol` and `rtol` are used to control the truncation of - low-rank blocks *adaptively* using an estimate of the true error (in - Frobenius norm). These local errors may accumulate after successive - truncations, meaning that the global approximation error (in Frobenius norm) may be larger - than the prescribed tolerance. +Note that unlike the matrix-vector product, factoring `H` is not *exact* in the +sense that `lu(H) ≠ lu(Matrix(H))`: the low-rank blocks of the factors are compressed. +Every update of a block is deferred until the block is needed, so that each low-rank +block of the factors is compressed once, from the sum of its updates. The keyword +arguments `atol`, `rtol` and `rank` control this compression (the truncation of each +low-rank block of the factors, in the Frobenius norm), which is done by a randomized SVD +(see [`RandomizedSVD`](@ref)); another compressor can be passed instead, e.g. +`lu(H, PartialACA(; atol = 1e-6))`. See [`lu!`](@ref) for more details. The returned object `F` is of the `LU` type, and efficient routines are provided to solve linear system using `F`: @@ -207,6 +204,27 @@ operator. rough factorization (with e.g. large tolerance or a fixed rank) as a preconditioner to an iterative solver. +For an `H` assembled from a `Hermitian` matrix, `cholesky(H; atol)` computes a +hierarchical Cholesky factorization, used in the same way. A real shift `H + σ*I` of +such an `H` is also `Hermitian`. + +## Threads + +The assembly, the products and the factorizations run on Julia's threads with +`threads = true` (the default) when Julia is started with several threads (e.g. `julia +--threads=auto`); `threads = false` runs them sequentially. Since the parallelism comes +from the blocks, which are small, BLAS should then run on a single thread: + +```julia +using LinearAlgebra +BLAS.set_num_threads(1) +``` + +An error raised by a threaded computation is rethrown without the backtrace of the task +which raised it; running it again with `threads = false` gives the full backtrace. The +methods taking cluster trees or a compressor (e.g. `lu!(H, comp)`) also accept an +`executor` ([`ThreadsExecutor`](@ref) or [`SerialExecutor`](@ref)) instead of `threads`. + ## Other kernels So far we focused on the (manual) compression of a simple kernel matrix where diff --git a/docs/src/references.md b/docs/src/references.md index d33a37e..1a508aa 100644 --- a/docs/src/references.md +++ b/docs/src/references.md @@ -1,5 +1,8 @@ # [References](@id references-section) +Names that are neither exported nor declared `public` are internal, and may change +without notice. + ```@autodocs Modules = [HMatrices] ``` diff --git a/src/HMatrices.jl b/src/HMatrices.jl index 851af7c..cbf1723 100644 --- a/src/HMatrices.jl +++ b/src/HMatrices.jl @@ -9,6 +9,7 @@ using Printf using RecipesBase using Base.Threads using SparseArrays +import Random const AdjOrMat = Union{Matrix, Adjoint{<:Any, <:Matrix}} @@ -48,6 +49,8 @@ include("rkmatrix.jl") include("compressor.jl") include("hmatrix.jl") include("multiplication.jl") +include("thread_executor.jl") +include("lazy_factorization.jl") include("triangular.jl") include("lu.jl") include("cholesky.jl") @@ -66,6 +69,9 @@ public ClusterTree, AbstractCompressor, PartialACA, TSVD, + RandomizedSVD, + ThreadsExecutor, + SerialExecutor, allocate_buffer, getblock!, rowperm, diff --git a/src/cholesky.jl b/src/cholesky.jl index e490724..9980ab5 100644 --- a/src/cholesky.jl +++ b/src/cholesky.jl @@ -22,78 +22,6 @@ function Base.show(io::IO, ::MIME"text/plain", chol::HChol) return println(io, "Cholesky factorization of $H") end -""" - cholesky!(M::HMatrix,comp) - -Hierarchical Cholesky factorization of `M`, using `comp` to generate the compressed -blocks during the multiplication routines. - -`F \\ b` solves in the ordering of the points used to assemble `M`. The factors `F.L` -and `F.U` are stored in the ordering of the cluster tree, with -`F.L * (F.U * x) ≈ Matrix(M)[F.p, F.p] * x`; products and solves with them act in that ordering. - -The factorization is currently serial: `threads` is accepted but not used. -""" -function LinearAlgebra.cholesky!(M::HermitianHMatrix, compressor; threads = true) - # perform the cholesky decomposition of M in place - _cholesky!(M, compressor, _buffer_channel(compressor, eltype(M))) - # wrap the result in the cholesky structure - return M |> UpperTriangular |> Cholesky -end - -""" - cholesky!(M::HMatrix; atol, rank, rtol, threads = true) - -Hierarchical Cholesky factorization of `M`, using the -`PartialACA(; atol, rank, rtol)` compressor. -""" -function LinearAlgebra.cholesky!(M::HermitianHMatrix; threads = true, kwargs...) - return cholesky!(M, PartialACA(; kwargs...); threads) -end - -""" - cholesky(M::HMatrix,args...;kwargs...) - -Hierarchical cholesky factorization. See [`cholesky!`](@ref) for the available -options. -""" -function LinearAlgebra.cholesky(M::HermitianHMatrix, args...; kwargs...) - return cholesky!(deepcopy(M), args...; kwargs...) -end - -function _cholesky!(M::HermitianHMatrix, compressor, bufs = nothing) - if isleaf(M) - d = data(M) - @debug "dense cholesky! on $M" - cholesky!(d, NoPivot()) - else - @assert !hasdata(M) - chdM = children(M) - m, n = size(chdM) - for i in 1:m - _cholesky!(chdM[i, i], compressor, bufs) - for j in (i + 1):n - Lᵢᵢ = adjoint(UpperTriangular(chdM[i, i])) - ldiv!(Lᵢᵢ, chdM[i, j], compressor, bufs) - end - for j in (i + 1):m - for k in (i + 1):n - _hmul_tree!( - chdM[j, k], - adjoint(chdM[i, j]), - chdM[i, k], - -1, - 1, - compressor, - bufs, - ) - end - end - end - end - return M -end - # solve with the factors `L*U` of an LU or Cholesky factorization, which are in the # ordering of the trees: `L*U*x[q] = y[p]` function LinearAlgebra.ldiv!(A::Union{HLU, HChol}, y::AbstractVecOrMat) diff --git a/src/compressor.jl b/src/compressor.jl index 81f797a..12747f0 100644 --- a/src/compressor.jl +++ b/src/compressor.jl @@ -46,11 +46,10 @@ out; it continues from the largest residual if they show an error above the tole `samples = 0` disables this check, which is also skipped when an entry costs a whole column (in the products of the factorizations). -With `recompress = true`, the result is recompressed by a truncated SVD (see -[`TSVD`](@ref)) with the same tolerances, which lowers its rank (about 20% less memory -for single layers) at the cost of a QR and an SVD of the factors (an assembly up to 2–3 -times slower with cheap kernels). The errors of the two steps add up, so the error can -be up to twice the tolerance. +With `recompress = true`, the result is recompressed by a truncated SVD, computed from +QR factorizations of its factors (see [`TSVD`](@ref)), with the same tolerances, which +lowers its rank at the cost of a QR factorization of each factor and an SVD of a small +matrix. In the factorizations, the lower ranks also make the later products cheaper. The default `rtol` is `sqrt(eps(R))`, where `R` is the real type underlying the entries of the compressed matrix, or only the accuracy attainable with `R` if `atol` or @@ -73,7 +72,7 @@ end function (paca::PartialACA)(K, irange::AbstractRange, jrange::AbstractRange, bufs = nothing) R = _aca_partial(K, irange, jrange, paca.atol, paca.rank, paca.rtol, paca.samples, bufs) paca.recompress || return R - return _recompress!(R, paca.atol, paca.rtol, paca.rank, bufs) + return _recompress!(R, paca.atol, paca.rtol, paca.rank) end (paca::PartialACA)(K::AbstractMatrix) = paca(K, axes(K, 1), axes(K, 2)) @@ -87,20 +86,11 @@ struct ACABuffer{T} rb::Vector{Float64} # squared norms of the rows of `B`, `Inf` for the used columns pa::Vector{Int} pb::Vector{Int} - data::Vector{T} # scratch of the recompression, grown via resize!, never shrunk end # every field is resized by each call of `_aca_partial` function ACABuffer(T) - return ACABuffer{T}(VectorOfVectors(T), VectorOfVectors(T), BitVector(), BitVector(), Float64[], Float64[], Int[], Int[], T[]) -end - -function _get_scratch!(buf::ACABuffer{T}, k) where {T} - n = k * k - if length(buf.data) < n - resize!(buf.data, n) - end - return reshape(view(buf.data, 1:n), k, k) + return ACABuffer{T}(VectorOfVectors(T), VectorOfVectors(T), BitVector(), BitVector(), Float64[], Float64[], Int[], Int[]) end """ @@ -141,6 +131,7 @@ function _aca_partial(K, irange, jrange, atol, rmax, rtol, samples, buffer_ = no r = 0 # current rank zero_rows = true # whether every rejected row of the residual was exactly zero exhausted = false # whether every row was used or rejected + steps = Float64[] # norm of each rank-one update while true while er > max(atol, rtol * est_norm) && r < rmax # remove index i from allowed row @@ -196,6 +187,7 @@ function _aca_partial(K, irange, jrange, atol, rmax, rtol, samples, buffer_ = no B.k += 1 # estimate the error by || R_{k} - R_{k-1} || = ||a bᴴ|| er = sqrt(_frob2(a, b)) + push!(steps, er) # estimate the norm by || K || ≈ || R_k || est_norm = _update_frob_norm(est_norm, A, B) _add_abs2!(ra, a) @@ -215,14 +207,18 @@ function _aca_partial(K, irange, jrange, atol, rmax, rtol, samples, buffer_ = no er = oftype(er, Inf) end # copy from buffer to matrix and create Rk matrix - R_ = RkMatrix(Matrix(A), Matrix(B)) + R_ = RkMatrix(Matrix(A), Matrix(B), :none, _aca_truncation_error(steps)) # indicate that `A` and `B` can be reused reset!(A) reset!(B) return R_ end -# whether single entries of `K` are cheap, as needed by `_aca_residual_sample` +""" + _can_sample(K) + +Whether single entries of `K` are cheap, as needed by `_aca_residual_sample`. +""" _can_sample(K) = true """ @@ -280,6 +276,15 @@ function _add_abs2!(out, a) return out end +""" + _aca_truncation_error(steps) + +The estimated truncation errors of an ACA with rank-one updates of norms `steps`: +keeping `i` updates leaves the next ones, and the error of the last update is estimated +by its norm (the stopping criterion of the ACA). +""" +_aca_truncation_error(steps) = _svd_truncation_error(steps, length(steps), isempty(steps) ? 0.0 : last(steps)) + """ _update_frob_norm(acc,A,B) @@ -409,11 +414,12 @@ end struct TSVD Compression algorithm based on *a posteriori* truncation of an `SVD`: the singular -values `σₖ ≤ max(atol, rtol*σ₁)` are dropped, and at most `rank` are kept. This is the -best approximation of its rank, and its error in the spectral norm is below the -tolerance; note that [`PartialACA`](@ref) estimates its error in the Frobenius norm -instead. It evaluates every entry of the block, so it should be used mostly for "small" -matrices. The default `rtol` is the same as for [`PartialACA`](@ref). +values `σᵣ₊₁, σᵣ₊₂, …` are dropped, for the smallest `r` such that the error of the +truncation in the Frobenius norm, `sqrt(σᵣ₊₁² + σᵣ₊₂² + ⋯)`, is at most `max(atol, +rtol*|M|)`, where `|M|` is the Frobenius norm of the matrix (the norm in which +[`PartialACA`](@ref) estimates its error), and at most `rank` are kept. This is the best +approximation of its rank. It evaluates every entry of the block, so it should be used +mostly for "small" matrices. The default `rtol` is the same as for [`PartialACA`](@ref). """ Base.@kwdef struct TSVD <: AbstractCompressor atol::Float64 = 0 @@ -430,13 +436,22 @@ end (comp::TSVD)(K::AbstractMatrix) = comp(K, axes(K, 1), axes(K, 2)) -# number of singular values `S` (sorted decreasingly) above the tolerance, at most -# `rmax` (zero if they are all below the tolerance) +""" + _truncation_rank(S, atol, rtol, rmax) + +The number of singular values `S` (sorted decreasingly) to keep, at most `rmax`, so that +the Frobenius norm of the dropped ones stays below `max(atol, rtol*norm(S))`. +""" function _truncation_rank(S, atol, rtol, rmax) rtol = _rtol(rtol, atol, rmax, eltype(S)) - isempty(S) && return 0 - tol = max(atol, rtol * S[1]) - return min(count(>(tol), S), rmax) + tol2 = max(atol, rtol * norm(S))^2 + r = length(S) + tail = zero(tol2) + while r > 0 && tail + abs2(S[r]) <= tol2 + tail += abs2(S[r]) + r -= 1 + end + return min(r, rmax) end """ @@ -465,35 +480,38 @@ function compress!(M::Base.Matrix, tsvd::TSVD) A = F.U[:, 1:r] B = @views (F.V[:, 1:r]) * Diagonal(F.S[1:r]) end - return RkMatrix(A, B) + return RkMatrix(A, B, :AB, _svd_truncation_error(F.S, r)) end -function _recompress!(R::RkMatrix{T}, atol, rtol, rmax, bufs = nothing) where {T} +""" + _recompress!(R::RkMatrix, atol, rtol, rmax) + +Recompress `R` in place by a truncated SVD (see [`TSVD`](@ref)), computed from QR +factorizations of its factors, or from `R` itself when they would not be smaller. +""" +function _recompress!(R::RkMatrix{T}, atol, rtol, rmax) where {T} m, n = size(R) k = rank(R) + prior = _error_estimate(R) if k >= min(m, n) # the QR factors would not be smaller than the matrix - Rt = compress!(R.A * adjoint(R.B), TSVD(atol, rmax, rtol)) - R.A, R.B = Rt.A, Rt.B - return R - end - QA, RA = qr!(R.A) - QB, RB = qr!(R.B) - if isnothing(bufs) - C = RA * adjoint(RB) + QA = QB = I + F = svd!(R.A * adjoint(R.B)) else - C = _get_scratch!(bufs, k) - mul!(C, RA, adjoint(RB)) + QA, RA = qr!(R.A) + QB, RB = qr!(R.B) + F = svd!(RA * adjoint(RB)) end - F = svd!(C) r = _truncation_rank(F.S, atol, rtol, rmax) R.A = QA * (F.U[:, 1:r] * Diagonal(F.S[1:r])) R.B = QB * F.V[:, 1:r] + R.orthogonality = :AB + R.truncation_error = _svd_truncation_error(F.S, r, prior) return R end # matrix entries: truncate the equivalent scalar matrix, whose rank is rounded up to a # multiple of the size of the entries -function _recompress!(R::RkMatrix{S}, atol, rtol, rmax, bufs = nothing) where {S <: SMatrix} +function _recompress!(R::RkMatrix{S}, atol, rtol, rmax) where {S <: SMatrix} q = size(S, 2) Rs = RkMatrix(_scalar_matrix(R.A), _scalar_matrix(R.B)) _recompress!(Rs, atol, rtol, rmax > typemax(Int) ÷ q ? typemax(Int) : q * rmax) @@ -536,6 +554,92 @@ function _block_matrix(::Type{S}, M) where {S <: SMatrix} return [S(view(Mp, ((i - 1) * p + 1):(i * p), ((j - 1) * q + 1):(j * q))) for i in 1:m, j in 1:k] end +""" + RandomizedSVD(; atol = 0, rank = typemax(Int), rtol = nothing, block = 4) + +Compression algorithm based on a randomized SVD (Halko, Martinsson and Tropp, "Finding +structure with randomness", SIAM Review 53, 2011): an orthonormal basis `Q` of the range +of the block `M` is given by the Householder QR factorization of the products of `M` +with random Gaussian vectors, extended by blocks of `block` vectors until the error `|M +- Q*Q'*M|` estimated from the last block is below `max(atol, rtol*|M|)`, in the +Frobenius norm. The SVD of `Q'*M` is then truncated as by [`TSVD`](@ref), and at most +`rank` singular values are kept; with a `rank`, the basis has one more block than the +rank, so that the singular values kept are accurate. The default `rtol` is the same as +for [`PartialACA`](@ref). + +It only uses the products `M*X` and `M'*X`, whose evaluations are batched. It suits the +blocks whose updates are deferred in the factorizations and the products: their +products are cheap, while each of their entries costs a whole column. It is the +default compressor of [`lu`](@ref) and [`cholesky`](@ref). Any other block is first +evaluated entirely, so [`PartialACA`](@ref) should be preferred for the assembly. + +The error is estimated from the residuals of a single block of random vectors, which is +more reliable for larger blocks. The random vectors only depend on the size of the +block, so that the results are reproducible. +""" +Base.@kwdef struct RandomizedSVD <: AbstractCompressor + atol::Float64 = 0 + rank::Int = typemax(Int) + rtol::Union{Nothing, Float64} = nothing + block::Int = 4 + function RandomizedSVD(atol, rank, rtol, block) + block >= 1 || throw(ArgumentError("block = $block must be positive")) + return new(_check_tolerances(atol, rank, rtol)..., block) + end +end + +function (comp::RandomizedSVD)(K, irange::AbstractRange, jrange::AbstractRange, buf = nothing) + M = Base.Matrix{eltype(K)}(undef, length(irange), length(jrange)) + getblock!(M, K, irange, jrange) + return _randomized_svd(M, comp) +end + +(comp::RandomizedSVD)(K::AbstractMatrix) = comp(K, axes(K, 1), axes(K, 2)) + +""" + _randomized_svd(K, comp::RandomizedSVD) + +The randomized SVD of `K` (see [`RandomizedSVD`](@ref)), through the products `mul!(Y, K, +X)` and `mul!(Y, K', X)`. +""" +function _randomized_svd(K, comp::RandomizedSVD) + T = eltype(K) + m, n = size(K) + rtol = _rtol(comp.rtol, comp.atol, comp.rank, T) + rng = Random.Xoshiro(hash((m, n))) + kmax = min(m, n, comp.rank > typemax(Int) - comp.block ? typemax(Int) : comp.rank + comp.block) + # the Householder QR factorization of the products with the random vectors, block + # after block: the factorization of a block starting at the column `j+1` acts on the + # rows `j+1:m` (typed after the factorization of the rows of a matrix) + blocks = Tuple{Int, typeof(qr!(view(zeros(T, 1, 1), 1:1, :)))}[] + k = 0 + err = 0.0 # the error of the basis, estimated from the last block + norm2, nsamples = 0.0, 0 # estimate of |K|², from the products with the random vectors + while k < kmax + b = min(comp.block, kmax - k) + Y = mul!(Base.Matrix{T}(undef, m, b), K, Random.randn(rng, T, n, b)) + norm2 += sum(abs2, Y) + nsamples += b + for (j, F) in blocks # Y ← Q'*Y + lmul!(F.Q', view(Y, (j + 1):m, :)) + end + # the rows below the first `k` are the residual of `Y`, in a basis completing `Q` + residual = view(Y, (k + 1):m, :) + err = norm(residual) / sqrt(b) + err <= max(comp.atol, rtol * sqrt(norm2 / nsamples)) && break + push!(blocks, (k, qr!(residual))) + k += b + end + Q = Base.Matrix{T}(I, m, k) + for (j, F) in Iterators.reverse(blocks) + lmul!(F.Q, view(Q, (j + 1):m, (j + 1):k)) + end + F = svd!(mul!(Base.Matrix{T}(undef, n, k), K', Q)) # K'*Q = U*S*V' + r = _truncation_rank(F.S, comp.atol, rtol, comp.rank) + prior = k == min(m, n) ? 0.0 : err + return RkMatrix(Q * (F.V[:, 1:r] * Diagonal(F.S[1:r])), F.U[:, 1:r], :AB, _svd_truncation_error(F.S, r, prior)) +end + """ _check_rtol(comp, T) @@ -543,7 +647,7 @@ Check that the tolerances of `comp` are attainable for entries of type `T`, befo compressing any block. """ _check_rtol(comp, T) = nothing -function _check_rtol(comp::Union{PartialACA, TSVD}, T) +function _check_rtol(comp::Union{PartialACA, TSVD, RandomizedSVD}, T) _rtol(comp.rtol, comp.atol, comp.rank, T) return nothing end diff --git a/src/hmatrix.jl b/src/hmatrix.jl index 4cad437..d8fcd31 100644 --- a/src/hmatrix.jl +++ b/src/hmatrix.jl @@ -48,11 +48,11 @@ parentnode(H::AdjointHMatrix) = H |> parent |> parentnode |> adjoint const HermitianHMatrix{R, T} = Hermitian{T, HMatrix{R, T}} isadmissible(H::HermitianHMatrix) = H |> parent |> isadmissible -data(H::HermitianHMatrix) = H |> parent |> data |> Hermitian +data(H::HermitianHMatrix) = Hermitian(data(parent(H)), Symbol(H.uplo)) rowtree(H::HermitianHMatrix) = H |> parent |> rowtree coltree(H::HermitianHMatrix) = H |> parent |> coltree -children(H::HermitianHMatrix) = H |> parent |> children |> Hermitian -parentnode(H::HermitianHMatrix) = H |> parent |> parentnode |> Hermitian +children(H::HermitianHMatrix) = Hermitian(children(parent(H)), Symbol(H.uplo)) +parentnode(H::HermitianHMatrix) = Hermitian(parentnode(parent(H)), Symbol(H.uplo)) const HTypes = Union{HMatrix, AdjointHMatrix, HermitianHMatrix} @@ -225,12 +225,15 @@ columns of `K`. The points are only used to cluster the indices, and are not mod `SMatrix` entries; [`getblock!`](@ref) can be overloaded to compute its blocks faster. If `K` is a `Hermitian`, only its upper triangle is assembled and a `Hermitian` `HMatrix` is returned (this requires `Y === X`). -- `atol`, `rtol` and `rank` control the compression of the low-rank blocks (see - [`PartialACA`](@ref)); by default `rtol = sqrt(eps)` of the real type of the entries, - or only the accuracy attainable with that type if `atol` or `rank` is given. +- `atol`, `rtol` and `rank` control the compression of the low-rank blocks, by a + partial ACA (see [`PartialACA`](@ref)); by default `rtol = sqrt(eps)` of the real type + of the entries, or only the accuracy attainable with that type if `atol` or `rank` is + given. - Two clusters are compressed if `min(diameters) < eta * distance`; `eta = Inf` compresses every pair of disjoint clusters (weak admissibility). - `nmax` is the maximum number of points in a leaf of the cluster trees. +- The leaves are assembled in parallel with `threads = true` (when Julia runs on + several threads). Every operation on the result (products, `Matrix`, factorizations) uses the ordering of `X` and `Y`. @@ -261,11 +264,13 @@ end """ assemble_hmatrix(K, rowtree::ClusterTree, coltree::ClusterTree; - adm = StrongAdmissibilityStd(), comp = PartialACA(), threads = true) + adm = StrongAdmissibilityStd(), comp = PartialACA(), threads = true, executor) Lower-level version of [`assemble_hmatrix`](@ref) with given cluster trees, admissibility condition `adm` (called on a node of `rowtree` and a node of `coltree` to decide if the -block is compressed) and compressor `comp` (see [`AbstractCompressor`](@ref)). +block is compressed) and compressor `comp` (see [`AbstractCompressor`](@ref)). The leaves +are assembled by `executor`, a [`ThreadsExecutor`](@ref) if `threads = true` and Julia +runs on several threads, and a [`SerialExecutor`](@ref) otherwise. """ function assemble_hmatrix( K::AbstractMatrix, @@ -274,6 +279,7 @@ function assemble_hmatrix( adm = StrongAdmissibilityStd(), comp = PartialACA(), threads = true, + executor = _executor(threads), ) size(K) == (length(rowtree), length(coltree)) || throw(DimensionMismatch("the matrix is of size $(size(K)), but the trees have $(length(rowtree)) and $(length(coltree)) elements")) @@ -295,13 +301,7 @@ function assemble_hmatrix( end # the blocks are assembled in the ordering of the trees K = PermutedMatrix(K, loc2glob(rowtree), loc2glob(coltree)) - # now assemble the data in the blocks - if threads - _assemble_threads!(hmat, K, comp) - else - _assemble_cpu!(hmat, K, comp, allocate_buffer(comp, T)) - end - return hmat + return _assemble!(hmat, K, comp, executor) end """ @@ -349,70 +349,43 @@ function _build_block_structure!(adm, current_node::HMatrix{R, T}) where {R, T} end """ - _assemble_cpu!(hmat::HMatrix,K,comp) + _assemble!(hmat, K, comp, executor) -Assemble data on the leaves of `hmat`. The admissible leaves are compressed -using the compressor `comp`. This function assumes the structure of `hmat` has -already been initialized, and therefore should not be called directly. See -[`HMatrix`](@ref) for information on constructors. +Assemble the leaves of `hmat`, whose structure is already built, each by a piece of work +of `executor` which writes it: the admissible leaves are compressed with `comp`, the +others are evaluated. """ -function _assemble_cpu!(hmat, K, comp, bufs) - if isleaf(hmat) # base case - _process_leaf!(hmat, K, comp, bufs) - else - # recurse on children - for child in children(hmat) - _assemble_cpu!(child, K, comp, bufs) +function _assemble!(hmat, K, comp, executor) + T = eltype(hmat) + pool = workspaces(typeof(allocate_buffer(comp, T))) + _run!(executor) do + for leaf in leaves(hmat) + H = _stored_leaf(leaf) + isnothing(H) && continue + spawn!(executor, (), (H,)) do + if isadmissible(H) + with_workspace(buf -> _assemble_sparse_block!(H, K, comp, buf), pool, () -> allocate_buffer(comp, T)) + else + _assemble_dense_block!(H, K) + end + end end end return hmat end -function _process_leaf!(leaf, K, comp, bufs) - # for hermitian, the upper triangular stores the data - (leaf isa Adjoint || leaf isa Transpose) && (return leaf) - H = if leaf isa Hermitian - parent(leaf) # the underlying HMatrix - elseif leaf isa HMatrix - leaf - else - throw(ArgumentError("Invalid leaf type: $(typeof(leaf))")) - end - # - return if isadmissible(H) - _assemble_sparse_block!(H, K, comp, bufs) - else - _assemble_dense_block!(H, K) - end -end - """ - _assemble_threads!(hmat::HMatrix,K,comp) + _stored_leaf(leaf) -Like [`_assemble_cpu!`](@ref), but uses threads to assemble the leaves. Note -that the threads are spawned using `Threads.@spawn`, which means they are -spawned on the same worker as the caller. +The `HMatrix` storing the data of a leaf of an `HMatrix` or of a `Hermitian` one: +`nothing` for a leaf of the lower triangle of a `Hermitian`, which stores no data. """ -function _assemble_threads!(hmat, K, comp) - c = leaves(hmat) - acc = Threads.Atomic{Int}(1) - # spawn np workers to assemble the leaves in parallel - np = Threads.nthreads() - @sync for _ in 1:np - Threads.@spawn begin - buf = allocate_buffer(comp, eltype(hmat)) - while true - i = Threads.atomic_add!(acc, 1) - i > length(c) && break - _process_leaf!(c[i], K, comp, buf) - end - end - end - return hmat -end +_stored_leaf(leaf::HMatrix) = leaf +_stored_leaf(leaf::Hermitian) = parent(leaf) +_stored_leaf(::Union{Adjoint, Transpose}) = nothing function _assemble_sparse_block!(hmat, K, comp, bufs) - return hmat.data = comp(K, rowrange(hmat), colrange(hmat), bufs) + return setdata!(hmat, comp(K, rowrange(hmat), colrange(hmat), bufs)) end function _assemble_dense_block!(hmat, K) @@ -421,7 +394,7 @@ function _assemble_dense_block!(hmat, K) T = eltype(hmat) out = Matrix{T}(undef, length(irange), length(jrange)) getblock!(out, K, irange, jrange) - hmat.data = out + setdata!(hmat, out) return hmat end @@ -489,17 +462,6 @@ function Base.zero(H::HMatrix) return H0 end -function compress!(H::HMatrix, comp) - @assert isclean(H) - for leaf in leaves(H) - d = data(leaf) - if d isa RkMatrix - compress!(d, comp) - end - end - return H -end - ############################################################################################ # Recipes ############################################################################################ @@ -546,19 +508,17 @@ function LinearAlgebra.axpy!(a, X::UniformScaling, Y::HMatrix) return _axpy_diagonal!(a, X, Y) end -# add `a*X` to the diagonal of the stored blocks of `Y` +# add `a*X` to the diagonal of the stored blocks of `Y`, which are dense leaves or have +# diagonal children (also in a `Hermitian`, whose diagonal blocks are stored) function _axpy_diagonal!(a, X::UniformScaling, Y::HMatrix) - @assert isclean(Y) - if hasdata(Y) + if isleaf(Y) d = data(Y) - @assert d isa Matrix - n = min(size(d)...) - for i in 1:n + d isa Matrix || error("a diagonal leaf must be dense") + for i in 1:min(size(d)...) d[i, i] += a * X.λ end else - n = min(blocksize(Y)...) - for i in 1:n + for i in 1:min(blocksize(Y)...) _axpy_diagonal!(a, X, children(Y)[i, i]) end end @@ -568,6 +528,12 @@ end Base.:(+)(X::UniformScaling, Y::HMatrix) = axpy!(true, X, deepcopy(Y)) Base.:(+)(X::HMatrix, Y::UniformScaling) = Y + X +# a real shift keeps a `Hermitian` Hermitian, and only its stored triangle is modified +function Base.:(+)(H::HermitianHMatrix, J::UniformScaling{<:Real}) + return Hermitian(parent(H) + J, Symbol(H.uplo)) +end +Base.:(+)(J::UniformScaling{<:Real}, H::HermitianHMatrix) = H + J + # adding a sparse matrix to an HMatrix is allowed, but in the current # implementation is done to recompress blocks which may increase rank during the # process. If the rank increases by a large amount, we just print a warning for now. diff --git a/src/lazy_factorization.jl b/src/lazy_factorization.jl new file mode 100644 index 0000000..5ed6b76 --- /dev/null +++ b/src/lazy_factorization.jl @@ -0,0 +1,585 @@ +""" + mutable struct LazyLowRankTerm{T} + +An exact low-rank term `A*B'` of the size of the block it was computed for: the +product `α*X*Y` of two blocks of the factors, one of them being a leaf. One of `A` +and `B` is usually a factor of this leaf (not a copy), the other one is computed. + +It is computed by a piece of work (see `_compute_low_rank_term`), and read by the +flushes of the leaves below the block (see [`LazyDriver`](@ref)), through +restrictions ([`CarryTerm`](@ref)). +""" +mutable struct LazyLowRankTerm{T} + A::Matrix{T} + B::Matrix{T} +end +LazyLowRankTerm{T}() where {T} = LazyLowRankTerm{T}(Matrix{T}(undef, 0, 0), Matrix{T}(undef, 0, 0)) + +""" + struct CarryTerm{T} + +Restriction of a [`LazyLowRankTerm`](@ref) to a block below the one it was computed +for: its rows starting after `row_offset`, and its columns starting after +`col_offset`, the size of the restriction being the one of this block. +""" +struct CarryTerm{T} + term::LazyLowRankTerm{T} + row_offset::Int + col_offset::Int +end + +""" + factors(t::CarryTerm, m, n) + +The factors `(A, B)` of the restriction `t = A*B'`, of size `m × n`, as views. +""" +factors(t::CarryTerm, m, n) = (view(t.term.A, t.row_offset .+ (1:m), :), view(t.term.B, t.col_offset .+ (1:n), :)) + +""" + struct PendingUpdates{P,T} + +The updates pending at a node: the products `(X, Y)` (of type `P`) it still owes, and +the exact low-rank terms already evaluated for it (the carry). +""" +struct PendingUpdates{P, T} + products::Vector{P} + carry::Vector{CarryTerm{T}} +end +PendingUpdates{P, T}() where {P, T} = PendingUpdates{P, T}(P[], CarryTerm{T}[]) + +""" + struct UpdateBuffer{B,T} + +Workspace of a flush: the buffer `comp` of the compressor, the storage `lowrank` of +the packed low-rank factors of the leaf being compressed (see +`_flush_low_rank_leaf!`), and two vectors `scratch` and `rkscratch` for intermediate +products (those of a [`LeafOperator`](@ref)). The vectors grow as needed and are +reused. +""" +struct UpdateBuffer{B, T} + comp::B + lowrank::Vector{T} + scratch::Vector{T} + rkscratch::Vector{T} +end +UpdateBuffer(comp, T::Type) = UpdateBuffer(allocate_buffer(comp, T), T[], T[], T[]) + +""" + struct LazyDriver + +State of an algorithm on an `HMatrix` where every update is deferred until the block +it targets is factorized, solved for, or flushed (e.g. the [`lu!`](@ref) and +[`cholesky!`](@ref) factorizations, `hmul!`), with its numeric work run by an +executor ([`SerialExecutor`](@ref) or [`ThreadsExecutor`](@ref)). + +By the block Crout identity, every block of the factors is determined by a single +Schur complement, a sum of products of blocks of the factors that precede it. +Instead of evaluating these products one at a time and recompressing after each +one, each node carries the products it still owes, and the exact low-rank terms +already evaluated for it (see [`PendingUpdates`](@ref)), representing the update +`C ← C + Σₖ AₖBₖ' + α*Σᵢ XᵢYᵢ`. A node is flushed right before it is factorized or +solved for (see [`flush!`](@ref)), so that every admissible leaf is compressed once, +with `comp`. This is the accumulator of Börm (2019, "Hierarchical matrix arithmetic +with accumulated updates"), except that an admissible leaf is compressed once from +the whole sum. + +The driver does the structural work (pushing and splitting products, restricting +low-rank terms) itself, and hands the numeric work to `executor`: the low-rank +terms of a node, the flush of a leaf, and the factorization of a diagonal leaf or +the triangular solve on a leaf. A leaf is written by at most one flush followed by +one factorization or solve, a low-rank term by one piece of work, and a block is +only read once final, which is the access pattern of the executors. The workspaces +of the pieces of work are taken from `buffers`. + +With `uplo = 'U'` (or `'L'`), only the upper (or lower) triangle of the diagonal +blocks (whose rows and columns have the same indices) is updated, as for the data of a +`Hermitian`; `uplo = 'N'` updates every block. + + LazyDriver(C::HMatrix, X, Y, comp; α = -1, uplo = 'N', executor = SerialExecutor()) + +A driver for the nodes of `C` (and of any `HMatrix` of the same type), with products +of blocks of the types of `X` and `Y` (`HMatrix` or adjoint). +""" +struct LazyDriver{S, T, P, A, C, E, B} + pending::IdDict{HMatrix{S, T}, PendingUpdates{P, T}} + α::A + uplo::Char + comp::C + executor::E + buffers::B +end +function LazyDriver(::HMatrix{S, T}, X, Y, comp; α = -1, uplo = 'N', executor = SerialExecutor()) where {S, T} + # once here rather than in each block, where it would be raised inside a task + T <: Number || throw(ArgumentError("factorizations, products and solves of `HMatrix`s need scalar entries, not $T")) + _check_rtol(comp, T) + P = Tuple{typeof(X), typeof(Y)} + buffers = workspaces(UpdateBuffer{typeof(allocate_buffer(comp, T)), T}) + return LazyDriver(IdDict{HMatrix{S, T}, PendingUpdates{P, T}}(), α, uplo, comp, executor, buffers) +end + +""" + pending!(d::LazyDriver, C::HMatrix) + +The [`PendingUpdates`](@ref) of `C`, created if `C` has none. +""" +function pending!(d::LazyDriver{S, T, P}, C::HMatrix) where {S, T, P} + return get!(PendingUpdates{P, T}, d.pending, C) +end + +""" + push!(d::LazyDriver, C::HMatrix, X, Y) + +Register the update `C ← C + α*X*Y` (see [`LazyDriver`](@ref)), without performing +any arithmetic. `X` and `Y` must not be modified afterwards: their data may be +referenced (without copies) by the low-rank terms created when the update is +applied. +""" +function Base.push!(d::LazyDriver, C::HMatrix, X, Y) + push!(pending!(d, C).products, (X, Y)) + return d +end + +""" + with_buffer(f, d::LazyDriver) + +`f(buf)` with a workspace `buf` (an [`UpdateBuffer`](@ref)) used by no other piece +of work at the same time (see [`with_workspace`](@ref)). +""" +with_buffer(f, d::LazyDriver{S, T}) where {S, T} = with_workspace(f, d.buffers, () -> UpdateBuffer(d.comp, T)) + +""" + flush!(d::LazyDriver, C::HMatrix) + +Apply the updates pending at `C` (not those pending at its descendants): + +- internal node: a pending product with a leaf factor has an exact low-rank form, + which is computed once, here, and shared by the leaves below (carry); the other + products are split into the products of the children; the carry is restricted to + the children; +- dense leaf: the carry and the products are added exactly; +- admissible leaf: its data, its carry and the products with an exact low-rank form + are written side by side as `A*B'`, and `A*B' + α*Σ XᵢYᵢ` (the other products) is + compressed once (see [`LeafOperator`](@ref)). +""" +function flush!(d::LazyDriver, C::HMatrix) + updates = pop!(d.pending, C, nothing) + isnothing(updates) && return C + if !isleaf(C) + _flush_internal_node!(d, C, updates) + return C + end + reads = Iterators.flatten(((Z for (X, Y) in updates.products for Z in (X, Y)), (t.term for t in updates.carry))) + spawn!(d.executor, reads, (C,)) do + if isadmissible(C) + with_buffer(buf -> _flush_low_rank_leaf!(C, updates, d.α, d.comp, buf), d) + else + _flush_dense_leaf!(C, updates, d.α) + end + end + return C +end + +""" + flush_tree!(d::LazyDriver, C::HMatrix) + +Flush `C` and all of its descendants, top-down. +""" +function flush_tree!(d::LazyDriver, C::HMatrix) + flush!(d, C) + foreach(chd -> flush_tree!(d, chd), children(C)) + return C +end + +""" + _flush_internal_node!(d::LazyDriver, C::HMatrix, updates::PendingUpdates) + +The flush of the internal node `C` (see [`flush!`](@ref)). With `d.uplo = 'U'` (or +`'L'`), a diagonal block only hands its updates to the children of its upper (or lower) +triangle. +""" +function _flush_internal_node!(d::LazyDriver{S, T}, C::HMatrix, updates) where {S, T} + @assert !hasdata(C) "internal node with data found" + # the products with an exact low-rank form, computed by one piece of work, and + # shared by the leaves below `C` + low_rank_products = filter(((X, Y),) -> _has_low_rank_form(X, Y), updates.products) + if !isempty(low_rank_products) + terms = [LazyLowRankTerm{T}() for _ in low_rank_products] + append!(updates.carry, CarryTerm(term, 0, 0) for term in terms) + reads = (Z for (X, Y) in low_rank_products for Z in (X, Y)) + spawn!(d.executor, reads, terms) do + with_buffer(d) do buf + for ((X, Y), term) in zip(low_rank_products, terms) + term.A, term.B = _compute_low_rank_term(X, Y, d.α, buf.scratch) + end + end + end + end + # the other products and the carry are handed to the children + chdC = children(C) + diagonal = rowrange(C) == colrange(C) + skip(i, j) = diagonal && (d.uplo == 'U' ? i > j : d.uplo == 'L' ? i < j : false) + for (X, Y) in updates.products + _has_low_rank_form(X, Y) && continue + @assert !isleaf(X) && !isleaf(Y) "the factors of a product are not clustered like its target" + chdX, chdY = children(X), children(Y) + for i in axes(chdC, 1), j in axes(chdC, 2), k in axes(chdX, 2) + skip(i, j) && continue + push!(d, chdC[i, j], chdX[i, k], chdY[k, j]) + end + end + isempty(updates.carry) && return C + for j in axes(chdC, 2), i in axes(chdC, 1) + skip(i, j) && continue + chd = chdC[i, j] + row_shift = first(rowrange(chd)) - first(rowrange(C)) + col_shift = first(colrange(chd)) - first(colrange(C)) + carry = pending!(d, chd).carry + for t in updates.carry + push!(carry, CarryTerm(t.term, t.row_offset + row_shift, t.col_offset + col_shift)) + end + end + return C +end + +""" + _flush_dense_leaf!(C::HMatrix, updates::PendingUpdates, α) + +Add the carry and the products `α*X*Y` to the dense data of the leaf `C`. +""" +function _flush_dense_leaf!(C::HMatrix, updates, α) + d = data(C)::Matrix{eltype(C)} + m, n = size(C) + for t in updates.carry + A, B = factors(t, m, n) + mul!(d, A, B', true, true) + end + for (X, Y) in updates.products + _mul_dense!(d, X, Y, α) + end + return C +end + +""" + _flush_low_rank_leaf!(C::HMatrix, updates::PendingUpdates, α, comp, buf::UpdateBuffer) + +Compress `data(C) + Σ AₖBₖ' + α*Σ XᵢYᵢ` for the admissible leaf `C`, with the carry +`(Aₖ, Bₖ)` and the pending products `(Xᵢ, Yᵢ)`. + +The low-rank terms (the data, the carry, and the products with an exact low-rank +form, evaluated here) are packed side by side into a single pair of factors `(A, B)` +stored in `buf.lowrank`, so that the compressor samples them with one +matrix-vector product, without allocating. The other products are only sampled by +the compressor, through a [`LeafOperator`](@ref). +""" +function _flush_low_rank_leaf!(C::HMatrix, updates, α, comp, buf::UpdateBuffer) + T = eltype(C) + m, n = size(C) + R = data(C)::RkMatrix{T} + exact = filter(((X, Y),) -> _has_low_rank_form(X, Y), updates.products) + implicit = filter(((X, Y),) -> !_has_low_rank_form(X, Y), updates.products) + r = rank(R) + sum(t -> size(t.term.A, 2), updates.carry; init = 0) + + sum(((X, Y),) -> _low_rank_term_rank(X, Y), exact; init = 0) + w = buf.lowrank + length(w) < (m + n) * r && resize!(w, (m + n) * r) + A = reshape(view(w, 1:(m * r)), m, r) + B = reshape(view(w, (m * r + 1):((m + n) * r)), n, r) + k = 0 + for (Aₜ, Bₜ) in Iterators.flatten((((R.A, R.B),), (factors(t, m, n) for t in updates.carry))) + cols = (k + 1):(k + size(Aₜ, 2)) + copyto!(view(A, :, cols), Aₜ) + copyto!(view(B, :, cols), Bₜ) + k = last(cols) + end + for (X, Y) in exact + cols = (k + 1):(k + _low_rank_term_rank(X, Y)) + _compute_low_rank_term!(view(A, :, cols), view(B, :, cols), X, Y, α, buf.scratch) + k = last(cols) + end + L = LeafOperator{T}(A, B, implicit, α, buf.scratch, buf.rkscratch) + setdata!(C, comp(L, axes(L, 1), axes(L, 2), buf.comp)) + return C +end + +""" + _is_low_rank(X) + +Whether `X` is a low-rank (admissible) leaf. +""" +_is_low_rank(X) = isleaf(X) && isadmissible(X) + +""" + _rank_of(X) + +The rank of the low-rank leaf `X` (an `HMatrix` or its adjoint). +""" +_rank_of(X) = size(first(_rkfactors(data(X))), 2) + +""" + _has_low_rank_form(X, Y) + +Whether `X*Y` has an exact low-rank form computed by `_compute_low_rank_term`: `X` +or `Y` is a low-rank leaf, or both are dense leaves. This is always the case for a +product pending at an internal node with a leaf factor, since the cluster shared by +`X` and `Y` is then a leaf. +""" +_has_low_rank_form(X, Y) = _is_low_rank(X) || _is_low_rank(Y) || (isleaf(X) && isleaf(Y)) + +""" + _through_x(X, Y) + +Whether `_compute_low_rank_term` factors `X*Y` through the low-rank leaf `X` (rather +than `Y`): `X` is a low-rank leaf, and `Y` is not one of smaller rank. +""" +_through_x(X, Y) = _is_low_rank(X) && !(_is_low_rank(Y) && _rank_of(Y) < _rank_of(X)) + +""" + _low_rank_term_rank(X, Y) + +The rank of the factors of `X*Y` computed by `_compute_low_rank_term`. +""" +_low_rank_term_rank(X, Y) = _through_x(X, Y) ? _rank_of(X) : _is_low_rank(Y) ? _rank_of(Y) : size(X, 2) + +""" + _compute_low_rank_term(X, Y, α[, buf]) + +Return factors `(A, B)` (matrices) such that `α*X*Y = A*B'`, where `X` or `Y` (an +`HMatrix` or its adjoint) is a low-rank leaf, or both are dense leaves (see +`_has_low_rank_form`). The factorization is exact: its rank (see +`_low_rank_term_rank`) is either the smallest rank of the low-rank factors, or the +size of the cluster shared by `X` and `Y`, which is a leaf when `X*Y` targets an +internal node. A factor of a low-rank leaf, or the dense data of `X`, is shared, not +copied. +""" +function _compute_low_rank_term(X, Y, α, buf = eltype(X)[]) + T, r = eltype(X), _low_rank_term_rank(X, Y) + # share the factor which `_compute_low_rank_term!` copies, and allocate the other + A, B = if _through_x(X, Y) + first(_rkfactors(data(X))), Matrix{T}(undef, size(Y, 2), r) + elseif _is_low_rank(Y) + Matrix{T}(undef, size(X, 1), r), last(_rkfactors(data(Y))) + else + d = data(X) + (d isa Matrix{T} ? d : Matrix{T}(undef, size(X, 1), r)), Matrix{T}(undef, size(Y, 2), r) + end + return _compute_low_rank_term!(A, B, X, Y, α, buf) +end + +""" + _compute_low_rank_term!(A, B, X, Y, α, buf) + +Like `_compute_low_rank_term`, but writing the factors into `A` and `B` (which may +already be the factors shared with `X` or `Y`), using the scratch vector `buf`. +""" +function _compute_low_rank_term!(A, B, X, Y, α, buf) + if _through_x(X, Y) # α*X*Y = U*(conj(α)*Y'*V)' + U, V = _rkfactors(data(X)) + A === U || copyto!(A, U) + _mul131!(fill!(B, zero(eltype(B))), adjoint(Y), V, conj(α), buf) + elseif _is_low_rank(Y) # α*X*Y = (α*X*U)*V' + U, V = _rkfactors(data(Y)) + _mul131!(fill!(A, zero(eltype(A))), X, U, α, buf) + B === V || copyto!(B, V) + else # both dense + @assert isleaf(X) && isleaf(Y) + A === data(X) || copyto!(A, data(X)) + B .= conj(α) .* adjoint(data(Y)) + end + return A, B +end + +############################################################################################ +# Factorizations and triangular solves +############################################################################################ + +""" + lu!(M::HMatrix, compressor; threads = true, executor) + +Hierarchical LU factorization of `M` in place, every update being deferred: each +admissible leaf of the factors is compressed exactly once, with `compressor` (e.g. +[`RandomizedSVD`](@ref) or [`PartialACA`](@ref)), from its Schur complement. The work +is parallelized with `threads = true` (when Julia runs on several threads), or run by +the given `executor` ([`ThreadsExecutor`](@ref) or [`SerialExecutor`](@ref)). + +`F \\ b` solves in the ordering of the points used to assemble `M`. The factors `F.L` +and `F.U` are stored in the ordering of the cluster trees, with +`F.L * (F.U * x) ≈ Matrix(M)[F.p, F.q] * x`; products and solves with them act in that ordering. + +The entries of `M` must be numbers. With `threads = true`, BLAS should run on a single +thread (`BLAS.set_num_threads(1)`), since the parallelism comes from the blocks. An error +raised by a threaded factorization is rethrown without the backtrace of the task which +raised it; `threads = false` gives the full backtrace. +""" +function LinearAlgebra.lu!(M::HMatrix, compressor; threads = true, executor = _executor(threads)) + d = LazyDriver(M, M, M, compressor; executor) + _run!(() -> _lu!(d, M), executor) + @assert isempty(d.pending) "updates left after the factorization" + return LU(M, Int[], 0) +end + +""" + lu!(M::HMatrix; atol, rank, rtol, block, threads = true) + +Hierarchical LU factorization of `M`, using the `RandomizedSVD(; atol, rank, rtol, block)` +compressor (see [`RandomizedSVD`](@ref)). +""" +function LinearAlgebra.lu!(M::HMatrix; threads = true, kwargs...) + return lu!(M, RandomizedSVD(; kwargs...); threads) +end + +""" + LinearAlgebra.lu(M::HMatrix,args...;kwargs...) + +Hierarchical LU factorization. See [`lu!`](@ref) for the available options. +""" +LinearAlgebra.lu(M::HMatrix, args...; kwargs...) = lu!(deepcopy(M), args...; kwargs...) + +""" + _lu!(d::LazyDriver, M::HMatrix) + +Driver of [`lu!`](@ref) for the diagonal block `M`: flush `M`, then factor it (dense +LU of a leaf), or recurse on its children, pushing the Schur complement updates. +""" +function _lu!(d, M::HMatrix) + flush!(d, M) + if isleaf(M) + spawn!(() -> lu!(data(M)::Matrix{eltype(M)}, NoPivot()), d.executor, (), (M,)) + return M + end + chdM = children(M) + n = size(chdM, 1) + for i in 1:n + _lu!(d, chdM[i, i]) + for j in (i + 1):n + _solve_lower!(d, UnitLowerTriangular(chdM[i, i]), chdM[i, j]) + _solve_upper!(d, chdM[j, i], UpperTriangular(chdM[i, i])) + end + for j in (i + 1):n, k in (i + 1):n + push!(d, chdM[j, k], chdM[j, i], chdM[i, k]) + end + end + return M +end + +""" + cholesky!(M::HermitianHMatrix, compressor; threads = true, executor) + +Hierarchical Cholesky factorization `M = U'U` in place, the factor being stored in +the upper triangle of `M`, which must hold the data of `M` (as for the `Hermitian` +assembled by [`assemble_hmatrix`](@ref)); an `ArgumentError` is thrown otherwise. As for +[`lu!`](@ref), every update is deferred, each admissible leaf of the factor is +compressed once, and the work is parallelized with `threads = true` or run by the given +`executor`. + +`F \\ b` solves in the ordering of the points used to assemble `M`. The factors `F.L` +and `F.U` are stored in the ordering of the cluster tree, with +`F.L * (F.U * x) ≈ Matrix(M)[F.p, F.p] * x`; products and solves with them act in that ordering. +""" +function LinearAlgebra.cholesky!(M::HermitianHMatrix, compressor; threads = true, executor = _executor(threads)) + M.uplo == 'U' || throw(ArgumentError("the data of `M` must be stored in its upper triangle")) + H = parent(M) + d = LazyDriver(H, adjoint(H), H, compressor; uplo = 'U', executor) + _run!(() -> _cholesky!(d, H), executor) + @assert isempty(d.pending) "updates left after the factorization" + return M |> UpperTriangular |> Cholesky +end + +""" + cholesky!(M::HermitianHMatrix; atol, rank, rtol, block, threads = true) + +Hierarchical Cholesky factorization of `M`, using the +`RandomizedSVD(; atol, rank, rtol, block)` compressor (see [`RandomizedSVD`](@ref)). +""" +function LinearAlgebra.cholesky!(M::HermitianHMatrix; threads = true, kwargs...) + return cholesky!(M, RandomizedSVD(; kwargs...); threads) +end + +""" + cholesky(M::HermitianHMatrix, args...; kwargs...) + +Hierarchical Cholesky factorization. See [`cholesky!`](@ref) for the available +options. +""" +function LinearAlgebra.cholesky(M::HermitianHMatrix, args...; kwargs...) + return cholesky!(deepcopy(M), args...; kwargs...) +end + +""" + _cholesky!(d::LazyDriver, M::HMatrix) + +Driver of [`cholesky!`](@ref) for the diagonal block `M` (whose upper triangle holds +the data): flush `M`, then factor it (dense Cholesky of a leaf), or recurse on its +children, solving for the blocks of the first block row and pushing the updates +`M[j,k] ← M[j,k] - M[i,j]'*M[i,k]` of the upper triangle. +""" +function _cholesky!(d, M::HMatrix) + flush!(d, M) + if isleaf(M) + spawn!(() -> cholesky!(Hermitian(data(M)::Matrix{eltype(M)}, :U), NoPivot()), d.executor, (), (M,)) + return M + end + chdM = children(M) + n = size(chdM, 1) + for i in 1:n + _cholesky!(d, chdM[i, i]) + for j in (i + 1):n + _solve_lower!(d, adjoint(UpperTriangular(chdM[i, i])), chdM[i, j]) + end + for j in (i + 1):n, k in j:n + push!(d, chdM[j, k], adjoint(chdM[i, j]), chdM[i, k]) + end + end + return M +end + +""" + _solve_lower!(d::LazyDriver, L::HLowerTriangular, X::HMatrix) + +`X ← L⁻¹X`: flush `X`, then solve with its data (a leaf), or recurse on its children +by block forward substitution, pushing the updates `X[j,k] ← X[j,k] - L[j,i]*X[i,k]` +(the coefficient of `d` is `-1`). `L` is a triangle of an `HMatrix` or of its adjoint +(e.g. `UnitLowerTriangular(D)` for an LU, `UpperTriangular(D)'` for a Cholesky +factorization), whose blocks are final. +""" +function _solve_lower!(d, L::HLowerTriangular, X::HMatrix) + flush!(d, X) + if isleaf(X) + spawn!(() -> ldiv!(L, data(X)), d.executor, (L,), (X,)) + return X + end + isleaf(parent(L)) && throw(ArgumentError("the triangular factor is a leaf but the right-hand side is not")) + chdL, chdX = children(parent(L)), children(X) + n = size(chdL, 1) + for k in axes(chdX, 2), i in 1:n + _solve_lower!(d, _wraptriangular(chdL[i, i], L), chdX[i, k]) + for j in (i + 1):n + push!(d, chdX[j, k], chdL[j, i], chdX[i, k]) + end + end + return X +end + +""" + _solve_upper!(d::LazyDriver, X::HMatrix, U::HUpperTriangular) + +`X ← XU⁻¹`; see `_solve_lower!`. +""" +function _solve_upper!(d, X::HMatrix, U::HUpperTriangular) + flush!(d, X) + if isleaf(X) + spawn!(d.executor, (U,), (X,)) do + R = data(X) + R isa RkMatrix ? with_buffer(buf -> rdiv!(R, U, buf.scratch), d) : rdiv!(R, U) + end + return X + end + isleaf(parent(U)) && throw(ArgumentError("the triangular factor is a leaf but the right-hand side is not")) + chdU, chdX = children(parent(U)), children(X) + n = size(chdU, 2) + for k in axes(chdX, 1), i in 1:n + _solve_upper!(d, chdX[k, i], _wraptriangular(chdU[i, i], U)) + for j in (i + 1):n + push!(d, chdX[k, j], chdX[k, i], chdU[i, j]) + end + end + return X +end diff --git a/src/lu.jl b/src/lu.jl index 3bebc09..8d1789f 100644 --- a/src/lu.jl +++ b/src/lu.jl @@ -21,63 +21,3 @@ function Base.show(io::IO, ::MIME"text/plain", LU::HLU) H = getfield(LU, :factors) # the underlying hierarchical matrix return println(io, "LU factorization of $H") end - -""" - lu!(M::HMatrix,comp) - -Hierarchical LU factorization of `M`, using `comp` to generate the compressed -blocks during the multiplication routines. - -`F \\ b` solves in the ordering of the points used to assemble `M`. The factors `F.L` -and `F.U` are stored in the ordering of the cluster trees, with -`F.L * (F.U * x) ≈ Matrix(M)[F.p, F.q] * x`; products and solves with them act in that ordering. - -The factorization is currently serial: `threads` is accepted but not used. -""" -function LinearAlgebra.lu!(M::HMatrix, compressor; threads = true) - # perform the lu decomposition of M in place - _lu!(M, compressor, _buffer_channel(compressor, eltype(M))) - # wrap the result in the LU structure - return LU(M, Int[], 0) -end - -""" - lu!(M::HMatrix; atol, rank, rtol, threads = true) - -Hierarchical LU factorization of `M`, using the `PartialACA(; atol, rank, rtol)` compressor. -""" -function LinearAlgebra.lu!(M::HMatrix; threads = true, kwargs...) - return lu!(M, PartialACA(; kwargs...); threads) -end - -""" - LinearAlgebra.lu(M::HMatrix,args...;kwargs...) - -Hierarchical LU factorization. See [`lu!`](@ref) for the available options. -""" -LinearAlgebra.lu(M::HMatrix, args...; kwargs...) = lu!(deepcopy(M), args...; kwargs...) - -function _lu!(M::HMatrix, compressor, bufs = nothing) - if isleaf(M) - d = data(M) - @assert d isa Matrix - lu!(d, NoPivot()) - else - @assert !hasdata(M) - chdM = children(M) - m, n = size(chdM) - for i in 1:m - _lu!(chdM[i, i], compressor, bufs) - for j in (i + 1):n - ldiv!(UnitLowerTriangular(chdM[i, i]), chdM[i, j], compressor, bufs) - rdiv!(chdM[j, i], UpperTriangular(chdM[i, i]), compressor, bufs) - end - for j in (i + 1):m - for k in (i + 1):n - _hmul_tree!(chdM[j, k], chdM[j, i], chdM[i, k], -1, 1, compressor, bufs) - end - end - end - end - return M -end diff --git a/src/multiplication.jl b/src/multiplication.jl index 2e22a97..a88f64a 100644 --- a/src/multiplication.jl +++ b/src/multiplication.jl @@ -1,243 +1,138 @@ """ - hmul!(C::HMatrix, A::HMatrix, B::HMatrix, a, b, compressor) + struct LeafOperator{T,M,V,S} <: AbstractMatrix{T} -Similar to `mul!` : compute `C <-- A*B*a + C*b`, where `A,B,C` are hierarchical -matrices and `compressor` is a function/functor used in the intermediate stages -of the multiplication to avoid growing the rank of admissible blocks after -addition is performed. - -The rows of `A` and `C`, the columns of `A` and the rows of `B`, and the columns of -`B` and `C` must be clustered in the same way (e.g. built from the same points); -otherwise an `ArgumentError` is thrown. -""" -function hmul!(C::Union{HMatrix, HermitianHMatrix}, A::HTypes, B::HTypes, a, b, compressor) - rowperm(C) == rowperm(A) && colperm(A) == rowperm(B) && colperm(B) == colperm(C) || - throw(ArgumentError("the factors of `hmul!` must be clustered consistently with each other and with the result")) - return _hmul_tree!(C, A, B, a, b, compressor) -end +The operator +``` + L = A * B' + α * ∑ᵢ Xᵢ * Yᵢ +``` +known through its rows and columns, or its products with blocks of vectors, where `(A, +B)` are low-rank factors (of type `M`), `(Xᵢ, Yᵢ)` are pairs of hierarchical matrices +(of type `V`), and `α` is a scalar. It is the value of an admissible leaf with its +deferred updates, which a compressor compresses once (see `_flush_low_rank_leaf!`): +`compressor(L, axes(L)..., buf)`, through `getblock!` (see [`PartialACA`](@ref)), or +`mul!` (see [`RandomizedSVD`](@ref)). -""" - _hmul_tree!(C, A, B, a, b, compressor, bufs = nothing, Cflag = 'N') + LeafOperator{T}(A, B, pairs, α, buffer = T[], rkbuffer = T[]) -Compute `C <-- A*B*a + C*b` in the ordering in which the H-matrices are stored, i.e. -as products of the stored blocks, whatever the points they come from. +The scratch vectors `buffer` and `rkbuffer` grow as needed, and can be reused (e.g. +taken from the workspace of a flush). """ -function _hmul_tree!( - C::T, - A::HTypes, - B::HTypes, - a, - b, - compressor, - bufs_ = nothing, - Cflag = 'N', - ) where {T <: HMatrix} - bufs = isnothing(bufs_) ? _buffer_channel(compressor, eltype(C)) : bufs_ - b == true || rmul!(C, b) - dict = IdDict{T, Vector{Tuple{eltype(children(A)), eltype(children(B))}}}() - _plan_dict!(dict, C, A, B, Cflag) - _hmul!(C, compressor, dict, a, nothing, bufs, Cflag) - return C -end - -function _hmul_tree!(C::HermitianHMatrix, A, B, a, b, compressor, bufs = nothing) - return _hmul_tree!(parent(C), A, B, a, b, compressor, bufs, C.uplo) +struct LeafOperator{T, M, V, S} <: AbstractMatrix{T} + A::M + B::M + pairs::Vector{V} + α::S + # scratch space for the intermediate vectors of the products `Xᵢ*(Yᵢ*x)`, and for + # the products with the low-rank leaves of `Xᵢ` + buffer::Vector{T} + rkbuffer::Vector{T} end -# a channel holding one buffer of `compressor` per thread -function _buffer_channel(compressor, T) - nt = Threads.nthreads() - bufs = [allocate_buffer(compressor, T) for _ in 1:nt] - chn = Channel{eltype(bufs)}(nt) - foreach(buf -> put!(chn, buf), bufs) - return chn +function LeafOperator{T}(A::M, B::M, pairs::Vector{V}, α::S, buffer = T[], rkbuffer = T[]) where {T, M, V, S} + return LeafOperator{T, M, V, S}(A, B, pairs, α, buffer, rkbuffer) end -function _plan_dict!(dict, C::T, A::HTypes, B::HTypes, Cflag) where {T <: HMatrix} - pairs = get!(dict, C, Tuple{T, T}[]) - if isleaf(A) || isleaf(B) || isleaf(C) - push!(pairs, (A, B)) - else - ni, nj = blocksize(C) - _, nk = blocksize(A) - A_children = children(A) - B_children = children(B) - C_children = children(C) - for i in 1:ni - for j in 1:nj - (Cflag == 'U' && (i > j)) && continue - (Cflag == 'L' && (j > i)) && continue - for k in 1:nk - _plan_dict!( - dict, - C_children[i, j], - A_children[i, k], - B_children[k, j], - i == j ? Cflag : 'N', - ) - end - end - end - end - return dict -end - -function _hmul!(C::HMatrix, compressor, dict, a, R, bufs, Cflag) - execute_node!(C, compressor, dict, a, R, bufs) - shift = offset(C) - C_children = children(C) - ni, nj = size(C_children) - for i in 1:ni - for j in 1:nj - (Cflag == 'U' && (i > j)) && continue - (Cflag == 'L' && (j > i)) && continue - chd = C_children[i, j] - irange = rowrange(chd) .- shift[1] - jrange = colrange(chd) .- shift[2] - Rp = data(C) - Rv = hasdata(C) ? RkMatrix(Rp.A[irange, :], Rp.B[jrange, :]) : nothing - _hmul!(chd, compressor, dict, a, Rv, bufs, i == j ? Cflag : 'N') - end - end - isleaf(C) || (setdata!(C, nothing)) - return C -end +Base.size(L::LeafOperator) = (size(L.A, 1), size(L.B, 1)) -# non-recursive execution -function execute_node!(C::HMatrix, compressor, dict, a, R, bufs) - T = typeof(C) - S = eltype(C) - pairs = get(dict, C, Tuple{T, T}[]) - isnothing(R) && isempty(pairs) && (return C) - if isleaf(C) && !isadmissible(C) - d = data(C)::Matrix{S} - for (A, B) in pairs - _mul_dense!(d, A, B, a) - end - isnothing(R) || mul!(d, R.A, adjoint(R.B), true, true) - else - L = MulLinearOp{S}(data(C), R, pairs, a) - buf = take!(bufs) - R = compressor(L, axes(L, 1), axes(L, 2), buf) - put!(bufs, buf) - setdata!(C, R) - end - return C +function Base.getindex(L::Union{LeafOperator, Adjoint{<:Any, <:LeafOperator}}, args...) + return error("calling `getindex` of a `LeafOperator` has been disabled") end """ - struct MulLinearOp{T,V,S} <: AbstractMatrix{T} - -Abstract matrix representing the following linear operator: -``` - L = R + P + a * ∑ᵢ Aᵢ * Bᵢ -``` -where `R` and `P` are of type `RkMatrix{T}`, `Aᵢ,Bᵢ` are of type `HMatrix{R,T}` -and `a` is scalar multiplier. Calling `compressor(L)` produces a low-rank -approximation of `L`, where `compressor` is an [`AbstractCompressor`](@ref). + _oriented(L::LeafOperator, ::Val{trans}) -Note: this structure is used to group the operations required when multiplying -hierarchical matrices so that they can later be executed in a way that minimizes -recompression of intermediate computations. +The low-rank factors and the coefficient of `L` (`trans = false`), or of its adjoint +`L' = B*A' + conj(α)*∑ᵢ Yᵢ'*Xᵢ'` (`trans = true`); see `_product`. """ -struct MulLinearOp{T, V, S} <: AbstractMatrix{T} - R::Union{RkMatrix{T}, Nothing} - P::Union{RkMatrix{T}, Nothing} - pairs::Vector{V} - multiplier::S -end +_oriented(L::LeafOperator, ::Val{false}) = (L.A, L.B, L.α) +_oriented(L::LeafOperator, ::Val{true}) = (L.B, L.A, conj(L.α)) -function MulLinearOp{T}(R, P, pairs::Vector{V}, multiplier::S) where {T, V, S} - return MulLinearOp{T, V, S}(R, P, pairs, multiplier) -end +""" + _product(X, Y, ::Val{trans}) -# AbstractMatrix interface -function Base.size(L::MulLinearOp) - isnothing(L.R) || (return size(L.R)) - isnothing(L.P) || (return size(L.P)) - isempty(L.pairs) && (return (0, 0)) - A, B = first(L.pairs) - return (size(A, 1), size(B, 2)) -end +The factors of the product `X*Y` (`trans = false`) or of its adjoint (`trans = true`). +""" +_product(X, Y, ::Val{false}) = (X, Y) +_product(X, Y, ::Val{true}) = (adjoint(Y), adjoint(X)) -function Base.getindex(L::Union{MulLinearOp, Adjoint{<:Any, <:MulLinearOp}}, args...) - return error("calling `getindex` of a `MulLinearOp` has been disabled") -end +""" + _operator_col!(col, L::LeafOperator, trans::Val, j) -function getcol!(col, L::MulLinearOp, j) +The column `j` of `L` (or of its adjoint, see `_oriented`), in `col`. +""" +function _operator_col!(col, L::LeafOperator, trans, j) fill!(col, zero(eltype(col))) - m, n = size(L) - T = eltype(L) - # compute j-th column of ∑ Aᵢ Bᵢ - for (A, B) in L.pairs - m, k = size(A) - k, n = size(B) - tmp = zeros(T, k) - jg = j + offset(B)[2] # global index on hierarchical matrix B - getcol!(tmp, B, jg) - _hgemv_recursive!(col, A, tmp, offset(A)) - end - # multiply the columns by a - a = L.multiplier - rmul!(col, a) - # add R and P (if they exist) - R = L.R - if !isnothing(R) - getcol!(col, R, j, Val(true)) - end - P = L.P - if !isnothing(P) - getcol!(col, P, j, Val(true)) + A, B, α = _oriented(L, trans) + for (X, Y) in L.pairs + X, Y = _product(X, Y, trans) + tmp = fill!(_scratch!(L.buffer, size(X, 2)), zero(eltype(L))) + getcol!(tmp, Y, j + offset(Y)[2]) + _hgemv_recursive!(col, X, tmp, offset(X), L.rkbuffer) end + rmul!(col, α) + _add_lowrank_col!(col, A, B, j, L.buffer) return col end -function getblock!(out, L::MulLinearOp, irange, j::Int) - @assert irange == 1:size(L, 1) - return getcol!(out, L, j) +""" + _add_lowrank_col!(col, A, B, j, buf) + +`col ← col + (A*B')[:, j]`, with the row `j` of `B` adjoined into the scratch vector +`buf`, so that the product is a matrix-vector product with `A` (BLAS for +numbers, which a view of `adjoint(B)` with complex entries does not reach). +""" +function _add_lowrank_col!(col, A, B, j, buf) + x = _scratch!(buf, size(B, 2)) + for k in eachindex(x) + x[k] = adjoint(B[j, k]) + end + return mul!(col, A, x, true, true) end # an entry costs a column -_can_sample(::MulLinearOp) = false +_can_sample(::LeafOperator) = false -# a block of whole columns, e.g. for a `TSVD` of the product -function getblock!(out, L::MulLinearOp, irange, jrange::AbstractVector) - for (jloc, j) in enumerate(jrange) - getblock!(view(out, :, jloc), L, irange, j) +function getblock!(out, L::LeafOperator, irange, j::Int) + @assert irange == 1:size(L, 1) + return _operator_col!(out, L, Val(false), j) +end +function getblock!(out, L::Adjoint{<:Any, <:LeafOperator}, irange, j::Int) + @assert irange == 1:size(L, 1) + return _operator_col!(out, parent(L), Val(true), j) +end +# a whole block (e.g. for `TSVD`), column after column +function getblock!(out::AbstractMatrix, L::LeafOperator, irange, J::AbstractVector{<:Integer}) + @assert irange == 1:size(L, 1) + for (t, j) in enumerate(J) + _operator_col!(view(out, :, t), L, Val(false), j) end return out end +""" + _mul!(out, L::LeafOperator, V, trans::Val) -function getcol!(col, adjL::Adjoint{<:Any, <:MulLinearOp}, j) - fill!(col, zero(eltype(col))) - L = parent(adjL) - T = eltype(L) - # compute j-th column of ∑ adjoint(Bᵢ)*adjoint(Aᵢ) - for (A, B) in L.pairs - At, Bt = adjoint(A), adjoint(B) - tmp = zeros(T, size(At, 1)) - jg = j + offset(At)[2] - getcol!(tmp, At, jg) - _hgemv_recursive!(col, Bt, tmp, offset(Bt)) - end - # multiply by a - a = L.multiplier - rmul!(col, conj(a)) - # add the j-th column of Ct if it has data - R = L.R - if !isnothing(R) - getcol!(col, adjoint(R), j, Val(true)) - end - P = L.P - if !isnothing(P) - getcol!(col, adjoint(P), j, Val(true)) +`out = L*V` (or `L'*V`, see `_oriented`), through the products of the hierarchical +matrices with the block of vectors `V`. +""" +function _mul!(out, L::LeafOperator, V, trans) + fill!(out, zero(eltype(out))) + A, B, α = _oriented(L, trans) + for (X, Y) in L.pairs + X, Y = _product(X, Y, trans) + tmp = fill!(_scratch!(L.buffer, (size(Y, 1), size(V, 2))), zero(eltype(L))) + _mul131!(tmp, Y, V, true, L.rkbuffer) + _mul131!(out, X, tmp, α, L.rkbuffer) end - return col + tmp = mul!(_scratch!(L.buffer, (size(B, 2), size(V, 2))), adjoint(B), V) + return mul!(out, A, tmp, true, true) end -function getblock!(out, L::Adjoint{<:Any, <:MulLinearOp}, irange, j::Int) - @assert irange == 1:size(L, 1) - return getcol!(out, L, j) +LinearAlgebra.mul!(out::Matrix, L::LeafOperator, V::Matrix) = _mul!(out, L, V, Val(false)) +LinearAlgebra.mul!(out::Matrix, L::Adjoint{<:Any, <:LeafOperator}, V::Matrix) = _mul!(out, parent(L), V, Val(true)) + +function (comp::RandomizedSVD)(L::LeafOperator, irange::AbstractRange, jrange::AbstractRange, buf = nothing) + @assert irange == axes(L, 1) && jrange == axes(L, 2) + return _randomized_svd(L, comp) end #= @@ -305,28 +200,19 @@ function _mul113!( return C end -function _mul121!( - C::Union{Matrix, SubArray, Adjoint}, - R::AdjRkOrRk, - M::Union{Matrix, SubArray, Adjoint}, - a::Number, - ) - U, V = _rkfactors(R) - return mul!(C, U, adjoint(V) * M, a, true) -end - function _mul131!( - C::Union{Matrix, SubArray, Adjoint}, + C::AbstractVecOrMat, H::HTypes, - M::Union{Matrix, SubArray, Adjoint}, + M::AbstractVecOrMat, a::Number, + buf = nothing, ) if isleaf(H) mat = data(H) if mat isa AdjOrMat mul!(C, mat, M, a, true) elseif mat isa AdjRkOrRk - _mul121!(C, mat, M, a) + _leaf_gemm!(C, mat, M, a, buf) else error("$(typeof(mat))") end @@ -337,11 +223,27 @@ function _mul131!( jrange = colrange(child) .- shift[2] Cview = view(C, irange, :) Mview = view(M, jrange, :) - _mul131!(Cview, child, Mview, a) + _mul131!(Cview, child, Mview, a, buf) end return C end +""" + _leaf_gemm!(C, R, M, a, buf) + +`C ← C + a*R*M` for a low-rank leaf `R`, with the intermediate product in the scratch +vector `buf` if one is given (and the entries are numbers). +""" +function _leaf_gemm!(C, R, M, a, buf) + U, V = _rkfactors(R) + return mul!(C, U, adjoint(V) * M, a, true) +end +function _leaf_gemm!(C, R::Union{RkMatrix{<:Number}, Adjoint{<:Any, <:RkMatrix{<:Number}}}, M, a, buf::Vector) + U, V = _rkfactors(R) + tmp = mul!(_scratch!(buf, (size(V, 2), Base.tail(size(M))...)), adjoint(V), M) + return mul!(C, U, tmp, a, true) +end + ############################################################################################ # Specializations on gemv: # The routines below provide specialized version of mul!(C,A,B,a,b) when `A` and @@ -411,7 +313,7 @@ function _mul_tree!(y, A, x, b, threads) if threads _hgemv_threads!(y, x, leaves(A), offset(A)) # threaded implementation else - _hgemv_recursive!(y, A, x, offset(A)) # serial implementation + _hgemv_recursive!(y, A, x, offset(A), promote_type(eltype(A), eltype(x))[]) # serial implementation end return y end @@ -435,27 +337,63 @@ function LinearAlgebra.mul!( end """ - _hgemv_recursive!(C,A,B,offset) + _hgemv_recursive!(C, A, B, offset[, buf]) -Internal function used to compute `C[I] <-- C[I] + A*B[J]` where `I = -rowrange(A) - offset[1]` and `J = rowrange(B) - offset[2]`. - -The `offset` argument is used on the caller side to signal if the original -hierarchical matrix had a `pivot` other than `(1,1)`. +`C[I] ← C[I] + A*B[J]`, where `I = rowrange(A) .- offset[1]` and `J = colrange(A) .- +offset[2]`: the vectors `B` and `C` are indexed relative to `offset` (e.g. the offset of +the block of which `A` is a descendant). The products with low-rank leaves use the +scratch vector `buf` if one is given (see `_leaf_gemv!`). """ -function _hgemv_recursive!(C::AbstractVector, A::Union{HTypes, HTriangular}, B::AbstractVector, offset) +function _hgemv_recursive!(C::AbstractVector, A::HTypes, B::AbstractVector, offset, buf = nothing) if isleaf(A) - irange = rowrange(A) .- offset[1] - jrange = colrange(A) .- offset[2] - d = data(A) - mul!(view(C, irange), d, view(B, jrange), 1, 1) + _leaf_gemv!(C, A, B, offset, buf) else for block in children(A) - _hgemv_recursive!(C, block, B, offset) + _hgemv_recursive!(C, block, B, offset, buf) + end + end + return C +end +# the children in the triangle, the diagonal ones being triangles themselves +function _hgemv_recursive!(C::AbstractVector, A::HTriangular, B::AbstractVector, offset, buf = nothing) + if isleaf(A) + _leaf_gemv!(C, A, B, offset, buf) + else + chd = children(parent(A)) + for j in axes(chd, 2), i in axes(chd, 1) + if i == j + _hgemv_recursive!(C, _wraptriangular(chd[i, i], A), B, offset, buf) + elseif A isa HLowerTriangular ? i > j : i < j + _hgemv_recursive!(C, chd[i, j], B, offset, buf) + end end end return C end +_leaf_gemv!(C, A, B, offset, buf) = _leaf_gemv!(view(C, rowrange(A) .- offset[1]), data(A), view(B, colrange(A) .- offset[2]), buf) + +""" + _leaf_gemv!(y, d, x, buf) + +`y ← y + d*x` for the data `d` of a leaf, with the intermediate product of a low-rank +leaf in the scratch vector `buf` if one is given (and the entries are numbers). +""" +_leaf_gemv!(y, d, x, buf) = mul!(y, d, x, 1, 1) +function _leaf_gemv!(y, R::Union{RkMatrix{<:Number}, Adjoint{<:Any, <:RkMatrix{<:Number}}}, x, buf::Vector) + U, V = _rkfactors(R) + tmp = mul!(_scratch!(buf, size(V, 2)), adjoint(V), x) + return mul!(y, U, tmp, 1, 1) +end + +""" + _scratch!(buf::Vector, k) + _scratch!(buf::Vector, sz::Tuple) + +The first `k` entries of `buf` (as a vector), or the first `prod(sz)` entries (as a +matrix of size `sz`), growing `buf` if needed. +""" +_scratch!(buf::Vector, k::Integer) = (length(buf) < k && resize!(buf, k); view(buf, 1:k)) +_scratch!(buf::Vector, sz::Tuple) = reshape(_scratch!(buf, prod(sz)), sz) function _hgemv_threads!(C::AbstractVector, B::AbstractVector, leaves, offset) acc = Threads.Atomic{Int}(1) @@ -466,13 +404,14 @@ function _hgemv_threads!(C::AbstractVector, B::AbstractVector, leaves, offset) @sync for _ in 1:np Threads.@spawn begin buf = zero(C) + scratch = promote_type(eltype(C), eltype(B))[] while true i = Threads.atomic_add!(acc, 1) i > nl && break leaf = leaves[i] irange = rowrange(leaf) .- offset[1] jrange = colrange(leaf) .- offset[2] - mul!(view(buf, irange), data(leaf), view(B, jrange), 1, 1) + _leaf_gemv!(view(buf, irange), data(leaf), view(B, jrange), scratch) end # add the local buffer to the global buffer @lock lck axpy!(true, buf, C) @@ -488,6 +427,8 @@ function LinearAlgebra.rmul!(R::RkMatrix, b::Number) else rmul!(R.A, b) end + # scaling a factor keeps its columns orthogonal, and scales the errors + R.truncation_error .*= abs(b) return R end @@ -501,3 +442,49 @@ function LinearAlgebra.rmul!(H::HMatrix, b::Number) end return H end + +""" + hmul!(C::HMatrix, A, B, a, b, compressor; executor = SerialExecutor()) + +Similar to `mul!` : compute `C <-- A*B*a + C*b`, where `A,B,C` are hierarchical +matrices (`A` and `B` possibly adjoints, `C` possibly a `Hermitian`, of which only +the stored triangle is updated). Every admissible leaf of `C` is compressed once, +with `compressor`, from its data and all the products which reach it (see +[`LazyDriver`](@ref)), the numeric work being run by `executor`. + +The rows of `A` and `C`, the columns of `A` and the rows of `B`, and the columns of +`B` and `C` must be clustered in the same way (e.g. built from the same points); +otherwise an `ArgumentError` is thrown. +""" +function hmul!(C::Union{HMatrix, HermitianHMatrix}, A, B, a, b, compressor; kwargs...) + rowperm(C) == rowperm(A) && colperm(A) == rowperm(B) && colperm(B) == colperm(C) || + throw(ArgumentError("the factors of `hmul!` must be clustered consistently with each other and with the result")) + return _hmul_tree!(C, A, B, a, b, compressor; kwargs...) +end + +""" + _hmul_tree!(C, A, B, a, b, compressor; uplo = 'N', executor = SerialExecutor()) + +Like [`hmul!`](@ref), in the ordering in which the H-matrices are stored, i.e. as +products of the stored blocks, whatever the points they come from. With `uplo = 'U'` +(or `'L'`), only the upper (or lower) triangle of the diagonal blocks of `C` is updated. +""" +function _hmul_tree!( + C::HMatrix, A::Union{HMatrix, AdjointHMatrix}, B::Union{HMatrix, AdjointHMatrix}, a, b, compressor; + uplo = 'N', executor = SerialExecutor(), + ) + b == true || rmul!(C, b) + d = LazyDriver(C, A, B, compressor; α = a, uplo, executor) + _run!(executor) do + push!(d, C, A, B) + flush_tree!(d, C) + end + return C +end +function _hmul_tree!(C::HermitianHMatrix, A, B, a, b, compressor; kwargs...) + _hmul_tree!(parent(C), A, B, a, b, compressor; uplo = C.uplo, kwargs...) + return C +end +function _hmul_tree!(C, A, B, a, b, compressor; kwargs...) + throw(ArgumentError("the factors of `hmul!` must be `HMatrix`s or their adjoints")) +end diff --git a/src/rkmatrix.jl b/src/rkmatrix.jl index e68c076..0bb209d 100644 --- a/src/rkmatrix.jl +++ b/src/rkmatrix.jl @@ -3,21 +3,90 @@ Representation of a rank `r` matrix `M` in outer product format `M = A*adjoint(B)` where `A` has size `m × r` and `B` has size `n × r`. + +Two additional fields describe the factors, when this information is available: + +- `orthogonality::Symbol`: which factors have mutually orthogonal columns: `:none`, + `:A`, `:B`, or `:AB` (e.g. a truncated SVD, `A = U*Σ` and `B = V`). +- `truncation_error::Vector{Float64}`: `truncation_error[i]` is an estimate of + the Frobenius norm of the error made by keeping only the first `i` columns of + the factors (the last entry estimates the error of `R` itself). It is exact + (up to rounding) for a truncated SVD of an exact matrix, and an estimate + otherwise (e.g. the error of a [`PartialACA`](@ref), combined with the one of its + recompression). An empty vector means that no estimate is available. + +Constructing an `RkMatrix` from `A` and `B` only, or assigning `R.A` or `R.B`, +resets these fields to `:none` and `Float64[]`. """ mutable struct RkMatrix{T} <: AbstractMatrix{T} A::Matrix{T} B::Matrix{T} - function RkMatrix(A::Matrix{T}, B::Matrix{T}) where {T} + orthogonality::Symbol + truncation_error::Vector{Float64} + function RkMatrix( + A::Matrix{T}, B::Matrix{T}, orthogonality::Symbol = :none, + truncation_error::Vector{Float64} = Float64[], + ) where {T} @assert size(A, 2) == size(B, 2) "second dimension of `A` and `B` must match" + @assert orthogonality in (:none, :A, :B, :AB) "unknown orthogonality $orthogonality" m, r = size(A) n = size(B, 1) if r * (m + n) >= m * n @debug "Inefficient RkMatrix:" size(A) size(B) end - return new{T}(A, B) + return new{T}(A, B, orthogonality, truncation_error) + end +end + +# assigning a factor invalidates what is known about the factors +function Base.setproperty!(R::RkMatrix, s::Symbol, x) + setfield!(R, s, convert(fieldtype(typeof(R), s), x)) + if s === :A || s === :B + setfield!(R, :orthogonality, :none) + setfield!(R, :truncation_error, Float64[]) end + return R end +""" + _modified_factor!(R::RkMatrix, s::Symbol) + +Update what is known about the factors of `R` after the factor `s` (`:A` or +`:B`) was modified in place: the other factor keeps its orthogonality, and the +truncation errors are no longer known. +""" +function _modified_factor!(R::RkMatrix, s::Symbol) + o = R.orthogonality + other = s === :A ? :B : :A + R.orthogonality = (o === :AB || o === other) ? other : :none + R.truncation_error = Float64[] + return R +end + +""" + _svd_truncation_error(S, r, prior = 0.0) + +The truncation errors (in the Frobenius norm) of a truncated SVD with singular values +`S`, keeping `r` of them, of a matrix which was itself known up to an error `prior`. +""" +function _svd_truncation_error(S, r, prior = 0.0) + tail = sqrt(sum(abs2, view(S, (r + 1):length(S)); init = zero(real(eltype(S))))) + err = Vector{Float64}(undef, r) + acc = abs2(tail) + abs2(prior) + for i in r:-1:1 + err[i] = sqrt(acc) + acc += abs2(S[i]) + end + return err +end + +""" + _error_estimate(R::RkMatrix) + +The estimated error of `R` itself (zero if unknown). +""" +_error_estimate(R::RkMatrix) = isempty(R.truncation_error) ? 0.0 : last(R.truncation_error) + function Base.show(io::IO, ::MIME"text/plain", R::RkMatrix) return print( io, @@ -52,23 +121,16 @@ _rkfactors(R::RkMatrix) = (R.A, R.B) _rkfactors(adjR::AdjRk) = (parent(adjR).B, parent(adjR).A) """ - getcol!(col, R, j[, Val(add)]) + getcol!(col, R, j) -Fill `col` with column `j` of the low-rank matrix `R`, or add it to `col` if `add` is -`true`. +Fill `col` with column `j` of the low-rank matrix `R`. """ -function getcol!(col, R::AdjRkOrRk, j::Int, ::Val{T} = Val(false)) where {T} - # NOTE: using a `Val` argument to dispatch on the type of `T` is important - # for performance +function getcol!(col, R::AdjRkOrRk, j::Int) U, V = _rkfactors(R) - return if T - mul!(col, U, view(adjoint(V), :, j), true, true) - else - mul!(col, U, view(adjoint(V), :, j)) - end + return mul!(col, U, view(adjoint(V), :, j)) end -Base.copy(R::RkMatrix) = RkMatrix(copy(R.A), copy(R.B)) +Base.copy(R::RkMatrix) = RkMatrix(copy(R.A), copy(R.B), R.orthogonality, copy(R.truncation_error)) Base.size(rmat::RkMatrix) = (size(rmat.A, 1), size(rmat.B, 1)) function Base.isapprox(rmat::RkMatrix, B::AbstractArray, args...; kwargs...) @@ -112,6 +174,3 @@ function LinearAlgebra.mul!( end return C end - -# scalar multiplication -Base.:*(a::Number, R::RkMatrix) = (A = a * R.A; B = copy(R.B); RkMatrix(A, B)) diff --git a/src/thread_executor.jl b/src/thread_executor.jl new file mode 100644 index 0000000..962af1a --- /dev/null +++ b/src/thread_executor.jl @@ -0,0 +1,266 @@ +""" + SerialExecutor() + +Executor running every piece of work immediately, in the calling task: with +`executor = SerialExecutor()`, the algorithms which take an `executor` (e.g. +[`lu!`](@ref), [`cholesky!`](@ref)) run sequentially, as with `threads = false`. +""" +struct SerialExecutor end + +spawn!(work, ::SerialExecutor, reads, writes) = (work(); nothing) +Base.wait(::SerialExecutor) = nothing + +""" + mutable struct ExecutorTask + +A piece of work of a [`ThreadsExecutor`](@ref), with the number of its unfinished +dependencies (one more while it is being spawned, so that it does not run before), +and the pieces of work depending on it. `work === nothing` for a join. +""" +mutable struct ExecutorTask + work::Any + @atomic number_of_unfinished_dependencies::Int + const lock::Threads.SpinLock # protects `is_done` and `successors` + is_done::Bool + successors::Vector{ExecutorTask} +end +ExecutorTask(work) = ExecutorTask(work, 1, Threads.SpinLock(), false, ExecutorTask[]) + +""" + ThreadsExecutor(; check_accesses = false) + +Executor running pieces of work as tasks on Julia's threads, each one waiting only for +the last piece of work which wrote each of the objects it reads or writes: with +`executor = ThreadsExecutor()`, the algorithms which take an `executor` (e.g. +[`lu!`](@ref), [`cholesky!`](@ref)) run in parallel, as with `threads = true`. An error +raised by a piece of work is rethrown as is, without the backtrace of its task; running +sequentially (see [`SerialExecutor`](@ref)) gives the full backtrace. + +`spawn!(work, ex, reads, writes)` registers `work()`, which reads the objects of +`reads` and modifies those of `writes`, and `wait(ex)` returns once all the work +spawned is done, then forgets it, and rethrows the first error of a piece of work. + +There is no general dependency analysis: the executor only keeps the last writer of +every object, which is enough for drivers satisfying the following access pattern: +- an object is written by a sequence of pieces of work, which are run in the order + in which they are spawned; +- an object is only read once final, i.e. after its last write has been spawned, so + that there are no write-after-read hazards. +The objects written are leaves of an `HMatrix`, or other objects (e.g. a low-rank +term computed by one piece of work and read by others). A read of an internal block +of an `HMatrix` is a read of all its leaves: it waits for a join over the last +writers of its leaves, created at its first read and reused afterwards. With +`check_accesses = true`, the executor checks this access pattern: that no object is +written after it, or an internal block containing it, was read. + +A piece of work never blocks: it counts its unfinished dependencies, and is spawned +as a task by the piece of work completing the last of them. The objects are +identified by their `objectid`, so that the executor does not keep them alive. +""" +mutable struct ThreadsExecutor + const last_writers::Dict{UInt, Union{Nothing, ExecutorTask}} # by objectid + const read_objects::Base.IdSet{Any} # kept only if `check_accesses` + const check_accesses::Bool + const number_of_unfinished_tasks::Threads.Atomic{Int} + const all_done::Threads.Condition + @atomic exception::Any # the first error of a piece of work +end +function ThreadsExecutor(; check_accesses = false) + return ThreadsExecutor( + Dict{UInt, Union{Nothing, ExecutorTask}}(), Base.IdSet{Any}(), check_accesses, Threads.Atomic{Int}(0), + Threads.Condition(), nothing, + ) +end + +""" + _stored(x) + +The object which an access to `x` reads or writes: the `HMatrix` underlying an +adjoint, a `Hermitian` or a triangle of one, and `x` itself otherwise. +""" +_stored(x) = x +_stored(x::Union{Adjoint, Hermitian, HTriangular}) = _stored(parent(x)) + +_isinternal(x) = x isa HMatrix && !isleaf(x) + +function spawn!(work, ex::ThreadsExecutor, reads, writes) + for x in writes + x = _stored(x) + _isinternal(x) && throw(ArgumentError("a piece of work writes an internal block of an HMatrix")) + ex.check_accesses && _check_write(ex, x) + end + task = _new_task!(ex, work) + for x in reads + x = _stored(x) + ex.check_accesses && push!(ex.read_objects, x) + _add_dependency!(task, _last_writer!(ex, x)) + end + for x in writes + x = _stored(x) + _add_dependency!(task, _last_writer!(ex, x)) + ex.last_writers[objectid(x)] = task + end + _release!(ex, task) + return nothing +end + +function Base.wait(ex::ThreadsExecutor) + @lock ex.all_done while ex.number_of_unfinished_tasks[] > 0 + wait(ex.all_done) + end + empty!(ex.last_writers) + empty!(ex.read_objects) + exception = @atomicswap ex.exception = nothing + isnothing(exception) || throw(exception) + return nothing +end + +function _new_task!(ex::ThreadsExecutor, work) + Threads.atomic_add!(ex.number_of_unfinished_tasks, 1) + return ExecutorTask(work) +end + +""" + _last_writer!(ex::ThreadsExecutor, x) + +The piece of work after which `x` is up to date, if any. A read of an internal block +of an `HMatrix`, which is final, waits for a join over the last writers of its +leaves, created once. +""" +function _last_writer!(ex::ThreadsExecutor, x) + key = objectid(x) + haskey(ex.last_writers, key) && return ex.last_writers[key] + _isinternal(x) || return nothing + writers = [ex.last_writers[objectid(leaf)] for leaf in leaves(x) if haskey(ex.last_writers, objectid(leaf))] + join = nothing + if !isempty(writers) + join = _new_task!(ex, nothing) + foreach(w -> _add_dependency!(join, w), writers) + _release!(ex, join) + end + return ex.last_writers[key] = join +end + +""" + _check_write(ex::ThreadsExecutor, x) + +Throw an error if `x`, or an internal block of an `HMatrix` containing it, was already +read: its readers would not wait for this write. +""" +function _check_write(ex::ThreadsExecutor, x) + node = x + while true + node in ex.read_objects && error("an object is written after it, or a block containing it, was read") + node isa HMatrix && !isroot(node) || return nothing + node = parentnode(node) + end + return +end + +""" + _add_dependency!(task::ExecutorTask, dependency) + +Make `task` wait for `dependency` (an `ExecutorTask`, or `nothing`), unless it is +done. +""" +function _add_dependency!(task::ExecutorTask, dependency) + (isnothing(dependency) || dependency === task) && return task + @lock dependency.lock if !dependency.is_done + @atomic task.number_of_unfinished_dependencies += 1 + push!(dependency.successors, task) + end + return task +end + +""" + _release!(ex::ThreadsExecutor, task::ExecutorTask) + +Decrement the number of unfinished dependencies of `task`, and run it once it +reaches zero: a join is finished at once, the other pieces of work are spawned as +tasks. +""" +function _release!(ex::ThreadsExecutor, task::ExecutorTask) + (@atomic task.number_of_unfinished_dependencies -= 1) == 0 || return nothing + isnothing(task.work) ? _finish!(ex, task) : Threads.@spawn(_execute!($ex, $task)) + return nothing +end + +""" + _execute!(ex::ThreadsExecutor, task::ExecutorTask) + +Run the work of `task`, recording its error if it throws, then release the pieces of +work depending on it. +""" +function _execute!(ex::ThreadsExecutor, task::ExecutorTask) + try + task.work() + catch e + @atomicreplace ex.exception nothing => e + end + # a finished piece of work must not keep alive what its work captured (e.g. low-rank terms) + task.work = nothing + return _finish!(ex, task) +end + +function _finish!(ex::ThreadsExecutor, task::ExecutorTask) + successors = @lock task.lock begin + task.is_done = true + s, task.successors = task.successors, ExecutorTask[] + s + end + foreach(s -> _release!(ex, s), successors) + # under the lock, so that `wait` cannot miss the notification between its check and its wait + Threads.atomic_sub!(ex.number_of_unfinished_tasks, 1) == 1 && @lock ex.all_done notify(ex.all_done) + return nothing +end + +""" + _executor(threads::Bool) + +The default executor: a [`ThreadsExecutor`](@ref) if `threads` and Julia runs on +several threads, and a [`SerialExecutor`](@ref) otherwise. +""" +_executor(threads::Bool) = threads && Threads.nthreads() > 1 ? ThreadsExecutor() : SerialExecutor() + +""" + _run!(driver, executor) + +Run `driver()`, which spawns work on `executor`, then wait for this work, also when +the driver throws, so that no work outlives the call. +""" +function _run!(driver, executor) + result = try + driver() + catch + try + wait(executor) + catch + end + rethrow() + end + wait(executor) + return result +end + +""" + workspaces(T) + +An empty pool of workspaces of type `T`, for [`with_workspace`](@ref). +""" +workspaces(T) = Base.Lockable(T[], Threads.SpinLock()) + +""" + with_workspace(f, pool, make) + +`f(w)` with a workspace `w` used by no other piece of work at the same time: taken from +`pool` (see [`workspaces`](@ref)), or made by `make()` if the pool is empty, then put +back in `pool`. A piece of work never waits for a workspace, and the pool grows to the +number of pieces of work running at the same time. +""" +function with_workspace(f, pool, make) + w = @lock pool (isempty(pool[]) ? nothing : pop!(pool[])) + w = isnothing(w) ? make() : w + result = f(w) + @lock pool push!(pool[], w) + return result +end diff --git a/src/triangular.jl b/src/triangular.jl index 38e015a..8cebe95 100644 --- a/src/triangular.jl +++ b/src/triangular.jl @@ -35,7 +35,8 @@ function children(T::HTriangular) end return v end -isleaf(H::HTriangular) = isempty(children(H)) +# the diagonal children of an internal node are always in the triangle +isleaf(H::HTriangular) = isleaf(parent(H)) hasdata(t::HTriangular) = hasdata(parent(t)) @@ -46,6 +47,16 @@ end Base.show(io::IO, ::MIME"text/plain", tri::HTriangular) = show(io, tri) function LinearAlgebra.ldiv!(L::HLowerTriangular, B::AbstractVecOrMat) + return _ldiv!(L, B, promote_type(eltype(L), eltype(B))[]) +end + +""" + _ldiv!(L::HLowerTriangular, B, buf) + +`B ← L⁻¹B` by block forward substitution, with the products with the low-rank blocks +of `L` in the scratch vector `buf` (see `_leaf_gemm!`). +""" +function _ldiv!(L::HLowerTriangular, B, buf) H = parent(L) if isleaf(H) d = data(H) @@ -62,10 +73,10 @@ function LinearAlgebra.ldiv!(L::HLowerTriangular, B::AbstractVecOrMat) for j in 1:(i - 1) # ji jrows = colrange(chdH[i, j]) .- shift[2] bj = selectdim(B, 1, jrows) - _mul131!(bi, chdH[i, j], bj, -1) + _mul131!(bi, chdH[i, j], bj, -1, buf) end # recursion stage - ldiv!(_wraptriangular(chdH[i, i], U), bi) + _ldiv!(_wraptriangular(chdH[i, i], U), bi, buf) end end return B end -# 1.3 function LinearAlgebra.rdiv!(B::StridedMatrix, U::HUpperTriangular) H = parent(U) if isleaf(H) d = data(H) - rdiv!(B, _wraptriangular(d, U)) # b <-- b/L + rdiv!(B, _wraptriangular(d, U)) # B <-- B/U else @assert !hasdata(H) "only leaves are allowed to have data when using `rdiv`!" shift = reverse(offset(H)) @@ -154,34 +148,41 @@ function LinearAlgebra.rdiv!(B::StridedMatrix, U::HUpperTriangular) return B end -# 2.3 -function LinearAlgebra.rdiv!(R::RkMatrix, U::HUpperTriangular) - Bt = rdiv!(Matrix(adjoint(R.B)), U) - adjoint!(R.B, Bt) - return R +""" + rdiv!(R::RkMatrix, U::HUpperTriangular[, buf::Vector]) + +`R ← R*U⁻¹`, forming the transposed factor in the scratch vector `buf` (grown if +needed). +""" +function LinearAlgebra.rdiv!(R::RkMatrix, U::HUpperTriangular, buf::Vector = eltype(R)[]) + Bt = adjoint!(_scratch!(buf, reverse(size(R.B))), R.B) + adjoint!(R.B, rdiv!(Bt, U)) + return _modified_factor!(R, :B) end -# 3.3 -function LinearAlgebra.rdiv!(X::HMatrix, U::HUpperTriangular, compressor, bufs = nothing) - H = parent(U) - if isleaf(X) - d = data(X) - rdiv!(d, U) # b <-- b/L - elseif isleaf(H) - error("the triangular factor is a leaf but the left-hand side is not") - else - @assert !hasdata(H) # only leaves are allowed to have data for the inversion - chdX = children(X) - chdH = children(H) - m, n = size(chdH) - for k in 1:size(chdX, 1) - for i in 1:m - for j in 1:(i - 1) - _hmul_tree!(chdX[k, i], chdX[k, j], chdH[j, i], -1, 1, compressor, bufs) - end - rdiv!(chdX[k, i], _wraptriangular(chdH[i, i], U), compressor, bufs) - end - end - end +""" + hldiv!(L::HLowerTriangular, X::HMatrix, compressor; executor = SerialExecutor()) + +`X ← L⁻¹X` for a triangle `L` of an `HMatrix` (or of its adjoint), compressing +every admissible leaf of `X` once with `compressor` (see [`LazyDriver`](@ref)), the +numeric work being run by `executor`. +""" +function hldiv!(L::HLowerTriangular, X::HMatrix, compressor; executor = SerialExecutor()) + d = LazyDriver(X, _checkblocks(parent(L)), X, compressor; executor) + _run!(() -> _solve_lower!(d, L, X), executor) return X end + +""" + hrdiv!(X::HMatrix, U::HUpperTriangular, compressor; executor = SerialExecutor()) + +`X ← XU⁻¹` for a triangle `U` of an `HMatrix` (or of its adjoint); see [`hldiv!`](@ref). +""" +function hrdiv!(X::HMatrix, U::HUpperTriangular, compressor; executor = SerialExecutor()) + d = LazyDriver(X, X, _checkblocks(parent(U)), compressor; executor) + _run!(() -> _solve_upper!(d, X, U), executor) + return X +end + +_checkblocks(H::Union{HMatrix, AdjointHMatrix}) = H +_checkblocks(H) = throw(ArgumentError("triangular solves with an `HMatrix` need a triangle of an `HMatrix` or of its adjoint")) diff --git a/test/Project.toml b/test/Project.toml index e852c99..1ca303c 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -1,6 +1,7 @@ [deps] ComputationalResources = "ed09eef8-17a6-5b46-8889-db040fac31e3" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +Logging = "56ddb016-857b-54e1-b83d-db4d58db5568" LoopVectorization = "bdcacae8-1622-11e9-2a5c-532679323890" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" SafeTestsets = "1bc83da4-3b8d-516f-aca4-4fe02f6d838f" diff --git a/test/api_test.jl b/test/api_test.jl index 295124a..20d78fe 100644 --- a/test/api_test.jl +++ b/test/api_test.jl @@ -9,9 +9,9 @@ public_names = filter(n -> Base.ispublic(HMatrices, n) && !Base.isexported(HMatr [ :ClusterTree, :AbstractSplitter, :GeometricSplitter, :CardinalitySplitter, :PrincipalComponentSplitter, :HyperRectangle, :StrongAdmissibilityStd, - :WeakAdmissibilityStd, :AbstractCompressor, :PartialACA, :TSVD, + :WeakAdmissibilityStd, :AbstractCompressor, :PartialACA, :TSVD, :RandomizedSVD, :allocate_buffer, :getblock!, :rowperm, :colperm, :center, - :rowelements, :colelements, + :rowelements, :colelements, :ThreadsExecutor, :SerialExecutor, ] ) for n in union(exported, public_names) diff --git a/test/cholesky_test.jl b/test/cholesky_test.jl index eec555a..c9495de 100644 --- a/test/cholesky_test.jl +++ b/test/cholesky_test.jl @@ -25,7 +25,7 @@ adm = StrongAdmissibilityStd(3) comp = PartialACA(; atol = 1.0e-10) for threads in (false, true) H = assemble_hmatrix(Hermitian(K), Xclt, Yclt; adm, comp, threads) - hchol = cholesky(H; atol = 1.0e-10) + hchol = cholesky(H; atol = 1.0e-10, threads) y = rand(m) M = Matrix(K) exact = M \ y @@ -45,3 +45,38 @@ for threads in (false, true) hchol = cholesky(H, PartialACA(; atol = 1.0e-10, recompress = true)) @test norm(exact - hchol \ y) < 1.0e-7 * norm(exact) end + +@testset "shift, single precision and complex entries" begin + n = 1500 + S = single_layer_sphere(n) + X = S.X + y = rand(n) + # a real shift of a `Hermitian` is a `Hermitian` + H = assemble_hmatrix(Hermitian(S); rtol = 1.0e-10, threads = false) + Hs = H + 2I + @test Hs isa HMatrices.HermitianHMatrix && 2I + H isa HMatrices.HermitianHMatrix + M = Matrix(S) + @test norm(Matrix(Hs) - (M + 2I)) < 1.0e-8 * norm(M) + @test norm(Matrix(H) - M) < 1.0e-8 * norm(M) + exact = (M + 2I) \ y + @test norm(cholesky(Hs; atol = 1.0e-10) \ y - exact) < 1.0e-7 * norm(exact) + # single precision + K32 = KernelMatrix((x, y) -> Float32(S.f(x, y)), X, X) + H32 = assemble_hmatrix(Hermitian(K32); rtol = 1.0e-5, threads = false) + y32 = Float32.(y) + exact = Matrix(K32) \ y32 + for threads in (false, true) + F = cholesky(H32; rtol = 1.0e-5, threads) + @test eltype(F.factors) == Float32 + @test norm(F \ y32 - exact) < 1.0e-3 * norm(exact) + end + # complex entries: `D*S*D'` with `D` diagonal and unitary is Hermitian positive definite + Kc = KernelMatrix((x, y) -> S.f(x, y) * cis(x[1] - y[1]), X, X) + Hc = assemble_hmatrix(Hermitian(Kc); rtol = 1.0e-10, threads = false) + b = rand(ComplexF64, n) + exact = Matrix(Kc) \ b + for threads in (false, true) + F = cholesky(Hc; atol = 1.0e-10, threads) + @test norm(F \ b - exact) < 1.0e-7 * norm(exact) + end +end diff --git a/test/compressor_test.jl b/test/compressor_test.jl index c384bae..e08475e 100644 --- a/test/compressor_test.jl +++ b/test/compressor_test.jl @@ -5,6 +5,7 @@ using LinearAlgebra using HMatrices: PartialACA, TSVD, + RandomizedSVD, RkMatrix, VectorOfVectors, allocate_buffer @@ -23,12 +24,13 @@ Random.seed!(1) M = Matrix(K) irange, jrange = 1:m, 1:n @testset "aca_partial" begin + # the ACA alone (see below for its recompression) atol = 1.0e-5 - aca = PartialACA(; atol = atol) + aca = PartialACA(; atol) R = aca(M, irange, jrange) @test norm(Matrix(R) - M) < atol rtol = 1.0e-5 - aca = PartialACA(; rtol = rtol) + aca = PartialACA(; rtol) R = aca(M, irange, jrange) @test norm(Matrix(R) - M) < rtol * norm(M) r = 10 @@ -43,7 +45,7 @@ Random.seed!(1) Z = zero(M) Z[:, 1] .= 1 R = @test_logs aca(Z, irange, jrange) - @test Matrix(R) == Z + @test Matrix(R) ≈ Z # rows much smaller than the others: the next row is taken from the residual # column, not by scanning the rows @@ -100,7 +102,16 @@ Random.seed!(1) atol = 1.0e-5 comp = PartialACA(; atol, recompress = true) R = comp(M, irange, jrange) - @test norm(Matrix(R) - M) < 5 * atol + @test norm(Matrix(R) - M) < 2 * atol + # the truncation drops the most singular values whose Frobenius norm is below the + # tolerance (only the first one with the spectral norm) + S = [1.0, 0.3, 0.3, 0.3] + @test HMatrices._truncation_rank(S, 0.5, nothing, typemax(Int)) == 2 + @test HMatrices._truncation_rank(S, 0.0, 0.4, typemax(Int)) == 2 # rtol is relative to norm(S) + @test HMatrices._truncation_rank(S, 0.5, nothing, 1) == 1 + R0 = RkMatrix(rand(T, 50, 8), rand(T, 40, 8)) + R1 = HMatrices.compress!(copy(R0), TSVD(; atol = 0.1 * norm(Matrix(R0)))) + @test norm(Matrix(R1) - Matrix(R0)) <= 0.1 * norm(Matrix(R0)) # accuracy: rtol rtol = 1.0e-5 comp = PartialACA(; rtol, recompress = true) @@ -136,13 +147,12 @@ Random.seed!(1) atol = 1.0e-5 tsvd = TSVD(; atol = atol) R = tsvd(M, irange, jrange) - # the inequality below is guaranteed to be true for the spectral norm - # i.e. (the `opnorm` with `p=2`). - @test opnorm(Matrix(R) - M) < atol + # guaranteed in the Frobenius norm (up to rounding) + @test norm(Matrix(R) - M) <= atol rtol = 1.0e-5 tsvd = TSVD(; rtol = rtol) R = tsvd(M, irange, jrange) - @test opnorm(Matrix(R) - M) < rtol * opnorm(M) + @test norm(Matrix(R) - M) <= rtol * norm(M) r = 10 tsvd = TSVD(; rank = r) R = tsvd(M, irange, jrange) @@ -157,7 +167,7 @@ Random.seed!(1) # every singular value is below the tolerance: truncate to rank zero small = 1.0e-12 * M R = RkMatrix(1.0e-12 * rand(T, m, 3), rand(T, n, 3)) - for comp in (TSVD(; atol = 1.0e-6), PartialACA(; atol = 1.0e-6, recompress = true)) + for comp in (TSVD(; atol = 1.0e-6), PartialACA(; atol = 1.0e-6, recompress = true), RandomizedSVD(; atol = 1.0e-6)) @test rank(comp(small)) == 0 @test rank(comp(zero(M))) == 0 end @@ -169,21 +179,21 @@ Random.seed!(1) @testset "single precision" begin M32 = ComplexF32.(M) # the default tolerance follows the precision of the entries - for comp in (PartialACA(), TSVD(), PartialACA(; recompress = true)) + for comp in (PartialACA(), TSVD(), PartialACA(; recompress = true), RandomizedSVD()) R = comp(M32) @test eltype(R) == ComplexF32 @test rank(R) < 20 @test norm(Matrix(R) - M32) < 1.0e-3 * norm(M32) end # a tolerance that cannot be reached is an error, not a full-rank block - for comp in (PartialACA(; rtol = 1.0e-8), TSVD(; rtol = 1.0e-8), PartialACA(; rtol = 1.0e-8, recompress = true)) + for comp in (PartialACA(; rtol = 1.0e-8), TSVD(; rtol = 1.0e-8), PartialACA(; rtol = 1.0e-8, recompress = true), RandomizedSVD(; rtol = 1.0e-8)) @test_throws ArgumentError comp(M32) @test rank(comp(M)) < m end @test_throws ArgumentError PartialACA(; rtol = 1.0e-16)(M) # an atol below the precision stops at the precision instead of at full rank, # also with an explicit `rtol = 0` or `rtol = nothing` - makers = (kw -> PartialACA(; kw...), kw -> TSVD(; kw...), kw -> PartialACA(; kw..., recompress = true)) + makers = (kw -> PartialACA(; kw...), kw -> TSVD(; kw...), kw -> PartialACA(; kw..., recompress = true), kw -> RandomizedSVD(; kw...)) for rtol in (0, nothing), comp in makers R = comp((; atol = 1.0e-12, rtol))(M32) @test rank(R) < 20 @@ -192,6 +202,29 @@ Random.seed!(1) @test rank(comp((; rank = 50, rtol))(M32)) < 20 end end + @testset "randomized svd" begin + atol = 1.0e-5 + Rt = TSVD(; atol)(M, irange, jrange) + for block in (1, 4, 16) + comp = RandomizedSVD(; atol, block) + R = comp(M, irange, jrange) + @test norm(Matrix(R) - M) < 2 * atol + @test abs(rank(R) - rank(Rt)) <= 1 + @test R.orthogonality == :AB + # the random vectors only depend on the size of the block + @test Matrix(comp(M, irange, jrange, allocate_buffer(comp, T))) == Matrix(R) + end + @test norm(Matrix(RandomizedSVD(; rtol = 1.0e-5)(M)) - M) < 2.0e-5 * norm(M) + @test rank(RandomizedSVD(; rank = 10)(M)) == 10 + @test_throws ArgumentError RandomizedSVD(; block = 0) + # the basis stays orthonormal when the residuals reach the rounding errors + for S in (Float32, Float64) + L = rand(S, 120, 15) * rand(S, 15, 90) + R = RandomizedSVD(; rtol = 0)(L) + @test rank(R) == 15 + @test norm(Matrix(R) - L) < 1.0e3 * eps(S) * norm(L) + end + end end @testset "Tensorial" begin @@ -244,8 +277,24 @@ end Rw = PartialACA(; rtol, recompress = true)(M) Rt = TSVD(; rtol)(M) @test rank(Rw) < rank(Ra) && rank(Rt) == rank(Rw) - @test fro(Matrix(Rw) - M) < 5 * rtol * fro(M) + @test fro(Matrix(Rw) - M) < rtol * fro(M) @test fro(Matrix(Rt) - M) < 5 * rtol * fro(M) end end end + +@testset "ACA on special blocks" begin + # a block-diagonal matrix: the residual check finds the block missed by the crosses + rng = Xoshiro(6) + m, n, k = 48, 27, 13 + D = zeros(m, n) + D[1:k, 1:k] = rand(rng, k, 3) * rand(rng, 3, k) + D[(k + 1):end, (k + 1):end] = rand(rng, m - k, 2) * rand(rng, 2, n - k) + @test norm(Matrix(PartialACA(; atol = 1.0e-8)(D)) - D) < 1.0e-8 + # zero blocks, and zero rows which use up the candidate rows + Z = zeros(30, 20) + @test norm(Matrix(@test_logs PartialACA()(Z))) == 0 + Z[7, :] = rand(20) + Z[:, 3] = rand(30) + @test Matrix(PartialACA(; atol = 1.0e-12)(Z)) ≈ Z +end diff --git a/test/hmatrix_test.jl b/test/hmatrix_test.jl index 25d55dc..bd171b1 100644 --- a/test/hmatrix_test.jl +++ b/test/hmatrix_test.jl @@ -1,4 +1,5 @@ using Test +using Logging using StaticArrays using HMatrices using HMatrices: ClusterTree, CardinalitySplitter, StrongAdmissibilityStd, PartialACA @@ -8,6 +9,9 @@ using Random include(joinpath(HMatrices.PROJECT_ROOT, "test", "testutils.jl")) +# adding a random sparse matrix grows the blocks, which `axpy!` warns about +quiet(f) = with_logger(f, NullLogger()) + # a compressor that only implements the method with index ranges, without annotations struct RangeOnlyCompressor <: HMatrices.AbstractCompressor rtol::Float64 @@ -89,7 +93,7 @@ end T = eltype(H) m, n = size(H) S = spdiagm(0 => rand(T, n)) - Hnew = axpy!(true, S, deepcopy(H)) + Hnew = quiet(() -> axpy!(true, S, deepcopy(H))) @test Matrix(Hnew) == (H_full + Matrix(S)) end @testset "Vector problem (elasticity)" begin @@ -99,7 +103,7 @@ end T = eltype(H) m, n = size(H) S = spdiagm(0 => rand(T, n)) - Hnew = axpy!(true, S, deepcopy(H)) + Hnew = quiet(() -> axpy!(true, S, deepcopy(H))) @test Matrix(Hnew) == (H_full + Matrix(S)) end end @@ -125,7 +129,7 @@ end S = sprand(T, m, n, 0.01) # compare the increments: the large diagonal of `H` would hide errors for a in (true, 2) # the scaling also applies to admissible blocks - Hnew = axpy!(a, S, deepcopy(H)) + Hnew = quiet(() -> axpy!(a, S, deepcopy(H))) @test norm(Matrix(Hnew) - H_full - a * Matrix(S)) < 1.0e-8 * norm(a * S) end end @@ -138,7 +142,7 @@ end S = sprand(T, m, n, 0.1) # compare the increments: the large diagonal of `H` would hide errors for a in (true, 2) # the scaling also applies to admissible blocks - Hnew = axpy!(a, S, deepcopy(H)) + Hnew = quiet(() -> axpy!(a, S, deepcopy(H))) @test norm(Matrix(Hnew) - H_full - a * Matrix(S)) < 1.0e-8 * norm(a * S) end end @@ -262,6 +266,8 @@ end @test HMatrices.rowperm(H) != HMatrices.colperm(H) @test norm(Matrix(H + 2I) - (M + 2I)) < 1.0e-8 * norm(M) @test norm(Matrix(axpy!(3, I, deepcopy(H))) - (M + 3I)) < 1.0e-8 * norm(M) + @test iszero(Matrix(zero(H))) + @test norm(Matrix(H) - M) < 1.0e-8 * norm(M) # `zero` does not modify `H` # the factors of a product must be clustered consistently @test_throws ArgumentError HMatrices.hmul!(deepcopy(H), H, H, 1, 0, HMatrices.PartialACA()) # operations in the user ordering are not defined on a block diff --git a/test/lazy_factorization_test.jl b/test/lazy_factorization_test.jl new file mode 100644 index 0000000..d0a3041 --- /dev/null +++ b/test/lazy_factorization_test.jl @@ -0,0 +1,244 @@ +using Test +using HMatrices +using LinearAlgebra +using Random +using StaticArrays + +using HMatrices: RkMatrix, PartialACA, RandomizedSVD, ClusterTree, CardinalitySplitter, StrongAdmissibilityStd, flush!, flush_tree!, children, ThreadsExecutor, SerialExecutor, LazyDriver, LazyLowRankTerm, CarryTerm + +include(joinpath(HMatrices.PROJECT_ROOT, "test", "testutils.jl")) + +Random.seed!(1) + +m = 1500 +X = rand(SVector{3, Float64}, m) +splitter = CardinalitySplitter(; nmax = 50) +Xclt = ClusterTree(X, splitter) +adm = StrongAdmissibilityStd(; eta = 3) +K = laplace_matrix(X, X) +H = assemble_hmatrix(K, Xclt, Xclt; adm, comp = PartialACA(; atol = 1.0e-8), threads = false) +H_full = Matrix(H) + +relerr(A, B) = norm(A - B) / norm(B) +same(A, B) = relerr(A, B) <= 1.0e-12 + +@testset "Lazy updates" begin + for comp in (PartialACA(; atol = 1.0e-6), PartialACA(; atol = 1.0e-6, recompress = true), RandomizedSVD(; atol = 1.0e-6)) + @testset "$comp" begin + @testset "single product" begin + C = deepcopy(H) + d = LazyDriver(C, H, H, comp) + push!(d, C, H, H) + flush_tree!(d, C) + @test relerr(Matrix(C), H_full - H_full * H_full) < 1.0e-5 + @test HMatrices.isclean(C) + @test isempty(d.pending) + end + + @testset "several products and a carry" begin + C = deepcopy(H) + d = LazyDriver(C, H, H, comp) + A = RkMatrix(rand(m, 3), rand(m, 3)) + push!(HMatrices.pending!(d, C).carry, CarryTerm(LazyLowRankTerm(copy(A.A), copy(A.B)), 0, 0)) + push!(d, C, H, H) + push!(d, C, H, H) + flush_tree!(d, C) + exact = H_full + Matrix(A) - 2 * H_full * H_full + @test relerr(Matrix(C), exact) < 1.0e-5 + end + + @testset "updates pushed at different times and levels" begin + C = deepcopy(H) + d = LazyDriver(C, H, H, comp) + push!(d, C, H, H) + flush!(d, C) # only the root: work is handed to the children + @test !haskey(d.pending, C) + @test any(chd -> haskey(d.pending, chd), children(C)) + # register a second product directly on the children + chdC, chdH = children(C), children(H) + for i in 1:2, j in 1:2, k in 1:2 + push!(d, chdC[i, j], chdH[i, k], chdH[k, j]) + end + flush_tree!(d, C) + @test isempty(d.pending) + @test relerr(Matrix(C), H_full - 2 * H_full * H_full) < 1.0e-5 + end + end + end +end + + +@testset "exact low-rank products" begin + # complex data, to check the conjugations with a complex coefficient + Kc = single_layer_sphere(1500; k = 4) + cltc = ClusterTree(Kc.X, CardinalitySplitter(; nmax = 50)) + Hc = assemble_hmatrix(Kc, cltc, cltc; adm = StrongAdmissibilityStd(3), comp = PartialACA(; atol = 1.0e-8), threads = false) + isrk(X) = HMatrices.isleaf(X) && HMatrices.isadmissible(X) + α = 0.3 + 0.7im + found = Dict{Symbol, Int}() + for X in HMatrices.nodes(Hc), Y in HMatrices.nodes(Hc) + (HMatrices.isleaf(X) || HMatrices.isleaf(Y)) || continue + size(X, 2) == size(Y, 1) && HMatrices.colrange(X) == HMatrices.rowrange(Y) || continue + HMatrices._has_low_rank_form(X, Y) || continue + kind = isrk(X) && isrk(Y) ? :rkrk : isrk(X) ? :rkh : isrk(Y) ? :hrk : :dd + get(found, kind, 0) >= 3 && continue + found[kind] = get(found, kind, 0) + 1 + A, B = HMatrices._compute_low_rank_term(X, Y, α) + @test size(A, 2) == HMatrices._low_rank_term_rank(X, Y) + @test A * B' ≈ α * HMatrices._tree_matrix(X) * HMatrices._tree_matrix(Y) + # the same product with adjoint factors + A, B = HMatrices._compute_low_rank_term(adjoint(Y), adjoint(X), α) + @test A * B' ≈ α * (HMatrices._tree_matrix(X) * HMatrices._tree_matrix(Y))' + if kind == :rkrk + @test size(A, 2) == min(rank(HMatrices.data(X)), rank(HMatrices.data(Y))) + end + all(k -> get(found, k, 0) >= 3, (:rkrk, :rkh, :hrk, :dd)) && break + end + @test all(k -> get(found, k, 0) >= 1, (:rkrk, :rkh, :hrk, :dd)) +end + +""" + ShuffleExecutor(seed) + +Test executor which records the work spawned by a driver with its dependencies +(from the declared accesses, as `ThreadsExecutor` does), and runs it in `wait`, on +the calling task, in a random topological order. A driver which does not declare +an access correctly gives results depending on the order. +""" +struct ShuffleExecutor + seed::Int + lastwriter::Dict{UInt, Int} + work::Vector{Any} + preds::Vector{Vector{Int}} +end +ShuffleExecutor(seed) = ShuffleExecutor(seed, Dict{UInt, Int}(), Any[], Vector{Int}[]) + +function _writers(ex::ShuffleExecutor, x) + haskey(ex.lastwriter, objectid(x)) && return [ex.lastwriter[objectid(x)]] + x isa HMatrix && !HMatrices.isleaf(x) || return Int[] + return [ex.lastwriter[objectid(l)] for l in HMatrices.leaves(x) if haskey(ex.lastwriter, objectid(l))] +end + +function HMatrices.spawn!(f, ex::ShuffleExecutor, reads, writes) + id = length(ex.work) + 1 + accessed = map(HMatrices._stored, collect(Iterators.flatten((reads, writes)))) + push!(ex.preds, unique(reduce(vcat, (_writers(ex, x) for x in accessed); init = Int[]))) + foreach(x -> ex.lastwriter[objectid(HMatrices._stored(x))] = id, writes) + push!(ex.work, f) + return nothing +end + +function Base.wait(ex::ShuffleExecutor) + n = length(ex.work) + succs = [Int[] for _ in 1:n] + npending = length.(ex.preds) + for (i, p) in enumerate(ex.preds), j in p + push!(succs[j], i) + end + ready = findall(iszero, npending) + rng = Xoshiro(ex.seed) + while !isempty(ready) + k = rand(rng, eachindex(ready)) + i = ready[k] + ready[k] = ready[end] + pop!(ready) + ex.work[i]() + for j in succs[i] + (npending[j] -= 1) == 0 && push!(ready, j) + end + end + @assert all(iszero, npending) + empty!(ex.work), empty!(ex.preds), empty!(ex.lastwriter) + return nothing +end + +@testset "products and solves on threads" begin + # the drivers give the same results serially and on threads, where the executor checks + # their accesses + comp = PartialACA(; atol = 1.0e-8) + Hh = assemble_hmatrix(Hermitian(K), Xclt, Xclt; adm, comp, threads = false) + F = lu(H, comp) + L, U = UnitLowerTriangular(F.factors), UpperTriangular(F.factors) + serial_and_threads(f) = same(Matrix(f(ThreadsExecutor(; check_accesses = true))), Matrix(f(SerialExecutor()))) + @test serial_and_threads(ex -> HMatrices._hmul_tree!(deepcopy(H), H, H, -1, 1, comp; executor = ex)) + @test serial_and_threads(ex -> HMatrices._hmul_tree!(deepcopy(Hh), H, adjoint(H), -1, 1, comp; executor = ex)) + @test serial_and_threads(ex -> HMatrices.hldiv!(L, deepcopy(H), comp; executor = ex)) + @test serial_and_threads(ex -> HMatrices.hrdiv!(deepcopy(H), U, comp; executor = ex)) + # a `Hermitian` storing its lower triangle + Cl = HMatrices._hmul_tree!(Hermitian(deepcopy(H), :L), H, adjoint(H), -1, 1, comp) + Mt = HMatrices._tree_matrix(H) + @test relerr(HMatrices._tree_matrix(Cl), Hermitian(Mt, :L) - Mt * Mt') < 1.0e-6 + # an error in a piece of work is thrown as such, whatever the executor + Hn = deepcopy(Hh) + rmul!(parent(Hn), -1) + for ex in (SerialExecutor(), ThreadsExecutor()) + @test_throws PosDefException cholesky(Hn, comp; executor = ex) + end +end + +@testset "Factorizations" begin + # (kernel, wavenumber, size) for single-layer operators on the sphere + for (name, k, n) in (("Laplace", 0, 4000), ("Helmholtz", 8, 3000)) + @testset "LU, $name" begin + K = single_layer_sphere(n; k) + clt = ClusterTree(K.X, CardinalitySplitter(; nmax = 50)) + H = assemble_hmatrix( + K, clt, clt; adm = StrongAdmissibilityStd(3), comp = PartialACA(; rtol = 1.0e-10), + threads = false, + ) + M = Matrix(H) + y = rand(eltype(M), n) + exact = M \ y + atol = 1.0e-8 + for comp in (PartialACA(; atol), PartialACA(; atol, recompress = true), RandomizedSVD(; atol)) + F = lu(H, comp) + @test HMatrices.isclean(F.factors) + approx = F \ y + @test norm(approx - exact) < 1.0e-5 * norm(exact) + # `F.L` and `F.U` act in the ordering of the cluster tree + @test F.L * (F.U * approx[F.q]) ≈ y[F.p] + end + # the same operations in a different order give the same factors, up to the + # rounding errors (some BLAS round differently with the memory layout) + for comp in (PartialACA(; atol), RandomizedSVD(; atol)) + Ms = HMatrices._tree_matrix(lu(H, comp; executor = SerialExecutor()).factors) + Ft = lu(H, comp; executor = ThreadsExecutor(; check_accesses = true)) + @test HMatrices.isclean(Ft.factors) + @test same(HMatrices._tree_matrix(Ft.factors), Ms) + for seed in 1:2 + @test same(HMatrices._tree_matrix(lu(H, comp; executor = ShuffleExecutor(seed)).factors), Ms) + end + end + end + end + # the upper triangle of the stored factor of a Cholesky factorization (the lower + # leaves of a `Hermitian` have no data) + function upper_factor(F) + H = parent(F.factors) + U = zeros(eltype(H), size(H)) + for leaf in HMatrices.leaves(H) + HMatrices.hasdata(leaf) || continue + U[HMatrices.rowrange(leaf), HMatrices.colrange(leaf)] = Matrix(HMatrices.data(leaf)) + end + return triu(U) + end + @testset "Cholesky" begin + K = single_layer_sphere(4000) + clt = ClusterTree(K.X, CardinalitySplitter(; nmax = 50)) + H = assemble_hmatrix(Hermitian(K), clt, clt; adm = StrongAdmissibilityStd(3), comp = PartialACA(; rtol = 1.0e-10), threads = false) + M = Matrix(K) + y = rand(4000) + exact = M \ y + for comp in (PartialACA(; atol = 1.0e-8), RandomizedSVD(; atol = 1.0e-8)) + F = cholesky(H, comp; executor = SerialExecutor()) + @test norm(F \ y - exact) < 1.0e-5 * norm(exact) + Us = upper_factor(F) + Ft = cholesky(H, comp; executor = ThreadsExecutor(; check_accesses = true)) + @test same(upper_factor(Ft), Us) + for seed in 1:2 + Fr = cholesky(H, comp; executor = ShuffleExecutor(seed)) + @test same(upper_factor(Fr), Us) + end + end + end +end diff --git a/test/lu_test.jl b/test/lu_test.jl index 84ce67b..9a599de 100644 --- a/test/lu_test.jl +++ b/test/lu_test.jl @@ -24,7 +24,7 @@ adm = StrongAdmissibilityStd(3) comp = PartialACA(; atol = 1.0e-10) for threads in (false, true) H = assemble_hmatrix(K, Xclt, Yclt; adm, comp, threads) - hlu = lu(H; atol = 1.0e-10) + hlu = lu(H; atol = 1.0e-10, threads) y = rand(m) M = Matrix(K) exact = M \ y @@ -79,3 +79,22 @@ end Z = rand(n, 2) @test norm(F.L * (F.U * Z) - M[F.p, F.q] * Z) < 1.0e-6 * norm(M[F.p, F.q] * Z) end + +@testset "single precision" begin + S = single_layer_sphere(1500) + K32 = KernelMatrix((x, y) -> Float32(S.f(x, y)), S.X, S.X) + H = assemble_hmatrix(K32; rtol = 1.0e-5, threads = false) + y = rand(Float32, 1500) + exact = Matrix(K32) \ y + for threads in (false, true) + F = lu(H; rtol = 1.0e-5, threads) + @test eltype(F.factors) == Float32 + @test norm(F \ y - exact) < 1.0e-3 * norm(exact) + end +end + +@testset "non-scalar entries" begin + X = rand(SVector{3, Float64}, 500) + H = assemble_hmatrix(elastostatic_matrix(X, X, 1, 1), X; threads = false) + @test_throws ArgumentError lu(H) +end diff --git a/test/multiplication_test.jl b/test/multiplication_test.jl index b00ae04..42cf5f9 100755 --- a/test/multiplication_test.jl +++ b/test/multiplication_test.jl @@ -1,4 +1,5 @@ using Test +using Logging using HMatrices using HMatrices: ClusterTree, CardinalitySplitter, StrongAdmissibilityStd, PartialACA using LinearAlgebra @@ -78,9 +79,10 @@ end Hc = assemble_hmatrix(KernelMatrix(f, Xc, Xc), Xcclt, Xcclt; comp, threads = false) Mc = HMatrices._tree_matrix(Hc) C = deepcopy(Hc) - HMatrices.hmul!(C, Hc, Hc, -1, 1, comp) + # the sharp cutoff of the kernel limits the accuracy of the partial ACA, which + # may warn that it failed + with_logger(() -> HMatrices.hmul!(C, Hc, Hc, -1, 1, comp), NullLogger()) exact = Mc - Mc * Mc - # the sharp cutoff of the kernel limits the accuracy of the partial ACA @test norm(HMatrices._tree_matrix(C) - exact) < 1.0e-2 * norm(exact) end end @@ -152,3 +154,27 @@ end @test_throws DimensionMismatch mul!(zeros(T, m, 2), H, rand(T, n, 3)) end + +@testset "columns and products of a product operator" begin + # complex entries, a complex multiplier, two products and a low-rank term + K = single_layer_sphere(1200; k = 4) + clt = ClusterTree(K.X, CardinalitySplitter(; nmax = 40)) + H = assemble_hmatrix(K, clt, clt; adm = StrongAdmissibilityStd(3), comp = PartialACA(; atol = 1.0e-8), threads = false) + tm = HMatrices._tree_matrix + chd = HMatrices.children(H) + X1, Y1, X2, Y2 = chd[2, 1], chd[1, 2], chd[2, 2], chd[2, 2] + m, n = size(X1, 1), size(Y1, 2) + A, B = rand(ComplexF64, m, 5), rand(ComplexF64, n, 5) + a = 0.3 - 0.8im + L = HMatrices.LeafOperator{ComplexF64}(A, B, [(X1, Y1), (X2, Y2)], a) + M = a * (tm(X1) * tm(Y1) + tm(X2) * tm(Y2)) + A * B' + for j in (1, 7, 41) + @test HMatrices.getblock!(zeros(ComplexF64, m), L, 1:m, j) ≈ M[:, j] + @test HMatrices.getblock!(zeros(ComplexF64, n), adjoint(L), 1:n, j) ≈ M'[:, j] + end + # a whole block (e.g. for `TSVD`) + @test HMatrices.getblock!(zeros(ComplexF64, m, 3), L, 1:m, [1, 7, 41]) ≈ M[:, [1, 7, 41]] + V, W = rand(ComplexF64, n, 3), rand(ComplexF64, m, 3) + @test mul!(zeros(ComplexF64, m, 3), L, V) ≈ M * V + @test mul!(zeros(ComplexF64, n, 3), adjoint(L), W) ≈ M' * W +end diff --git a/test/rkmatrix_test.jl b/test/rkmatrix_test.jl index 4911af1..3e8308b 100644 --- a/test/rkmatrix_test.jl +++ b/test/rkmatrix_test.jl @@ -2,7 +2,7 @@ using HMatrices using LinearAlgebra using Test using StaticArrays -using HMatrices: RkMatrix +using HMatrices: RkMatrix, PartialACA, TSVD @testset "RkMatrix" begin @testset "Scalar entries" begin @@ -39,3 +39,53 @@ using HMatrices: RkMatrix @test rank(R) == r end end + +@testset "orthogonality and truncation errors" begin + m, n, r = 60, 40, 8 + M = rand(m, r) * rand(r, n) + 1.0e-9 * rand(m, n) + # truncation errors of the first `i` columns + errs(R) = [norm(M - R.A[:, 1:i] * R.B[:, 1:i]') for i in 1:rank(R)] + @testset "constructors" begin + R = RkMatrix(rand(m, 2), rand(n, 2)) + @test R.orthogonality == :none && isempty(R.truncation_error) + R.orthogonality = :AB + R.truncation_error = [1.0, 0.0] + @test copy(R).orthogonality == :AB && copy(R).truncation_error == [1.0, 0.0] + R.A = rand(m, 2) # assigning a factor invalidates the information + @test R.orthogonality == :none && isempty(R.truncation_error) + end + @testset "PartialACA" begin + R = PartialACA(; atol = 1.0e-6)(M) + @test R.orthogonality == :none + @test length(R.truncation_error) == rank(R) + @test issorted(R.truncation_error; rev = true) + end + @testset "SVD forms" begin + for R in ( + PartialACA(; atol = 1.0e-6, recompress = true)(M), + HMatrices.RandomizedSVD(; atol = 1.0e-6)(M), + HMatrices.compress!(copy(M), TSVD(; atol = 1.0e-6)), + HMatrices.compress!(RkMatrix(copy(M), Matrix(1.0I, n, n)), TSVD(; atol = 1.0e-6)), + ) + @test R.orthogonality == :AB + GA, GB = R.A' * R.A, R.B' * R.B + @test norm(GA - Diagonal(diag(GA))) <= 1.0e-10 * norm(GA) + @test norm(GB - Diagonal(diag(GB))) <= 1.0e-10 * norm(GB) + @test length(R.truncation_error) == rank(R) + # the estimates are the actual errors, up to the error of the input + @test all(abs.(R.truncation_error - errs(R)) .<= 1.0e-6 .+ 1.0e-6 * errs(R)) + end + end + @testset "in-place modifications" begin + R = PartialACA(; atol = 1.0e-6, recompress = true)(M) + e = copy(R.truncation_error) + rmul!(R, -2.0) + @test R.orthogonality == :AB && R.truncation_error ≈ 2 * e + HMatrices._modified_factor!(R, :A) # e.g. a triangular solve on `A` + @test R.orthogonality == :B && isempty(R.truncation_error) + HMatrices._modified_factor!(R, :A) + @test R.orthogonality == :B + HMatrices._modified_factor!(R, :B) + @test R.orthogonality == :none + end +end diff --git a/test/runtests.jl b/test/runtests.jl index d3549bb..24eda04 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -28,6 +28,14 @@ end include("multiplication_test.jl") end +@safetestset "Thread executor" begin + include("thread_executor_test.jl") +end + +@safetestset "Lazy factorization" begin + include("lazy_factorization_test.jl") +end + @safetestset "Triangular" begin include("triangular_test.jl") end diff --git a/test/thread_executor_test.jl b/test/thread_executor_test.jl new file mode 100644 index 0000000..059d22d --- /dev/null +++ b/test/thread_executor_test.jl @@ -0,0 +1,154 @@ +using Test +using HMatrices +using HMatrices: ThreadsExecutor, SerialExecutor, spawn! +using LinearAlgebra +using Random +using StaticArrays + +""" + random_program!(ex, objects, nsteps, rng) + +Spawn `nsteps` pieces of work, each writing one or two random objects +(`Ref{Int}`s) and reading a few objects written before. As in the drivers, an +object is never written after it was read. A piece of work checks that the +objects it reads hold the value written by their last writer in program order, +then writes its step number into the objects it writes. Random `yield`s inside +the work shuffle the execution, so a missing dependency shows up even on a +single thread. Returns the number of failed checks. +""" +function random_program!(ex, objects, nsteps, rng) + expected = zeros(Int, length(objects)) # value of each object after the work spawned so far + wasread = falses(length(objects)) + errors = Threads.Atomic{Int}(0) + for step in 1:nsteps + writable = findall(!, wasread) + written = findall(!iszero, expected) + writes = unique(rand(rng, writable, rand(rng, 1:2))) + reads = isempty(written) ? Int[] : setdiff(unique(rand(rng, written, rand(rng, 0:3))), writes) + want = expected[reads] + nyields = rand(rng, 0:3) + spawn!(ex, (objects[i] for i in reads), (objects[i] for i in writes)) do + for _ in 1:nyields + yield() + end + for (i, v) in zip(reads, want) + objects[i][] == v || Threads.atomic_add!(errors, 1) + end + for i in writes + objects[i][] = step + end + end + expected[writes] .= step + wasread[reads] .= true + end + return errors +end + +# whether a piece of work reading the block `H` runs after the one writing its `leaf` +function block_read_waits_for_leaves(ex, H, leaf) + done, seen = Ref(false), Ref(false) + spawn!(() -> (sleep(0.1); done[] = true), ex, (), (leaf,)) + spawn!(() -> (seen[] = done[]), ex, (H,), ()) + wait(ex) + return seen[] +end + +@testset "ThreadsExecutor" begin + @info "testing the executor with $(Threads.nthreads()) threads" + @testset "random dependencies" begin + ex = ThreadsExecutor() # reused after each `wait` + for seed in 1:20 + objects = [Ref(0) for _ in 1:300] + errors = random_program!(ex, objects, 200, Xoshiro(seed)) + wait(ex) + @test errors[] == 0 + end + end + + @testset "errors" begin + ex = ThreadsExecutor() + ran = Threads.Atomic{Int}(0) + objects = [Ref(0) for _ in 1:4] + for step in 1:1000 + spawn!(ex, (), (objects[mod1(step, 4)],)) do + step == 10 && error("failure at step 10") + Threads.atomic_add!(ran, 1) + end + end + err = try + wait(ex) + nothing + catch e + e + end + # the error itself, as with a serial executor + @test err isa ErrorException + @test occursin("failure at step 10", sprint(showerror, err)) + # the other pieces of work ran, and none runs after `wait` + @test ran[] == 999 + sleep(0.05) + @test ran[] == 999 + # the error is reported once + spawn!(() -> nothing, ex, (), (objects[1],)) + @test wait(ex) === nothing + end + + @testset "accesses" begin + H = assemble_hmatrix(KernelMatrix((x, y) -> exp(-norm(x - y)), rand(SVector{3, Float64}, 400), rand(SVector{3, Float64}, 400)); threads = false) + leaf = first(HMatrices.leaves(H)) + ex = ThreadsExecutor(; check_accesses = true) + # a leaf written after a block containing it was read + spawn!(() -> nothing, ex, (H,), ()) + @test_throws ErrorException spawn!(() -> nothing, ex, (), (leaf,)) + wait(ex) + # an object written after it was read + object = Ref(0) + spawn!(() -> nothing, ex, (object,), ()) + @test_throws ErrorException spawn!(() -> nothing, ex, (), (object,)) + wait(ex) + # a piece of work reading and writing an object + spawn!(() -> nothing, ex, (object,), (object,)) + wait(ex) + # without the check, the same program runs + ex = ThreadsExecutor() + spawn!(() -> nothing, ex, (H,), ()) + spawn!(() -> nothing, ex, (), (leaf,)) + wait(ex) + # an internal block cannot be written + @test_throws ArgumentError spawn!(() -> nothing, ex, (), (H,)) + wait(ex) + # a read of a block waits for the writers of its leaves + @test block_read_waits_for_leaves(ex, H, leaf) + end + + @testset "drivers which throw" begin + # the work spawned before the error is done when the call returns + ex = ThreadsExecutor() + done = Threads.Atomic{Int}(0) + err = try + HMatrices._run!(ex) do + for i in 1:100 + spawn!(() -> (sleep(0.001); Threads.atomic_add!(done, 1)), ex, (), (Ref(i),)) + end + error("driver failure") + end + nothing + catch e + e + end + @test err isa ErrorException + @test done[] == 100 + @test wait(ex) === nothing + end + + @testset "serial executor" begin + ex = SerialExecutor() + out = Int[] + for i in 1:3 + spawn!(() -> push!(out, i), ex, (), ()) + end + wait(ex) + @test out == 1:3 + @test_throws ErrorException spawn!(() -> error("failure"), ex, (), ()) + end +end diff --git a/test/triangular_test.jl b/test/triangular_test.jl index b5efc4c..6296344 100755 --- a/test/triangular_test.jl +++ b/test/triangular_test.jl @@ -54,7 +54,7 @@ H_full = HMatrices._tree_matrix(H) ## 3.3 compressor = PartialACA(; atol = 1.0e-8) exact = ldiv!(UnitLowerTriangular(H_full), copy(H_full)) - approx = ldiv!(UnitLowerTriangular(H), deepcopy(H), compressor) + approx = HMatrices.hldiv!(UnitLowerTriangular(H), deepcopy(H), compressor) @test exact ≈ HMatrices._tree_matrix(approx) end @@ -75,6 +75,6 @@ end ## 3.3 compressor = PartialACA(; atol = 1.0e-8) exact = rdiv!(deepcopy(H_full), UpperTriangular(H_full)) - approx = rdiv!(deepcopy(H), UpperTriangular(H), compressor) + approx = HMatrices.hrdiv!(deepcopy(H), UpperTriangular(H), compressor) @test exact ≈ HMatrices._tree_matrix(approx) end