Repository navigation
Closed
Labels
arraybugSomething is brokenneeds attentionIt's been a while since this was pushed on. Needs attention from the owner or a maintainer.
Description
What happened:
Complex singular values and vectors of svd_compressed() are different from standard np.linalg.svd.
What you expected to happen:
Complex singular values and vectors of svd_compressed() are similar (within some uncertainties) to standard np.linalg.svd.
Minimal Complete Verifiable Example:
import numpy as np
import xarray as xr
import dask.array as da
from matplotlib.pyplot import imshow
data = xr.tutorial.open_dataset(
'air_temperature',
chunks={'lat': 25, 'lon': 25, 'time': -1}
)
temp = data.air
temp = temp.stack(x=('lat', 'lon')).compute()
temp -= temp.mean('time')
# artificial complexification of data
temp = temp + (1j * 0.1 * temp**2)
kernel = np.dot(temp.conj().T, temp) / temp.shape[0]
# standard SVD
u, s, vt = np.linalg.svd(kernel, full_matrices=False)
# dask SVD
dask_kernel = da.from_array(kernel)
k = 100
dsvd = da.linalg.svd_compressed(dask_kernel, k)
u2, s2, vt2 = (x.compute() for x in dsvd)
np.allclose(s[:100], s2) # False
np.allclose(vt[:100], vt2) # False
# visual check: look at first singular vector
v = vt.reshape((temp.shape[1],) + data.air.shape[1:])
v2 = vt2.reshape((k,) + data.air.shape[1:])
# imaginary parts of first singular vector are clearly different
imshow(v[0,:,:].imag, vmin=-1e-3, vmax=1e-3)
imshow(-v2[0,:,:].imag, vmin=-1e-3, vmax=1e-3)Anything else we need to know?:
- For real input, both methods yield the same results.
- When running
svd_compressed()a warning is thrown complaining about complex being casted to real dtypes:
/home/nrieger/anaconda3/envs/xmca/lib/python3.7/site-packages/dask/array/utils.py:108: ComplexWarning: Casting complex values to real discards the imaginary part
meta = meta.astype(dtype)
Environment:
- Dask version: 2021.04.0
- Python version: 3.7.10
- Operating System: Ubuntu 20.04
- Install method: conda
Metadata
Metadata
Assignees
Labels
arraybugSomething is brokenneeds attentionIt's been a while since this was pushed on. Needs attention from the owner or a maintainer.
Activity
jsignell commentedon May 14, 2021
Ping @eric-czech and @RogerMoens since you have both looked at the svd implementation recently.
eric-czech commentedon May 15, 2021
What makes you say that? If I remove the line in your example that casts
tempto imaginary, theallclosestill fails and afiak singular vectors fromnp.lingalg.svdaren't directly comparable to those fromda.lingalg.svd_compressedlike that.You could compare to
da.linalg.svdinstead, but even then the results will only be the same up to possible sign flips. You would have to pass the numpy results through sign coercion as dask does by default now after #6613.nicrie commentedon May 16, 2021
Hi thanks for getting back! You're completely correct with your points, I added
svd_flipto guarantee consistent signs in the solution and, as you suggested, comparedda.linalg.svd_compressedtoda.linalg.svd.I'm aware that
da.linalg.svd_compressedis an approximation and I'm not expecting it to yield the exact results asda.linalg.svd. However, I would expect that they yield similar solutions (what would be the benefit of having such a method otherwise?). I rewrote the MWE a bit to make things clear.Imports
Make two functions for (i) getting the kernel (real and complex) and (ii) performing svd both in standard and compressed form.
perform_svdonly returns the first 5 singular values/vectors for both SVD algorithms.Functions
Perform SVD
realcontains the solution forda.linalg.svd_compressedandda.linalg.svdfor real input,cplxcontains the same but for complex input.Check results
Example: Image of imaginary part of 2nd singular vector
Both figures are using the same colorbar range
For
svdFor
svd_compressedRogerMoens commentedon May 16, 2021
@nicrie: You have not set an iterator for the randomized svd, setting it properly might improve the quality of the fit. Default is the no iterator, as the number of iterations is set to 0. The power iterator or the qr iterator are more precise depending on your singular value spectrum. Secondly, due to its sampling nature you should not compare the left and right singular vectors separately, but rather compare the whole reconstruction A_k w.r.t. the original A, e.g. by a Frobenius or 2-norm. Your maximal absolute deviation therefore doesn't seem appropriate to me. I guess you use it due to the dimensionality of your vectors?
Edit 1: it might as well be that there is a problem with complex valued matrices, I will try some mock-up problem tomorrow. First I need to get acquainted with the complex type svd.
Edit 2: for
np.max(cplx['svd']['s'] - cplx['com_svd']['s'])you inherently assume that the singular vectors of both solutions are properly aligned and ordered w.r.t. each other (standard svd vs. randomized svd), I don't think such statement is generally true.RogerMoens commentedon May 17, 2021
I tried to review the reconstruction and I got:
which is relatively large: 147% and 2.2% relative difference. It seems that the real part is well reconstructed to some extent, but the complex part not. It might be that the sampling of the imaginary part is not appropriate as only the real part is sampled, i.e. we use a real sampling matrix.
I think we have to review lines 720 to 726 in linalg.py for it:
eric-czech commentedon May 17, 2021
I was trying to understand that myself recently and came to the conclusion that I don't think this is true. Afaik, SVD is not unique for non-square matrices so comparison of reconstruction quality is necessary instead of comparing singular vectors.
RogerMoens commentedon May 17, 2021
@eric-czech: The SVD is unique (up to signs) for square, non-square, and complex matrices as long as no singular value pairs (two or more singular values with the same value exist). See Trefethen, L. N. & Bau III, D. Numerical linear algebra, vol. 50 (Siam, 1997).
I am not sure whether randomized methods such as svd_compressed provide unique solutions, as they severely depend on the sampling of the matrix. In my experience they are not unique.
RogerMoens commentedon May 19, 2021
Just checked, the TSQR gives same results for complex matrices as numpy QR. I am not sure whether the sampling for complex matrices should also be a complex matrix.
RogerMoens commentedon May 21, 2021
I think the sampling step is appropriate as is for complex matrices. I have planned to check the tsqr including svd next week:
@nicrie: you could try to compare the outputs with sklearn randomized/compressed/truncated SVD: https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html
@eric-czech: how does the svd flip function handles complex inputs?
eric-czech commentedon May 25, 2021
It should be fine AFAIK since the operations in that function only operate on the real term, so this invariant should be true regardless of the input:
It will preserve the complex dtypes too since it's only using addition, multiplication and axis summation.
RogerMoens commentedon May 27, 2021
Small update: I just checked the tsqr with svd, I think there is a casting in there somewhere that is not appropriate:
gives me
The singular values (s_da) seem to be correct, but the u_da and vt_da are not.
nicrie commentedon May 28, 2021
Thanks for the updates @RogerMoens. I tried to compare with the truncated SVD of sklearn, but their implementation does not support complex data (perhaps for a reason?)
I tried to understand where the
ComplexWarningis coming from, but I realize I don't understand the code sufficiently well.Nevertheless, I narrowed down the thrown warning to final lines of code in TSQR, lines 502 - 517, where
meta_from_arrayis called and causes the casting from complex to real. However, not sure if its really a problem since it affects only the meta information (?):jsignell commentedon Jun 3, 2021
If the error arises before you call
.computethen the meta might be the issue, but I think what you are seeing is not an error, but incorrect results, so I think the meta is not the root of the issue.LUOXIAO92 commentedon Aug 22, 2022
The same issue. But on my case, I reconstructed the matrix using M'=UΣV^† . The real matrix input yields reasonable answer, and it fails for complex matrix input. Here is my code
I calculated the trace and norm of M-M' (M:original matrix; M':M'~UΣV^†) which should be small. On the complex case, difference between M and M' is large.
But on the real case, it yields a reasonable answer.
LUOXIAO92 commentedon Sep 4, 2022
I think I have found the bugs in svd_compressed(). The svd calculation for complex matrix is$A=U\Sigma V^\dagger$ , where $U$ and $V^\dagger$ are complex matrices. The " ${}^\dagger$ " means "Hermitian transpose", which on the case of real matrix reduces to a transpose matrix. While calculating complex matrix svd, we should use Hermitian transpose but not transpose matrix.
At the source code for dask.array.linalg, I found some bugs, and I will figure out the bugs by comments. First, at the "compression_matrix()" function,
Then, at the "svd_compressed()" function,
Here is my code of randomized svd by the use of power iteration
randomized_svd.py
Here is the test code, which compares to the full svd "cupy.linalg.svd" and "dask.array.linalg.svd_compressed"
test.py
The results are:
full svd by using cupy.linalg.svd()
ramdomized svd by using my function "rsvd()"
ramdomized svd by using dask.array.linalg.svd_compressed()
I calculated the trace and error of matrix$M-M'$ , in which $M$ is the original matrix, and
$$M_{ik} \simeq M^\prime_{ik}=\sum_{k=1}^{32} U_{ij} \sigma_{j} V^\dagger_{jk}.$$ $\text{err}=||M-M^\prime||/||M||$ .
The error is defined by
The results show that my code yields a reasonable answer because the trace and error are quite small, and the large singular values are the same as full svd.
By the way, the skinny matrix svd and tsqr seem to be currect because I used them in my code. But I'm not sure if there are the same bugs (at where should use Hermitian transpose, but have used tranpose matrix for complex matrix) in the code.
ncclementi commentedon Sep 6, 2022
@LUOXIAO92 Thank you for the detailed explanation. By looking at the dask code, we are clearly missing the case for complex numbers. I'm not sure what's the best approach to include this case here, but would you be interested in opening a PR?
Maybe @ian-r-rose or @jakirkham might have some input here.
nicrie commentedon Oct 28, 2022
Perhaps I am wrong, but it seems to me that an easy fix such as replacing all expression in the form of
A.TtoA.conj().Tshould do the trick, no?conjcreates the conjugates of a matrix which is the identity matrix for real matrices. Therefore, only complex matrices are affected by the change.I'd still like to get this work so I will try to make a PR if that's really all what's needed.
philipdkennedy commentedon May 7, 2026
Is there any change in this issue from the dask side? I am trying to use complex SVDs within the xeofs package on petabytes of kilometre-scale climate model output and this issue with dask appears to be the critical problem with my entire analysis chain. Without dask I can't realistically handle such large Datasets using python. Also wondering if anyone has come up with a work-around since this issue was opened?
nicrie commentedon May 7, 2026
No udpate from my side. Since a few years have passed since the detection of the bug, it may be worth re-checking whether or not the issues still exists within dask.
EDIT: Seems indeed te still be an open issue: #12335 . May be solved by this PR #12348
nicrie commentedon May 27, 2026
@philipdkennedy this issue has been solved by #12416 . You may want to follow the corresponding xeofs issue to track progress.
philipdkennedy commentedon May 27, 2026
Thanks @nicrie and the dask team too for the help! I keep an eye on the xeofs issue now.