Skip to content

Commit 2a851fb

Browse files
committed
Support and tests for randomized SVD
1 parent 6a009ba commit 2a851fb

3 files changed

Lines changed: 165 additions & 1 deletion

File tree

‎src/factorizations/factorizations.jl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ include("utility.jl")
3131
include("matrixalgebrakit.jl")
3232
include("truncation.jl")
3333
include("adjoint.jl")
34+
include("randomized.jl")
3435
include("diagonal.jl")
3536
include("pullbacks.jl")
3637
include("pushforwards.jl")

‎src/factorizations/randomized.jl‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# Randomized truncated SVD
2+
# ------------------------
3+
# A randomized SVD (e.g. `CUSOLVER_Randomized`) only computes the largest `k` singular triplets of
4+
# a matrix. For a tensor, `k` is needed *per block* before the decomposition. We derive it from
5+
# the truncation strategy: each block is decomposed into a reduced space that is guaranteed to
6+
# contain everything the strategy keeps, after which the strategy is applied as usual.
7+
8+
const RandomizedSVDAlgorithm = TruncatedAlgorithm{<:MAK.GPU_Randomized}
9+
10+
_keeps_largest(strategy) = strategy.rev && (strategy.by === abs || strategy.by === identity)
11+
12+
"""
13+
_svd_rank_bound(strategy, c, n)
14+
15+
Upper bound on the number of singular values that `strategy` keeps in the block of sector `c`,
16+
which has `n` singular values in total, or `nothing` if the strategy does not bound it (or does
17+
not keep the largest values).
18+
"""
19+
_svd_rank_bound(::TruncationStrategy, c, n) = nothing
20+
function _svd_rank_bound(strategy::TruncationByOrder, c, n)
21+
_keeps_largest(strategy) || return nothing
22+
# values in block `c` are weighted by `dim(c)`
23+
return min(n, floor(Int, strategy.howmany / dim(c)))
24+
end
25+
function _svd_rank_bound(strategy::TruncationSpace, c, n)
26+
_keeps_largest(strategy) || return nothing
27+
return min(n, dim(strategy.space, c))
28+
end
29+
function _svd_rank_bound(strategy::TruncationIntersection, c, n)
30+
bounds = map(s -> _svd_rank_bound(s, c, n), strategy.components)
31+
all(isnothing, bounds) && return nothing
32+
return minimum(b for b in bounds if !isnothing(b))
33+
end
34+
function _svd_rank_bound(strategy::TruncationUnion, c, n)
35+
bounds = map(s -> _svd_rank_bound(s, c, n), strategy.components)
36+
any(isnothing, bounds) && return nothing
37+
return maximum(bounds)
38+
end
39+
40+
# use `k` values per sector, taken from the truncation strategy and,
41+
# if `k` is provided by the algorithm, capped by that
42+
function _randomized_svd_space(t::AbstractTensorMap, alg::RandomizedSVDAlgorithm)
43+
V = infimum(fuse(codomain(t)), fuse(domain(t)))
44+
kmax = get(alg.alg.kwargs, :k, nothing)
45+
inds = SectorDict(c => Base.OneTo(_randomized_svd_rank(alg.trunc, kmax, c, dim(V, c))) for c in sectors(V))
46+
return truncate_space(V, inds)
47+
end
48+
function _randomized_svd_rank(trunc, kmax, c, n)
49+
k = _svd_rank_bound(trunc, c, n)
50+
if isnothing(kmax)
51+
isnothing(k) && throw(
52+
ArgumentError(
53+
"randomized SVD needs the number of singular values to compute: use a truncation strategy that bounds the rank (`truncrank`, `truncspace`, or an intersection with one of these), or pass `k` to the algorithm"
54+
)
55+
)
56+
return k
57+
end
58+
return isnothing(k) ? min(kmax, n) : min(k, kmax)
59+
end
60+
61+
function MAK.initialize_output(
62+
::Union{typeof(svd_trunc!), typeof(svd_trunc_no_error!)}, t::AbstractTensorMap,
63+
alg::RandomizedSVDAlgorithm
64+
)
65+
@timeit_debug GLOBAL_TIMER "alloc: initialize_output" begin
66+
Vk = _randomized_svd_space(t, alg)
67+
U = similar(t, codomain(t) ← Vk)
68+
S = similar_diagonal(t, real(scalartype(t)), Vk)
69+
Vᴴ = similar(t, Vk ← domain(t))
70+
return U, S, Vᴴ
71+
end
72+
end
73+
74+
function MAK.svd_trunc_no_error!(t::AbstractTensorMap, USVᴴ, alg::RandomizedSVDAlgorithm)
75+
U, S, Vᴴ = USVᴴ
76+
kwargs = Base.structdiff(alg.alg.kwargs, NamedTuple{(:k, :p, :fixgauge)})
77+
fixgauge = get(alg.alg.kwargs, :fixgauge, MAK.default_fixgauge())::Bool
78+
@timeit_debug GLOBAL_TIMER "svd_trunc!" begin
79+
for (c, Sb) in blocks(S)
80+
tb, Ub, Vᴴb = block(t, c), block(U, c), block(Vᴴ, c)
81+
s = diagview(Sb)
82+
k = length(s)
83+
k == 0 && continue
84+
n = min(size(tb)...)
85+
p = get(alg.alg.kwargs, :p, n - k - 1)
86+
if p > 0 && k + p < n
87+
MAK._gpu_Xgesvdr!(tb, s, Ub, Vᴴb; k, p, kwargs...)
88+
else # the requested oversampling does not fit in this block
89+
Uf, Sf, Vᴴf = svd_compact!(tb, MAK.select_algorithm(svd_compact!, tb, nothing))
90+
copyto!(Ub, view(Uf, :, 1:k))
91+
copyto!(s, view(diagview(Sf), 1:k))
92+
copyto!(Vᴴb, view(Vᴴf, 1:k, :))
93+
end
94+
fixgauge && MAK.gaugefix!(svd_trunc!, Ub, Vᴴb)
95+
end
96+
end
97+
USVᴴtrunc, _ = MAK.truncate(svd_trunc!, (U, S, Vᴴ), alg.trunc)
98+
return USVᴴtrunc
99+
end
100+
101+
function MAK.svd_trunc!(t::AbstractTensorMap, USVᴴ, alg::RandomizedSVDAlgorithm)
102+
normt = norm(t)
103+
Ũ, S̃, Ṽᴴ = svd_trunc_no_error!(t, USVᴴ, alg)
104+
normS = norm(S̃)
105+
ϵ = sqrt((normt + normS) * abs(normt - normS))
106+
return Ũ, S̃, Ṽᴴ, ϵ
107+
end
108+
109+
function MAK.initialize_output(
110+
::typeof(svd_trunc!), t::AdjointTensorMap, alg::RandomizedSVDAlgorithm
111+
)
112+
return reverse(adjoint.(MAK.initialize_output(svd_trunc!, adjoint(t), _adjoint(alg))))
113+
end
114+
function MAK.svd_trunc!(t::AdjointTensorMap, F, alg::RandomizedSVDAlgorithm)
115+
U, S, Vᴴ, ϵ = svd_trunc!(adjoint(t), reverse(adjoint.(F)), _adjoint(alg))
116+
return Vᴴ', S, U', ϵ
117+
end

