Skip to content

Commit ffa3c6a

Browse files
committed
Solve the truncated svd and eigh pullbacks by conjugate gradients
1 parent af6a263 commit ffa3c6a

5 files changed

Lines changed: 204 additions & 50 deletions

File tree

‎src/MatrixAlgebraKit.jl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ include("common/defaults.jl")
9292
include("common/householder.jl")
9393
include("common/initialization.jl")
9494
include("common/pullbacks.jl")
95+
include("common/stein.jl")
9596
include("common/safemethods.jl")
9697
include("common/view.jl")
9798
include("common/regularinv.jl")

‎src/common/pullbacks.jl‎

Lines changed: 0 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -35,39 +35,3 @@ iterating over `ind`, so that this also works for an `ind` that lives on a devic
3535
"""
3636
is_leading_index(ind::AbstractRange, p::Int) = ind == 1:p
3737
is_leading_index(ind::AbstractVector, p::Int) = length(ind) == p && all(ind .== 1:p)
38-
39-
"""
40-
accelerative_smith_iteration!(X, Xₙ, G, w, atol, maxiter)
41-
42-
Solve `X = B + G * X * Diagonal(w)` by summing the Neumann series
43-
`X = Σₖ Gᵏ * B * Diagonal(w)ᵏ` by doubling (Smith's method), i.e. by repeatedly adding
44-
`G^(2ʲ) * X * Diagonal(w)^(2ʲ)` to `X` until the norm of that increment drops below `atol`,
45-
for at most `maxiter` steps.
46-
47-
On entry, `X` contains `B`, and it is overwritten with the result. `Xₙ` is used as a buffer,
48-
and `G` and `w` are overwritten. `w` is normalized such that `maximum(abs, w) == 1`, so that
49-
squaring it can only shrink it; `G` is scaled by the inverse factor to compensate.
50-
51-
Reference: https://doi.org/10.1016/j.aml.2009.01.012.
52-
"""
53-
function accelerative_smith_iteration!(X, Xₙ, G, w, atol, maxiter)
54-
Gₙ = similar(G)
55-
wmax = maximum(abs, w)
56-
w ./= wmax
57-
G .*= wmax
58-
for k in 1:maxiter
59-
Xₙ = rmul!(mul!(Xₙ, G, X), Diagonal(w))
60-
if maximum(abs, Xₙ) < atol
61-
break
62-
end
63-
X .+= Xₙ
64-
if k == maxiter
65-
@warn "Sylvester iteration did not converge after $k iterations, final norm of X: $(maximum(abs, X))"
66-
break
67-
end
68-
w .= w .^ 2
69-
Gₙ = mul!(Gₙ, G, G)
70-
G, Gₙ = Gₙ, G
71-
end
72-
return X
73-
end

‎src/common/stein.jl‎

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
# Solvers for the Stein equation X - G X Diagonal(w) = B, i.e. (1 - wᵢ G) xᵢ = bᵢ per column, of the
2+
# truncated pullbacks. svd: G = P Pᴴ or Pᴴ P (the smaller), wᵢ = 1/σᵢ²; eigh: G = P, wᵢ = 1/λᵢ; with
3+
# P the part of A outside the kept vectors and γᵢ < 1 the spectral radius of wᵢ G.
4+
5+
"""
6+
accelerative_smith_iteration!(X, Xₙ, G, w, atol, maxiter)
7+
8+
Solve `X = B + G * X * Diagonal(w)` by summing the Neumann series
9+
`X = Σₖ Gᵏ * B * Diagonal(w)ᵏ` by doubling (Smith's method), i.e. by repeatedly adding
10+
`G^(2ʲ) * X * Diagonal(w)^(2ʲ)` to `X` until the norm of that increment drops below `atol`,
11+
for at most `maxiter` steps.
12+
13+
On entry, `X` contains `B`, and it is overwritten with the result. `Xₙ` is used as a buffer,
14+
and `G` and `w` are overwritten. `w` is normalized such that `maximum(abs, w) == 1`, so that
15+
squaring it can only shrink it; `G` is scaled by the inverse factor to compensate.
16+
17+
Reference: https://doi.org/10.1016/j.aml.2009.01.012.
18+
"""
19+
function accelerative_smith_iteration!(X, Xₙ, G, w, atol, maxiter)
20+
Gₙ = similar(G)
21+
wmax = maximum(abs, w)
22+
w ./= wmax
23+
G .*= wmax
24+
for k in 1:maxiter
25+
Xₙ = rmul!(mul!(Xₙ, G, X), Diagonal(w))
26+
if maximum(abs, Xₙ) < atol
27+
break
28+
end
29+
X .+= Xₙ
30+
if k == maxiter
31+
@warn "Sylvester iteration did not converge after $k iterations, final norm of X: $(maximum(abs, X))"
32+
break
33+
end
34+
w .= w .^ 2
35+
Gₙ = mul!(Gₙ, G, G)
36+
G, Gₙ = Gₙ, G
37+
end
38+
return X
39+
end
40+
41+
# smallest Ritz value: smallest eigenvalue of the Lanczos tridiagonal from the CG coefficients `α`, `β`
42+
function _cg_ritz_min(α, β)
43+
l = length(α)
44+
d = similar(α)
45+
d[1] = 1 / α[1]
46+
for j in 2:l
47+
d[j] = 1 / α[j] + β[j - 1] / α[j - 1]
48+
end
49+
e = sqrt.(β[1:(l - 1)]) ./ α[1:(l - 1)]
50+
return LinearAlgebra.eigmin(LinearAlgebra.SymTridiagonal(d, e))
51+
end
52+
53+
# (1 - wᵢ G) applied to the columns of Z
54+
_stein_op(G, w, Z) = Z .- (G * Z) .* transpose(w)
55+
56+
# iterations until the squared residual norm `r` drops below `tol²`, at the faster of its rates over
57+
# the last `l` iterations (from `r₀`) and all `m` (from `rᵢ`)
58+
function _cg_remaining(r, r₀, rᵢ, tol, l, m)
59+
q = min(log(r / r₀) / l, log(r / rᵢ) / m) # logarithm of the reduction per iteration
60+
return q < 0 ? log(tol^2 / r) / q : oftype(float(r), Inf)
61+
end
62+
63+
# real parts of the column-wise inner products of A and B, on the device of A and B. CPU arrays use
64+
# `dot` per column, which avoids the temporary. This is restricted to `Matrix` rather than
65+
# `StridedMatrix`, which GPU arrays also are: there it would return a CPU vector, one `dot` call
66+
# each, which the GPU broadcasts in `hermitian_stein_cg!` cannot mix with the device arrays.
67+
_coldots(A, B) = vec(real(sum(conj.(A) .* B; dims = 1)))
68+
const _CPUMatrix = Union{Matrix, SubArray{<:Any, 2, <:Matrix}}
69+
_coldots(A::_CPUMatrix, B::_CPUMatrix) = [real(LinearAlgebra.dot(view(A, :, j), view(B, :, j))) for j in axes(A, 2)]
70+
71+
"""
72+
hermitian_stein_cg!(X, applyG!, formG, w, atol, maxiter; cost_apply, cost_apply_formed, cost_form, cost_square = nothing)
73+
74+
Solve `X - G * X * Diagonal(w) = B` for Hermitian `G` by conjugate gradients on all columns at
75+
once, in at most `maxiter` iterations: O(n² k) per iteration for k columns, against O(n³) per
76+
doubling step. Only the products wᵢ G enter, so neither needs normalizing. `X` contains `B` on
77+
entry and is overwritten with the result.
78+
79+
`applyG!(Y, Z)` sets `Y = G * Z` without forming `G`, and `formG()` returns `G`. `G` is formed
80+
once the predicted remaining applications save more than `cost_form`, given the costs per column
81+
`cost_apply` (by `applyG!`) and `cost_apply_formed` (by `G`); `cost_form = 0` forms it at once.
82+
With `cost_square`, for indefinite `G` (eigh), the solver restarts on the residual equation
83+
multiplied by 1 + wᵢ G, (1 - wᵢ² G²) xᵢ = (1 + wᵢ G) bᵢ, once half the predicted remaining cost
84+
exceeds `cost_square` (forming G² and the new right-hand side): its spectrum [1 - γᵢ², 1] needs
85+
about half the iterations. A column stops once its residual is below `atol` times the smallest
86+
Ritz value of the slowest column, so that its error is below about `atol`.
87+
"""
88+
function hermitian_stein_cg!(
89+
X, applyG!, formG, w, atol, maxiter;
90+
cost_apply, cost_apply_formed = cost_apply, cost_form, cost_square = nothing, nprobe::Int = 5
91+
)
92+
RT = real(eltype(X))
93+
G = iszero(cost_form) ? formG() : nothing
94+
tol = RT(atol) # stopping residual 2-norm, refined by the Ritz values
95+
ρ = _coldots(X, X)
96+
cols = findall(ρ .> tol^2) # active columns, kept contiguous at the front
97+
nact = length(cols)
98+
iszero(nact) && return fill!(X, zero(eltype(X)))
99+
R = X[:, cols] # X keeps B until the end
100+
P = zero(R)
101+
Q = similar(R)
102+
Xc = zero(R)
103+
wc = w[cols]
104+
ρ = ρ[cols]
105+
β = zero(ρ)
106+
ρ₀ = copy(ρ) # squared residual norms at the previous check
107+
ρᵢ = copy(ρ) # and at the start
108+
αs = [RT[] for _ in 1:nact]
109+
βs = [RT[] for _ in 1:nact]
110+
for numiter in 1:maxiter
111+
if numiter > 1 && (numiter - 1) % nprobe == 0
112+
c = argmax(abs.(view(wc, 1:nact))) # the slowest column
113+
tol = atol * _cg_ritz_min(αs[c], βs[c])
114+
nact = _cg_compact!(
115+
view(ρ, 1:nact), tol, view(R, :, 1:nact), view(P, :, 1:nact), view(Xc, :, 1:nact), view(wc, 1:nact),
116+
view(β, 1:nact), view(ρ₀, 1:nact), view(ρᵢ, 1:nact), view(cols, 1:nact), view(αs, 1:nact), view(βs, 1:nact)
117+
)
118+
iszero(nact) && break
119+
# predicted column applications
120+
napply = sum(_cg_remaining.(view(ρ, 1:nact), view(ρ₀, 1:nact), view(ρᵢ, 1:nact), tol, nprobe, numiter - 1))
121+
if isnothing(G) && napply * (cost_apply - cost_apply_formed) > cost_form
122+
G = formG()
123+
end
124+
if !isnothing(cost_square) && napply * cost_apply / 2 > cost_square # restart on the squared equation
125+
isnothing(G) && (G = formG())
126+
X₁ = zero(X) # the current solution
127+
X₁[:, cols] .= Xc
128+
R = X .- _stein_op(G, w, X₁)
129+
X .= R .+ (G * R) .* transpose(w)
130+
G² = G * G
131+
hermitian_stein_cg!(X, nothing, () -> G², w .^ 2, atol, maxiter; cost_apply, cost_form = 0, nprobe)
132+
return X .+= X₁
133+
end
134+
ρ₀ .= ρ
135+
end
136+
Pₐ, Rₐ, Qₐ, wₐ = view(P, :, 1:nact), view(R, :, 1:nact), view(Q, :, 1:nact), view(wc, 1:nact)
137+
ρₐ, βₐ = view(ρ, 1:nact), view(β, 1:nact)
138+
Pₐ .= Rₐ .+ Pₐ .* transpose(βₐ)
139+
isnothing(G) ? applyG!(Qₐ, Pₐ) : mul!(Qₐ, G, Pₐ)
140+
Qₐ .= Pₐ .- Qₐ .* transpose(wₐ) # q = (1 - wᵢ G) p
141+
α = ρₐ ./ _coldots(Pₐ, Qₐ)
142+
view(Xc, :, 1:nact) .+= Pₐ .* transpose(α)
143+
Rₐ .-= Qₐ .* transpose(α)
144+
βₐ .= ρₐ # ρold
145+
ρₐ .= _coldots(Rₐ, Rₐ)
146+
βₐ .= ρₐ ./ βₐ
147+
for (j, a, b) in zip(1:nact, Array(α), Array(βₐ))
148+
push!(αs[j], a)
149+
push!(βs[j], b)
150+
end
151+
nact = _cg_compact!(
152+
ρₐ, tol, Rₐ, Pₐ, view(Xc, :, 1:nact), wₐ,
153+
βₐ, view(ρ₀, 1:nact), view(ρᵢ, 1:nact), view(cols, 1:nact), view(αs, 1:nact), view(βs, 1:nact)
154+
)
155+
iszero(nact) && break
156+
end
157+
iszero(nact) || @warn "conjugate gradients did not converge in $maxiter iterations, largest residual norm: $(sqrt(maximum(view(ρ, 1:nact))))"
158+
fill!(X, zero(eltype(X)))
159+
X[:, cols] .= Xc
160+
return X
161+
end
162+
163+
# move the columns with `ρ > tol²` to the front of all arrays (in order) and return their number
164+
function _cg_compact!(ρ, tol, arrays...)
165+
keep = Array(ρ) .> tol^2
166+
all(keep) && return length(keep)
167+
perm = vcat(findall(keep), findall(.!keep))
168+
for a in (ρ, arrays...)
169+
if a isa AbstractMatrix
170+
a .= a[:, perm]
171+
else
172+
a .= a[perm]
173+
end
174+
end
175+
return count(keep)
176+
end

‎src/pullbacks/eigh.jl‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -134,16 +134,16 @@ function eigh_trunc_pullback!(
134134
ΔA::AbstractMatrix, A, DV, ΔDV;
135135
degeneracy_atol::Real = default_pullback_rank_atol(DV[1]),
136136
gauge_atol::Real = default_pullback_gauge_atol(ΔDV[2]),
137-
maxiter::Int = 100 # TODO: better default, depending on expected number of steps using quadratic convergence?
137+
maxiter::Int = 10 * size(ΔA, 1) # conjugate-gradient iterations
138138
)
139139

140140
# Basic size checks and determination
141141
Dmat, V = DV
142-
(n, p) = size(V)
142+
(n, k) = size(V)
143143
D = diagview(Dmat)
144-
p == length(D) || throw(DimensionMismatch())
144+
k == length(D) || throw(DimensionMismatch())
145145
(n, n) == size(ΔA) || throw(DimensionMismatch())
146-
iszero(p) && return ΔA
146+
iszero(k) && return ΔA
147147

148148
ΔDmat, ΔV = ΔDV
149149
VᴴΔAV, ΔV₊ = check_and_prepare_eigh_cotangents(
@@ -153,13 +153,16 @@ function eigh_trunc_pullback!(
153153
if !iszerotangent(ΔV₊)
154154
X₀ = rdiv!(ΔV₊, Diagonal(D))
155155
AP = mul!(copy(A), V * Dmat, V', -1, 1)
156-
X = accelerative_smith_iteration!(X₀, similar(X₀), AP, inv.(D), degeneracy_atol, maxiter)
156+
X = hermitian_stein_cg!(
157+
X₀, nothing, () -> AP, inv.(D), degeneracy_atol, maxiter;
158+
cost_apply = n^2, cost_form = 0, cost_square = n^3 + n^2 * k
159+
)
157160
Z .+= X
158161
# we cannot directly multiply Z * V' into ΔA, because we have to
159162
# take the Hermitian part, and cannot apply project_hermitian! to
160163
# the current contents of ΔA
161164
# TODO: add an `add_project_hermitian!`
162-
# recycle AP's storage, but overwrite it: `accelerative_smith_iteration!` may leave a power of AP in it
165+
# recycle AP's storage
163166
ΔA′ = project_hermitian!(mul!(AP, Z, V'))
164167
ΔA .+= ΔA′
165168
else

‎src/pullbacks/svd.jl‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -220,22 +220,22 @@ function svd_trunc_pullback!(
220220
rank_atol::Real = 0,
221221
degeneracy_atol::Real = default_pullback_rank_atol(USVᴴ[2]),
222222
gauge_atol::Real = default_pullback_gauge_atol(ΔUSVᴴ...),
223-
maxiter::Int = 100 # TODO: better default, depending on expected number of steps using quadratic convergence?
223+
maxiter::Int = 10 * minimum(size(ΔA)) # conjugate-gradient iterations
224224
)
225225
# Extract the SVD components
226226
U, Smat, Vᴴ = USVᴴ
227227
m, n = size(U, 1), size(Vᴴ, 2)
228228
(m, n) == size(ΔA) || throw(DimensionMismatch(lazy"size of ΔA ($(size(ΔA))) does not match size of USVᴴ ($m, $n)"))
229229
S = diagview(Smat)
230-
p = length(S)
231-
p == size(U, 2) || throw(DimensionMismatch(lazy"U has $p columns but S has $(length(S)) singular values"))
232-
p == size(Vᴴ, 1) || throw(DimensionMismatch(lazy"Vᴴ has $p rows but S has $(length(S)) singular values"))
233-
iszero(p) && return ΔA
230+
k = length(S)
231+
k == size(U, 2) || throw(DimensionMismatch(lazy"U has $k columns but S has $(length(S)) singular values"))
232+
k == size(Vᴴ, 1) || throw(DimensionMismatch(lazy"Vᴴ has $k rows but S has $(length(S)) singular values"))
233+
iszero(k) && return ΔA
234234

235235
# Extract and check the cotangents
236236
ΔU, ΔSmat, ΔVᴴ = ΔUSVᴴ
237237
UᴴΔAV, ΔU₊, ΔV₊ᴴ = check_and_prepare_svd_cotangents(
238-
U, S, Vᴴ, ΔU, ΔSmat, ΔVᴴ, p; degeneracy_atol, gauge_atol
238+
U, S, Vᴴ, ΔU, ΔSmat, ΔVᴴ, k; degeneracy_atol, gauge_atol
239239
)
240240
ΔAV = U * UᴴΔAV
241241
ΔA = mul!(ΔA, ΔAV, Vᴴ, 1, 1) # add the contribution to ΔA
@@ -253,15 +253,25 @@ function svd_trunc_pullback!(
253253
if m ≤ n
254254
X = rmul!(AP * Y₀ᴴ', Diagonal(S⁻¹))
255255
X .+= X₀
256-
X = accelerative_smith_iteration!(X, X₀, AP * AP', S⁻¹ .^ 2, degeneracy_atol, maxiter) # recycle X₀
256+
APᴴZ = similar(X, n, k) # for applying AP AP' without forming it
257+
X = hermitian_stein_cg!(
258+
X, (GZ, Z) -> mul!(GZ, AP, mul!(view(APᴴZ, :, axes(Z, 2)), AP', Z)), () -> AP * AP',
259+
S⁻¹ .^ 2, degeneracy_atol, maxiter;
260+
cost_apply = 2 * m * n, cost_apply_formed = m^2, cost_form = m^2 * n
261+
)
257262
Yᴴ = lmul!(Diagonal(S⁻¹), X' * AP)
258263
Yᴴ .+= Y₀ᴴ
259264
ΔA = mul!(ΔA, X, Vᴴ, 1, 1)
260265
ΔA = mul!(ΔA, U, Yᴴ, 1, 1)
261266
else
262267
Y = rmul!(AP' * X₀, Diagonal(S⁻¹))
263268
Y .+= Y₀ᴴ'
264-
Y = accelerative_smith_iteration!(Y, similar(Y), AP' * AP, S⁻¹ .^ 2, degeneracy_atol, maxiter)
269+
APZ = similar(Y, m, k) # for applying AP' AP without forming it
270+
Y = hermitian_stein_cg!(
271+
Y, (GZ, Z) -> mul!(GZ, AP', mul!(view(APZ, :, axes(Z, 2)), AP, Z)), () -> AP' * AP,
272+
S⁻¹ .^ 2, degeneracy_atol, maxiter;
273+
cost_apply = 2 * m * n, cost_apply_formed = n^2, cost_form = n^2 * m
274+
)
265275
X = rmul!(AP * Y, Diagonal(S⁻¹))
266276
X .+= X₀
267277
ΔA = mul!(ΔA, X, Vᴴ, 1, 1)

0 commit comments

Comments
 (0)