Repository navigation
[WIP] Solve the truncated svd and eigh pullbacks by conjugate gradients #296
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
leburgel
wants to merge
8
commits into
main
Choose a base branch
from
lb/trunc_pullback_cg
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
78200b3
Solve the truncated svd and eigh pullbacks by conjugate gradients
leburgel 4d33520
Update src/common/stein.jl
leburgel 103d01a
Undo rogue `p` -> `k` rename
leburgel d38116e
Remove trailing whitespace
leburgel 8e90e6f
Conjugate-gradient tolerance relative to the right-hand side (cg_rtol…
leburgel c9ffc28
Name the svd and eigh pullbacks' solver tolerance stein_rtol
leburgel 1f8ac7d
Rename stein_rtol to complement_rtol
leburgel 87b235e
Conjugate-gradient tolerance relative to each column's right-hand side
leburgel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| # Solvers for the Stein equation X - G X Diagonal(w) = B, i.e. (1 - wᵢ G) xᵢ = bᵢ per column. | ||
| # Used in the pullback of truncated decompositions, with G = P Pᴴ or Pᴴ P, wᵢ = 1/σᵢ² for the case of SVD, | ||
| # and G = P, wᵢ = 1/λᵢ for the case of EIG(H). Here, P the part of A outside the kept vectors. | ||
| # Naive iteration requires γᵢ, the spectral radius of wᵢ G, to be smaller than 1. | ||
|
|
||
| """ | ||
| accelerative_smith_iteration!(X, Xₙ, G, w, atol, maxiter) | ||
|
|
||
| Solve `X = B + G * X * Diagonal(w)` by summing the Neumann series | ||
| `X = Σₖ Gᵏ * B * Diagonal(w)ᵏ` by doubling (Smith's method), i.e. by repeatedly adding | ||
| `G^(2ʲ) * X * Diagonal(w)^(2ʲ)` to `X` until the norm of that increment drops below `atol`, | ||
| for at most `maxiter` steps. | ||
|
|
||
| On entry, `X` contains `B`, and it is overwritten with the result. `Xₙ` is used as a buffer, | ||
| and `G` and `w` are overwritten. `w` is normalized such that `maximum(abs, w) == 1`, so that | ||
| squaring it can only shrink it; `G` is scaled by the inverse factor to compensate. | ||
|
|
||
| Reference: https://doi.org/10.1016/j.aml.2009.01.012. | ||
| """ | ||
| function accelerative_smith_iteration!(X, Xₙ, G, w, atol, maxiter) | ||
| Gₙ = similar(G) | ||
| wmax = maximum(abs, w) | ||
| w ./= wmax | ||
| G .*= wmax | ||
| for k in 1:maxiter | ||
| Xₙ = rmul!(mul!(Xₙ, G, X), Diagonal(w)) | ||
| if maximum(abs, Xₙ) < atol | ||
| break | ||
| end | ||
| X .+= Xₙ | ||
| if k == maxiter | ||
| @warn "Sylvester iteration did not converge after $k iterations, final norm of X: $(maximum(abs, X))" | ||
| break | ||
| end | ||
| w .= w .^ 2 | ||
| Gₙ = mul!(Gₙ, G, G) | ||
| G, Gₙ = Gₙ, G | ||
| end | ||
| return X | ||
| end | ||
|
|
||
| # smallest Ritz value: smallest eigenvalue of the Lanczos tridiagonal from the CG coefficients `α`, `β` | ||
| function _cg_ritz_min(α, β) | ||
| l = length(α) | ||
| d = similar(α) | ||
| d[1] = 1 / α[1] | ||
| for j in 2:l | ||
| d[j] = 1 / α[j] + β[j - 1] / α[j - 1] | ||
| end | ||
| e = sqrt.(β[1:(l - 1)]) ./ α[1:(l - 1)] | ||
| return LinearAlgebra.eigmin(LinearAlgebra.SymTridiagonal(d, e)) | ||
| end | ||
|
|
||
| # (1 - wᵢ G) applied to the columns of Z | ||
| _stein_op(G, w, Z) = Z .- (G * Z) .* transpose(w) | ||
|
|
||
| # iterations until the squared residual norm `r` drops below `tol²`, at the faster of its rates over | ||
| # the last `l` iterations (from `r₀`) and all `m` (from `rᵢ`) | ||
| function _cg_remaining(r, r₀, rᵢ, tol, l, m) | ||
| q = min(log(r / r₀) / l, log(r / rᵢ) / m) # logarithm of the reduction per iteration | ||
| return q < 0 ? log(tol^2 / r) / q : oftype(float(r), Inf) | ||
| end | ||
|
|
||
| # real parts of the column-wise inner products of A and B, on the device of A and B. CPU arrays use | ||
| # `dot` per column, which avoids the temporary. This is restricted to `Matrix` rather than | ||
| # `StridedMatrix`, which GPU arrays also are: there it would return a CPU vector, one `dot` call | ||
| # each, which the GPU broadcasts in `hermitian_stein_cg!` cannot mix with the device arrays. | ||
| _coldots(A, B) = vec(real(sum(conj.(A) .* B; dims = 1))) | ||
| const _CPUMatrix = Union{Matrix, SubArray{<:Any, 2, <:Matrix}} | ||
| _coldots(A::_CPUMatrix, B::_CPUMatrix) = [real(LinearAlgebra.dot(view(A, :, j), view(B, :, j))) for j in axes(A, 2)] | ||
|
|
||
| """ | ||
| hermitian_stein_cg!(X, applyG!, formG, w, rtol, maxiter; cost_apply, cost_apply_formed, cost_form, cost_square = nothing) | ||
|
|
||
| Solve `X - G * X * Diagonal(w) = B` for Hermitian `G` by conjugate gradients on all columns at | ||
| once, in at most `maxiter` iterations: O(n² k) per iteration for k columns, against O(n³) per | ||
| doubling step. Only the products wᵢ G enter, so neither needs normalizing. `X` contains `B` on | ||
| entry and is overwritten with the result. | ||
|
|
||
| `applyG!(Y, Z)` sets `Y = G * Z` without forming `G`, and `formG()` returns `G`. `G` is formed | ||
| once the predicted remaining applications save more than `cost_form`, given the costs per column | ||
| `cost_apply` (by `applyG!`) and `cost_apply_formed` (by `G`); `cost_form = 0` forms it at once. | ||
| With `cost_square`, for indefinite `G` (eigh), the solver restarts on the residual equation | ||
| multiplied by 1 + wᵢ G, (1 - wᵢ² G²) xᵢ = (1 + wᵢ G) bᵢ, once half the predicted remaining cost | ||
| exceeds `cost_square` (forming G² and the new right-hand side): its spectrum [1 - γᵢ², 1] needs | ||
| about half the iterations. Each column is solved for its right-hand side normalized, and stops once | ||
| its residual is below `rtol` times the smallest Ritz value of the slowest column, so that its error | ||
| is below about `rtol` relative to its right-hand side. | ||
| """ | ||
| function hermitian_stein_cg!( | ||
| X, applyG!, formG, w, rtol, maxiter; | ||
| cost_apply, cost_apply_formed = cost_apply, cost_form, cost_square = nothing, nprobe::Int = 5 | ||
| ) | ||
| RT = real(eltype(X)) | ||
| G = iszero(cost_form) ? formG() : nothing | ||
| # the columns are independent: solve for normalized right-hand sides, so that `rtol` holds per column | ||
| nb = sqrt.(_coldots(X, X)) | ||
| nb = ifelse.(iszero.(nb), one(RT), nb) | ||
| X ./= transpose(nb) | ||
| tol = RT(rtol) # stopping residual 2-norm, refined by the Ritz values | ||
| ρ = _coldots(X, X) | ||
| cols = findall(ρ .> tol^2) # active columns, kept contiguous at the front | ||
| nact = length(cols) | ||
| iszero(nact) && return fill!(X, zero(eltype(X))) | ||
| R = X[:, cols] # X keeps B until the end | ||
| P = zero(R) | ||
| Q = similar(R) | ||
| Xc = zero(R) | ||
| wc = w[cols] | ||
| ρ = ρ[cols] | ||
| β = zero(ρ) | ||
| ρ₀ = copy(ρ) # squared residual norms at the previous check | ||
| ρᵢ = copy(ρ) # and at the start | ||
| αs = [RT[] for _ in 1:nact] | ||
| βs = [RT[] for _ in 1:nact] | ||
| for numiter in 1:maxiter | ||
| if numiter > 1 && (numiter - 1) % nprobe == 0 | ||
| c = argmax(abs.(view(wc, 1:nact))) # the slowest column | ||
| tol = rtol * _cg_ritz_min(αs[c], βs[c]) | ||
| nact = _cg_compact!( | ||
| view(ρ, 1:nact), tol, view(R, :, 1:nact), view(P, :, 1:nact), view(Xc, :, 1:nact), view(wc, 1:nact), | ||
| view(β, 1:nact), view(ρ₀, 1:nact), view(ρᵢ, 1:nact), view(cols, 1:nact), view(αs, 1:nact), view(βs, 1:nact) | ||
| ) | ||
| iszero(nact) && break | ||
| # predicted column applications | ||
| napply = sum(_cg_remaining.(view(ρ, 1:nact), view(ρ₀, 1:nact), view(ρᵢ, 1:nact), tol, nprobe, numiter - 1)) | ||
| if isnothing(G) && napply * (cost_apply - cost_apply_formed) > cost_form | ||
| G = formG() | ||
| end | ||
| if !isnothing(cost_square) && napply * cost_apply / 2 > cost_square # restart on the squared equation | ||
| isnothing(G) && (G = formG()) | ||
| X₁ = zero(X) # the current solution | ||
| X₁[:, cols] .= Xc | ||
| R = X .- _stein_op(G, w, X₁) | ||
| X .= R .+ (G * R) .* transpose(w) | ||
| G² = G * G | ||
| hermitian_stein_cg!(X, nothing, () -> G², w .^ 2, rtol, maxiter; cost_apply, cost_form = 0, nprobe) | ||
| return (X .+= X₁) .*= transpose(nb) | ||
| end | ||
| ρ₀ .= ρ | ||
| end | ||
| Pₐ, Rₐ, Qₐ, wₐ = view(P, :, 1:nact), view(R, :, 1:nact), view(Q, :, 1:nact), view(wc, 1:nact) | ||
| ρₐ, βₐ = view(ρ, 1:nact), view(β, 1:nact) | ||
| Pₐ .= Rₐ .+ Pₐ .* transpose(βₐ) | ||
| isnothing(G) ? applyG!(Qₐ, Pₐ) : mul!(Qₐ, G, Pₐ) | ||
| Qₐ .= Pₐ .- Qₐ .* transpose(wₐ) # q = (1 - wᵢ G) p | ||
| α = ρₐ ./ _coldots(Pₐ, Qₐ) | ||
| view(Xc, :, 1:nact) .+= Pₐ .* transpose(α) | ||
| Rₐ .-= Qₐ .* transpose(α) | ||
| βₐ .= ρₐ # ρold | ||
| ρₐ .= _coldots(Rₐ, Rₐ) | ||
| βₐ .= ρₐ ./ βₐ | ||
| for (j, a, b) in zip(1:nact, Array(α), Array(βₐ)) | ||
| push!(αs[j], a) | ||
| push!(βs[j], b) | ||
| end | ||
| nact = _cg_compact!( | ||
| ρₐ, tol, Rₐ, Pₐ, view(Xc, :, 1:nact), wₐ, | ||
| βₐ, view(ρ₀, 1:nact), view(ρᵢ, 1:nact), view(cols, 1:nact), view(αs, 1:nact), view(βs, 1:nact) | ||
| ) | ||
| iszero(nact) && break | ||
| end | ||
| iszero(nact) || @warn "conjugate gradients did not converge in $maxiter iterations, largest residual norm: $(sqrt(maximum(view(ρ, 1:nact))))" | ||
| fill!(X, zero(eltype(X))) | ||
| X[:, cols] .= Xc | ||
| return X .*= transpose(nb) | ||
| end | ||
|
|
||
| # move the columns with `ρ > tol²` to the front of all arrays (in order) and return their number | ||
| function _cg_compact!(ρ, tol, arrays...) | ||
| keep = Array(ρ) .> tol^2 | ||
| all(keep) && return length(keep) | ||
| perm = vcat(findall(keep), findall(.!keep)) | ||
| for a in (ρ, arrays...) | ||
| if a isa AbstractMatrix | ||
| a .= a[:, perm] | ||
| else | ||
| a .= a[perm] | ||
| end | ||
| end | ||
| return count(keep) | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is far from a "simple CG". It will take me quite some time to review it. I also don't particularly like the coding style, though I don't know to pinpoint that more precisely, or thus, what action could improve it 😄 . Maybe after I understand the code I will have some suggestions.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This was more a placeholder for pointing out that CG is a good Stein solver for these specific cases. Other than requesting it to be "as close to the KrylovKit CG as possible", I didn't really check the actual implementation. I'm perfectly fine with replacing the entire solver, I just didn't have the expertise to write a good one myself.