‎test/cuda/factorizations.jl‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ using Test, TestExtras
33
using TensorKit
44
using LinearAlgebra: LinearAlgebra
55
using Random
6-
using MatrixAlgebraKit: DefaultAlgorithm, Jacobi, diagview
6+
using MatrixAlgebraKit: DefaultAlgorithm, Jacobi, CUSOLVER_Randomized, diagview
77
const CUDAExt = Base.get_extension(TensorKit, :TensorKitCUDAExt)
88
@assert !isnothing(CUDAExt) "Failed to load TensorKit - CUDA extension"
99
const CuTensorMap = getglobal(CUDAExt, :CuTensorMap)
@@ -481,6 +481,52 @@ for V in spacelist
481481
end
482482
end
483483

484+
@testset "randomized truncated SVD" begin
485+
# a randomized SVD is only accurate if the discarded part of the spectrum is small,
486+
# so test on a low-rank tensor plus a small amount of noise
487+
function lowrank(t, nvals)
488+
t isa TensorKit.AdjointTensorMap && return lowrank(t', nvals)'
489+
U, S, Vᴴ, _ = svd_trunc(t; trunc = truncrank(nvals))
490+
noise = normalize!(cuRAND.randn(scalartype(t), space(t)))
491+
return U * S * Vᴴ + eps(real(scalartype(t)))^(3 / 4) * noise
492+
end
493+
for T in eltypes,
494+
t0 in (
495+
cuRAND.randn(T, W, W), cuRAND.randn(T, W, W)',
496+
cuRAND.randn(T, (V1 ⊗ V2 ⊗ V3), (V4 ⊗ V5)'), cuRAND.randn(T, (V1 ⊗ V2)', (V3 ⊗ V4 ⊗ V5))',
497+
)
498+
499+
normalize!(t0)
500+
_, Sref, _, _ = svd_trunc(t0; trunc = notrunc())
501+
nvals = round(Int, dim(domain(Sref)) / 2)
502+
t = lowrank(t0, nvals)
503+
alg = CUSOLVER_Randomized()
504+
505+
_, S1, _, _ = svd_trunc(t; trunc = truncrank(nvals))
506+
λ = minimum(diagview(S1))
507+
ϵtol = eps(real(T))^(1 / 3)
508+
for trunc in (
509+
truncrank(nvals), truncspace(space(S1, 1)),
510+
truncrank(nvals) & trunctol(; atol = λ / 2),
511+
)
512+
U, S, Vᴴ, ϵ = @constinferred svd_trunc(t; trunc, alg)
513+
Ur, Sr, Vᴴr, ϵr = svd_trunc(t; trunc)
514+
@test space(S, 1) == space(Sr, 1)
515+
@test S ≈ Sr
516+
@test isisometric(U)
517+
@test isisometric(Vᴴ; side = :right)
518+
@test U * S * Vᴴ ≈ Ur * Sr * Vᴴr
519+
@test norm(t - U * S * Vᴴ) ≈ ϵ atol = ϵtol
520+
@test ϵ ≈ ϵr atol = ϵtol
521+
end
522+
523+
_, S2, _, _ = svd_trunc(t; trunc = truncrank(nvals), alg = CUSOLVER_Randomized(; k = 1))
524+
@test all(c -> length(diagview(block(S2, c))) ≤ 1, blocksectors(S2))
525+
526+
@test_throws ArgumentError svd_trunc(t; trunc = trunctol(; atol = λ / 2), alg)
527+
end
528+
end
529+
484530
@testset "Eigenvalue decomposition" begin
485531
for T in eltypes,
486532
t in (

0 commit comments

Comments
 (0)