Repository navigation
Description
Description
xLARFGP computes a Householder reflector. Given an input vector x of dimension m, xLARFGP computes H = I - β vv^* such that
H x = ‖x‖ e1andv(1) = 1,
where β is a scalar and v is a vector.
#934 attempted to fix an overflow when 0 ≪ ‖x(2:m)‖ ≪ x(1) ≪ 1 by settings x(2:m) to zero under certain conditions. This does not resolve the issue. For example, let m = 2 and x = [ε^4, 2 ε^5], then an overflow takes place in the following code when 1 / ALPHA is computed:
Line 224 in ae9c818
| CALL SSCAL( N-1, ONE / ALPHA, X, INCX ) |
From the point of view of mathematics, this line should simply compute
- x / (x(1) - ‖x‖) if x(1) < 0,
- -x / [‖x(2:m)‖² · (x(1) + ‖x‖)] otherwise.
(See, e.g., Matrix Computations, 4th edition, Algorithm 5.1.1). Obviously the divisions cannot overflow and now the problem source becomes evident: the computation of the reciprocal of ALPHA. The use of, e.g., SLASCL in the case of INCX = 1 resolves the problem.
Minimal example demonstrating the problem (compile with cc -Wextra -Wall -std=c99 -pedantic -llapack -lm):
#include <math.h>
#include <stddef.h>
#include <stdio.h>
typedef int lapack_int;
void slarfgp_(
lapack_int* n,
float* alpha,
float* x,
lapack_int* incx,
float* tau);
#define N 2
int main()
{
float nan = NAN;
float eps = ldexpf(1.0f, -23);
lapack_int n = N;
float x[N] = { powf(eps, 4.0f), 2.0f * powf(eps, 5.0f) };
lapack_int incx = 1;
float tau = nan;
printf("input=[%.2e; %.2e]\n", x[0], x[1]);
slarfgp_(&n, x + 0, x + 1, &incx, &tau);
printf("output=[%.2e; %.2e]\n", x[0], x[1]);
printf("tau=%.2e\n", tau);
if(isinf(x[1])) {
fprintf(stderr, "x[1] is infinite!\n");
}
}Checklist
- I've included a minimal example to reproduce the issue
- I'd be willing to make a PR to solve this issue
Activity
langou commentedon Nov 12, 2023
Hi @christoph-conrads, would SRC/srscl.f do the job too? @langou
langou commentedon Nov 13, 2023
I did some digging and the issue with LARFGP are mentioned in
https://www.netlib.org/lapack/bug_list.html#_strong_span_class_green_bug0037_span_strong_xlarfp_and_scaling which reads:
And then
christoph-conrads commentedon Nov 13, 2023
Thank you for providing this reference. Apparently the changes to xLARFGP are on target whereas the changes to xORBDB5 and xORBDB6 from #930 are just working around the problem.
After reading the linked messages, reading §2 in LAWN 203 where xLARFGP is introduced, and reviewing my test data, I claim that the problem is caused by the current implementation handling only some of the possible under- and overflows.
For example, in the first message in this issue the expression
ONE / ALPHAis observed to overflow. The suggested fixSLASCL( CFROM=ALPHA, CTO=ONE, X )does not work becauseALPHAis subnormal in my test case; the computed vector entries are off by factor two. The problem could be avoided by computingSLASCL( CFROM=XNORM, CTO=-ALPHA/XNORM, X )andSLASCL( CFROM=ALPHA, CTO=ONE, X ), respectively, depending on which branch is taken in line 192.To resolve this issue, I will go through the xLARFGP code line by line and check if one can trigger over- or underflows. Luckily dimension-two inputs suffice to trigger these problems.
On the upside I previously claimed that
SLASCLcan replace calls toSSCALonly ifINCX = 1. This is not true:LDAtoINCX.christoph-conrads commentedon Nov 18, 2023
Computations with Householder reflectors by xLARFGP are only conditionally backward stable. The problem is not the computation of the reflector itself but the entries large in modulus it can contain. Those large entries in turn cause the loss of significant digits when the reflector is applied (e.g., with xLARF). Consequently, the problems with xLARFGP are not necessarily evident by looking only at the xLARFGP output.
The text is structured as follows:
tl;Dr Householder reflectors computed by xLARFGP can contain values with very large modulus when
x(1) > 0andx(1) ≈ ‖x‖. This can cause overflows during the reflector computation or later a loss of accuracy when the reflector is used by.Notation
Given a vector
x, xLARFGP computes a vectorvsubject tov(1) = 1and a scalar τ such thatvis an elementary Householder reflector withI - τ v v^* x = β e₁, whereβ = ‖x‖. In contrast to xLARFG (note the missing P in the subroutine name) β is constrained to be nonnegative.A 2x2 Example
Consider the following matrix in single precision:
This example was derived from the failing test that led to the creation of this issue. The constants 10/11 and 12/10 are tuned values from the test data; their most important properties are
|A(2,1)| > ε |A(1,1)|to avoid triggering a zero check in SLARFGP added in Make vector orthogonalization more reliable #930 (seeslarfgp.f).The QR decomposition computed by SGEQRF with SGEQR2 patched to use SLARFGP is as follows:
Note the very large value in modulus in the first column; this is the
v(2)entry of the first reflector. The Householder matrix assembled by SORGQR from this data looks as follows:There are two things of note in this matrix that should be orthogonal:
v(2)entry looks fine and its norm is within the acceptable bounds of rounding errors.The orthogonal matrix computed by SGEQRF, SORGQR, and SLARFGP is inaccurate.
An Explanation
The computation of Householder matrices is in general known to be backward stable. This section will discuss which assumptions made in the numerical linear algebra literature are not met by a Householder reflector computed with a nonnegative β. Specifically, I will refer to the proofs in "Accuracy and Stability of Numerical Algorithms", 2nd Edition, 2002, by Nicholas J. Higham (ASNA for short) in §19.3 "Error Analysis of Householder Computations".
There exist three points of divergence when ε must be nonnegative.
vis assumed to be √2 (see the paragraph after Lemma 19.1) whereas the LAPACK implementation constructs a reflector withv(1) = 1.vis applied as(√τ v)(√τ v)^*whereas SLARF computesy - τ (v (v^* y)).The norm of the reflector is significant in Lemma 19.2; this lemma proves a small backward error when
(I - τ v v^*) yis computed for an arbitrary vectory.Let us first consider the case of xLARFG:
1 ≤ τ ≤ 2. Thus, thus the computation ofy - τ (v (v^* y))by SLARF should not deliver results that differ significantly from the computationy - (√τ v)(√τ v)^* yin ASNA.In summary, there is a close match between the assumptions in ASNA and the actual LAPACK implementation.
Next, we examine the behavior with xLARFPG when x(1) is positive (if x(1) is negative, then it behaves identically to xLARFG and is numerically backward stable):
vis nearly unconstrained becausex(1) - ‖x‖can be very small. Thus the result ofv(i) = x(i) / (x(1) - ‖x‖)can be very large in modulus. This implies large intermediate values in computations and a backward error that is much larger than the one calculated in ASNA Lemma 19.2.x - τ (v (v^* x))and the modulus τ is nearly unconstrained again.In summary, the proofs concerning the backward stability of Householder matrix-related calculations in ASNA cannot be used when reflectors are computed by xLARFGP and
x(1) > 0andx(1) ≈ ‖x‖.Suggested Fixes
In general, I do not see how to fix xLARFGP. Possible work-arounds are:
Appendix
The Python program below computes the QR decomposition of a 2x2 matrix and explicitly forms the Householder matrix Afterwards. The purpose of the program is to be able to play with the values in the first matrix column after replacing the call to SLARFG with a call to SLARFGP in SGEQR2.
Usage:
python3 sgeqr-demo.pyorpython3 sgeqr-demo.py /path/to/liblapack.so.langou commentedon Nov 19, 2023
Thanks for all this work Christoph, and taking the time to explain.
Three follow-up question/comment's.
(1) Would another representation of the Householder reflector be better? So right now LAPACK decides that the Householder vector is such that the top element is always a 1, but other choices are possible. See for example,
The Computation of Elementary Unit Matrixby Rich Lehoucq, ACM Transactions on Mathematical Software, Volume 22, Issue 4, pp 393–400, https://doi.org/10.1145/235815.235817, where Rich Lehoucq explains four previous representations (1) Wilkinson's approach, which is also used in EISPACK, (2) LINPACK approach, (3) NAG approach, (4) LAPACK approach. Or maybe another approach would help. I agree that this does not seem to help, but since I am not sure I wanted to ask.(2) I would be in favor of spending some time to implement
Always use the safe sign choice and hiding a sign bit for τ somewhere in the data as suggested by Pat Quillen.How does that work for complex numbers though? It seems that for complex numbers we need more than a bit. Shall we just store an extra vectors of scalars (all of modulus 1, so +/-1 in real and e^(i.theta) in complex) along τ then?(3) To some extent these signs are already in the output of GEQRF (or LARFG) . . . they are on the diagonal of R. So we could return the signs on the diagonal of R, being understood that
of coursethe diagonal entries of R are real nonnegative. And we are only storing the signs on the diagonal of R to save space. This sounds like a bad idea. And I would more be in favor to store an extra array for these signs, and then have the diagonal of R real.We can add this on the wish list.
christoph-conrads commentedon Nov 19, 2023
(1) Frankly I do not want to look at alternative representations now and finish #406 before involving myself in something else. Besides the current representation has very nice properties (the first reflector element is known to be one which allows for compact QR/QL/... representations, the reflector norm is close to one, and 1 ≤ τ ≤ 2).
(2) The issue when computing a reflector
Hx = β e₁is not computing a real β but the choice of the sign. (In fact, LAPACK computed real β until version 3.1.1 according to LAWN 203.) If it was not for the fixed computation ofI - τ v v^*, the issue would be trivial to fix, e.g., byx(1)with -1 by means of a matrix multiplication from the left side,xwith -1 by means of a matrix multiplication from the right side,τ v v^* - I.edit Now I see what you mean. τ is complex in the complex case. I need to think about this. /editIn the complex case, 1 ≤ Re(τ) ≤ 2 and only the sign bit of the real part of τ would need to be modified.
[The preceding paragraph mentions matrix multiplications from the left or the right. The idea is that
xis the first column of a matrix whose columns are about to be orthonormalized.]In the current code, τ never has its sign bit set and one could exploit this unused bit of information to request the computation of
|τ| v v^* - Iin the SLARF* subroutines. This would work as follows:x(1) > 0, then set the sign bit of τ.I - |τ| v v^*or|τ| v v^* - I, respectively.Note that this suggestion requires a float representation where +0 and -0 can be distinguished. Checking for
τ < 0is insufficient (think ofx = [-1, 0]).The advantages of this approach are as follows:
xLARFG.Disadvantages:
(3) The most important call site for xLARFGP are the functions for the CS decomposition and they do not compute QR decompositions.
christoph-conrads commentedon Nov 19, 2023
Two scenarios come to mind how this might happen:
The change would only affect users of xLARFGP though.
christoph-conrads commentedon Dec 13, 2023
A 3x3 Example with Rapid Divergence
The stability proofs for the computations of QR decomposition by means of Householder reflections do not apply when the sign choice by slarfgP is used. In this post, I demonstrate the results with specially a crafted matrix
Aand a unit-norm vectorxsuch that computations involving the orthogonal factor of the QR decomposition diverge much more rapidly during the computations of matrix-vector productsQᵏ xin finite-precision arithmetic if slarfgP is employed instead of slarfg with its safe sign choice, whereQis the orthogonal factor of a QR decomposition based on Householder reflections ofA. The effect is present for both the factored representation and the explicitly formed representation of the orthogonal factor.Qwill denote the orthogonal factor of a QR decomposition in its factorized form whereasPwill denote the same factor after a call to xORGQR. The index+denotes matrices computed by slarfgP. The Euclidean norm is used throughout this post.Reminder: in real arithmetic, it holds that
‖x‖ = ‖Qᵏ x‖for any integerk,x = Q² x.Maximizing Inaccuracy with slarfgP
Based on my previous posts, inputs
xandAwere devised such thatQ₊ xis as inaccurate as possible. More concretely, each columnathat is used for the computation of a Householder reflector must have the following form:‖a‖ ≪ 1‖a(2:)‖ > ε ‖a(1)‖‖a(2:)‖ ≪ ‖a(1)‖.With a lot of trial-and-error, the following 3x3 matrix
Aand vectorxwas crafted (NB: crafted, not constructed. A lot of trial-and-error was involved.):Vector x:
Growth of Vector Norm
When computing
‖Q^k x‖, the norm grows in every iteration when slarfgP is used (see table below) and the norm grows quickly beyond what is considered an acceptable rounding error. No such effect can be observed with slarfg and for this reason, there is no column for this method in the table below. Obviously, ifQ₊ᵏ xgrows strictly monotonously in norm, thenx = Q₊²ᵏ xcannot hold. Furthermore, the growth in norm is still present though less pronounced after explicitly forming the orthogonal factorP₊.It holds that
|‖Q₊²ᵏ x‖ - 1| ≤ ‖x - Q₊²ᵏ x‖implying that the result of repeated multiplications is quickly becoming inaccurate.k‖Q₊ᵏ x‖ - 1‖P₊ᵏ x‖ - 1Divergence of Multiplication Result
In the next experiment
‖x - Qᵏ x‖,‖x - Qᵏ x‖and‖x - 1/l P₊ᵏ x‖are computed for evenk, wherel = ‖Q₊ᵏ x‖orl = ‖P₊ᵏ x‖, respectively. The previous experiment showed that when slarfgP is employed,lwill be different from one. This paragraph demonstrates that in addition to a growth in norm of the multiplication result, the computed result is increasingly inaccurate when slarfgP is used (even after normalization). The effect is again less pronounced when the orthogonal factorP₊is explicitly formed.The table below does not contain a column for results involving
P(the explicitly formed orthogonal factor computed by slarfg) because the results withPandQare indistinguishable at the accuracy level of the table.k‖x - Qᵏ x‖‖x - 1/l Q₊ᵏ x‖‖x - 1/l P₊ᵏ x‖Appendix: QR decomposition with slarfgP
Appendix: Python Code
Run the code with
python3 /path/to/lapack/library <k>.slarfgp/dlarfgp: avoid overflow when computing 1/ALPHA