Skip to content

LLM review #1312

Closed
Closed

Description

@jschueller

I ran deepseek on fortran sources, maybe some of these are actually actionable bugs worth fixing

SRC/ Bug Report

Analysis of SRC/ (excluding DEPRECATED/).


Critical

1. Missing RETURN after XERBLA in *gedmd.f90 — all 4 variants

Two NaN-detection blocks call XERBLA but are missing RETURN, inconsistent with standard LAPACK convention (set INFO → CALL XERBLA → RETURN). If XERBLA is replaced by a non-stopping version (common in testing), the code continues to the SVD computation with NaN-laden data and silently produces garbage.

File Lines (NaN X check) Lines (NaN Y check)
SRC/dgedmd.f90 788–792 863–867
SRC/sgedmd.f90 788–792 864–868
SRC/cgedmd.f90 767–771 843–847
SRC/zgedmd.f90 770–774 846–850

Example (dgedmd.f90:788–792):

IF ( DISNAN(SCALE) .OR. DISNAN(SSUM) ) THEN
    K    =  0
    INFO = -8
    CALL XERBLA('DGEDMD',-INFO)   ! ← no RETURN after this
END IF

The all-zero-column check immediately after (dgedmd.f90:823–829) correctly has RETURN.


High

2. XERBLA name mismatch — 'xORBDB' instead of 'DORBDB'

SRC/dorbdb.f:384:

CALL XERBLA( 'xORBDB', -INFO )

The subroutine is named DORBDB, but XERBLA is passed 'xORBDB' with a lowercase x. The error message will print the wrong name.


3. SYMB_ZERO uses wrong index X(J) instead of X(JX) in all *syamv.f INCX≠1 branches

Files: dla_syamv.f, sla_syamv.f, cla_syamv.f, zla_syamv.f

In every INCX != 1 branch (the ELSE blocks starting at ~line 332, both UPLO='U' and UPLO='L' variants), the SYMB_ZERO check uses X( J ) instead of X( JX ).

When INCX != 1, the elements of X are not contiguous. The code correctly uses strided indexing X( JX ) for the accumulation, but the symbolic-zero detection on the very next line checks X( J ) (the flat index without stride):

! BUG: uses X(J) instead of X(JX)
SYMB_ZERO = SYMB_ZERO .AND.
     $    ( X( J ) .EQ. ZERO .OR. TEMP .EQ. ZERO )
! correct: uses X(JX)
Y( IY ) = Y( IY ) + ALPHA*ABS( X( JX ) )*TEMP

Impact: Affects error-bound estimation routines. The symbolic-zero perturbation logic is wrong, potentially adding the underflow-threshold perturbation SAFE1 to results that should be symbolically zero, or failing to add it when needed.


4. Complex *wwaddw.f — (S+S)-S trick is a no-op for COMPLEX types

Files: cla_wwaddw.f:101-102, zla_wwaddw.f:100-101

The classic double-word addition trick S = (S+S) - S is designed to force IEEE rounding. For complex types, Fortran component-wise arithmetic means:

  • S = a + bi
  • S+S = (2a) + (2b)i
  • (S+S)-S = (2a-a) + (2b-b)i = a + bi = S (exact, no rounding)

So S = (S + S) - S is an identity for complex numbers. The error-free split of X(I) + W(I) into high and low parts fails silently for complex inputs. The Y(I) component (the "low" word) will be garbage rather than containing the rounding error.

Note: The Makefile (line 636–639) compiles these with FFLAGS_NOOPT, suggesting the trick already has portability concerns even for real types.


Medium

5. Integer overflow: EMPTSW = N*(N-1)/2 in *gesvj.f and *gsvj0.f

All variants compute:

EMPTSW = ( N*( N-1 ) ) / 2

For N > 46340, N*(N-1) overflows 32-bit integer arithmetic before the division.

File Line
SRC/{d,s,c,z}gesvj.f 684–718
SRC/{d,s,c,z}gsvj0.f 317–322

6. Division by zero in *gejsv.f, *gesvj.f, *geev.f, *geevx.f, *stein.f

Pattern: ONE / DNRM2(...) (or SCNRM2/DZNRM2) without checking for zero norm.

Example (SRC/dgejsv.f:1245):

XSC = ONE / DNRM2( M, U(1,p), 1 )
CALL DSCAL( M, XSC, U(1,p), 1 )

If a column of U is zero (rank deficiency or numerical error), DNRM2 returns 0, producing XSC = +Inf.

Affected: {d,s,c,z}gejsv.f, {d,s,c,z}gesvj.f, {d,s,c,z}geev.f, {d,s,c,z}geevx.f, {d,s,c,z}stein.f


7. Missing DROUNDUP_LWORK in dstedc.f

SRC/dstedc.f:271:

WORK( 1 ) = LWMIN

But SRC/sstedc.f:272 uses:

WORK( 1 ) = SROUNDUP_LWORK(LWMIN)

The double-precision version does not round up the workspace return value via DROUNDUP_LWORK. Same issue at line 470. The function DROUNDUP_LWORK exists in INSTALL/droundup_lwork.f.


Low

8. Preprocessor inconsistency in la_xisnan.F90

#ifdef USE_IEEE_INTRINSIC     ! checks if DEFINED
#elif USE_ISNAN               ! checks if NON-ZERO (different semantics!)

#elif USE_ISNAN evaluates the macro value, while #ifdef USE_IEEE_INTRINSIC checks if it's defined. If USE_ISNAN is defined via -DUSE_ISNAN (no value), this causes a preprocessor error or silently takes the wrong branch. Should be #elif defined(USE_ISNAN).

File: SRC/la_xisnan.F90:15,21,39,45


9. Trailing spaces in XERBLA name strings

Several files pass subroutine names with trailing spaces to XERBLA. While LEN_TRIM masks the issue in output, it's inconsistent.

Examples: 'CSYSV_ROOK ', 'CGGES ', 'SSBEV_2STAGE ', 'SGELST ', 'ZHPEV ', 'ZGGEV3 ', 'DSPSV ', 'ZSPSV ', 'ZHESV ', 'CHFRK ', 'DLA_GBAMV '.


10. Double increment of LGN in dlaed0.f / slaed0.f

SRC/dlaed0.f:278-281 / slaed0.f:278-281:

LGN = INT( TEMP )
IF( 2**LGN.LT.N ) LGN = LGN + 1
IF( 2**LGN.LT.N ) LGN = LGN + 1

The second increment is only needed when INT(TEMP) underestimates by 2 due to floating-point roundoff (extremely rare). For N=3: TEMP=1.585, LGN=1, first inc gives 2, second inc gives 3 (2^3=8 >> 3), over-allocating workspace by one level. Technically safe but wastes N*lgN slots.


General Observations (no bugs found)

Category Verdict
*disnan.f / *sisnan.f / *laisnan.f Clean — standard x /= x idiom
*ladiv.f (complex division) Clean — Baudin-Smith algorithm, scaling cancels as designed
*las2.f / *lasv2.f (2x2 SVD) Clean — well-guarded against edge cases
*lanv2.f (2x2 eigenvalues) Clean — safe
*laqr*.f series Clean — no off-by-one errors
*laqz*.f series Clean — no array indexing bugs
*trsyl.f / *trsyl3.f Clean — consistent
*trsen.f Clean — correct sensitivity bounds
*sfrk.f / *hfrk.f (RFP format) Clean — correct indexing in all 16 branches
*tfttp.f / *tpttf.f (format conversion) Clean — no off-by-one errors
*lassq.f90 (scaled square sum) Clean — Anderson 2017 algorithm correct
ilaenv.f / ilaenv2stage.f / iparmq.f Clean
*getsqrhrt.f Clean — workspace bounds correct

BLAS/SRC Bug Report

Analysis of BLAS/SRC (excluding DEPRECATED/ and TESTING/).


1. CMakeLists.txt:108 — SBLAS3 spuriously included in double-precision build

list(APPEND SOURCES
     ${DBLAS1} ${DB1AUX} ${ALLBLAS} ${DBLAS2} ${DBLAS3} ${SBLAS3})

When only BUILD_DOUBLE is enabled (without BUILD_SINGLE), the single-precision Level 3 BLAS routines (sgemm, ssymm, ssyrk, strsm, etc.) are still compiled into the BLAS library. This appears to be a copy-paste error — SBLAS3 should not be in the BUILD_DOUBLE section. While the object files may be ignored at link time, they bloat the build and may cause unexpected symbol exports.


2. dnrm2.f90:166 — Dead code condition

if ( (amed > zero) .or. (amed > maxN) .or. (amed /= amed) ) then

maxN is defined as huge(0.0_wp). The condition amed > maxN can never be true for any finite IEEE value (including Inf — comparisons with Inf return false). The subexpression is dead code. The intent appears to have been to detect special IEEE values, but the test doesn't accomplish that. This condition is repeated identically at line 175.


3. drotmg.f:226 / srotmg.f:226 — Inconsistent ABS usage in scaling loops

First scaling loop (DD1):

DO WHILE ((DD1.LE.RGAMSQ) .OR. (DD1.GE.GAMSQ))

(no ABS)

Second scaling loop (DD2):

DO WHILE ((DABS(DD2).LE.RGAMSQ) .OR. (DABS(DD2).GE.GAMSQ))

While both DD1 and DD2 should be non-negative at this point, the inconsistency is a code quality issue and suggests one of the loops may be wrong. If a negative value somehow reached the second check due to rounding, the DABS wrapper would prevent a missed/infinite loop, while the first loop lacks this protection.


4. srotmg.f:119 — Imprecise GAMSQ constant for single precision

DATA GAM,GAMSQ,RGAMSQ/4096.E0,1.67772E7,5.96046E-8/

GAMSQ ≈ 1.67772×10⁷ but the exact value 2²⁴ = 16777216. The error is ~16 (0.0001%). The comment says this is intentional since these are only used for size testing, but the double-precision counterpart (drotmg.f:119) uses the exact value 16777216.D0. This asymmetry could cause the single-precision scaling loop to iterate slightly differently than intended.


5. sskewsymm.f:171 / dskewsymm.f:171 — Wrong documentation group tag

*> \ingroup skewhemm

The group is named skewhemm (a mix of "skew" and "hemm" — Hermitian matrix multiply), but this is a skew-symmetric routine dealing with real matrices. Causes incorrect cross-referencing in generated docs.


6. dskewsyr2k.f:303 / sskewsyr2k.f:303 — Comment describes wrong sign pattern

! Form  C := alpha*A*B**T + alpha*B*A**T + C.

The documented operation is:

C := -alpha*A*B**T + alpha*B*A**T + beta*C

The comment is missing the negation on the first term. The actual code at lines 320-322 correctly computes -A(I,L)*TEMP1 + B(I,L)*TEMP2 with the negation, but the misleading comment could cause confusion during maintenance.


General Observations (no bugs found)

  • Standard BLAS (xGEMM, xGEMV, xGER, xAXPY, xDOT, etc.): All correct — well-tested reference implementations.
  • Skew-symmetric routines: The mathematical derivations from symmetric counterparts are correct. Verified indexing for both UPLO cases and both INCX/INCY stride patterns.
  • New F90 routines (icamax.f90, izamax.f90, dnrm2.f90, rotg.f90): NaN/Inf handling and scaling logic are correctly implemented.
  • Banded routines (xGBMV): Index mapping between band storage and logical (row, column) is verified correct.
  • xERBLA, xERBLA_ARRAY, LSAME, DCABS1/SCABS1: No issues.

Activity

  1. rmlarsen commented on Sep 8, 2026

    @rmlarsen
    Contributor

    AI attribution: OpenAI GPT-6, running as the Codex coding agent, produced this report and performed the source inspection and local test runs described below.

    I checked all 16 numbered findings against LAPACK commit 64ca1efc5a7dd7e5a899af3f1c75a2c4eca93c60, with source inspection and focused GNU Fortran reproductions. SRC items 1, 3, and 5 are real functional bugs; item 2 and BLAS item 6 are diagnostic/documentation mistakes. SRC item 7 matters for ILP64. Several other claims are false positives, and the broad claim in SRC item 6 needs a more specific reproducer and root cause.

    Two findings extend beyond the files listed in the issue: the strided indexing error also affects CLA_HEAMV and ZLA_HEAMV, and the incorrect xORBDB diagnostic name also occurs in SORBDB, CUNBDB, and ZUNBDB.

    The SRC findings:

    Item Assessment Evidence and scope
    1. Missing error returns in *GEDMD Confirmed in S/D/C/Z. With a returning XERBLA, both NaN paths continue and overwrite the original error. My 2-by-2 tests return K=2, INFO=4, after reporting argument 8 or 10. Adding the two missing RETURNs produces K=0, INFO=-8/-10 in all eight cases. This is an error-path bug; the issue's “critical” classification is overstated. DGEDMD source.
    2. xORBDB diagnostic name Confirmed, low severity; four routines. DORBDB, SORBDB, CUNBDB, and ZUNBDB all pass this literal. An invalid M call to DORBDB reports xORBDB, argument 3, and correctly returns INFO=-3. The numerical path is unaffected. DORBDB, ZUNBDB.
    3. Strided symbolic-zero detection Confirmed in all four *LA_SYAMV routines and both *LA_HEAMV routines. In the nonunit-stride branches, replace X(J) with X(JX) in the symbolic-zero checks. Tests cover upper/lower storage, INCX=±2, INCY=1/-2, and both spurious and missing safety perturbations. All 96 cases fail before that replacement and pass afterward. Existing in-tree refinement callers use INCX=1, so these reproductions establish the auxiliary routines' strided bug, not incorrect bounds from those callers. DLA_SYAMV, ZLA_HEAMV.
    4. Complex *LA_WWADDW The claimed complex-specific defect is false. Componentwise arithmetic applies the same compensated addition to the real and imaginary parts. In ordinary binary arithmetic without overflow, (s+s)-s is also an identity for a real, already-rounded s; that does not imply the subsequent residual calculation is zero or garbage. Both complex precisions correctly retain the small addend in the low word in the test below. This is not a claim of correctness for arbitrary magnitudes or reassociating compiler options. CLA_WWADDW.
    5. EMPTSW integer overflow Confirmed; correct the threshold. For signed 32-bit integers, the first overflowing product is at N=46342, not 46341. At N=50000, the product is 2,499,950,000, while the desired quotient 1,249,975,000 fits. The expression traps with -ftrapv. All eight listed sources have it; an overflowed threshold can corrupt the NOTROT >= EMPTSW convergence decision. Divide the even factor first, or use sufficiently wide arithmetic. The final count itself exceeds signed 32-bit range starting at N=65537, which also needs consideration. I did not run a full SVD at these dimensions. DGESVJ expression, convergence test.
    6. Reciprocal norms The blanket diagnosis is unsubstantiated; a separate *STEIN underflow failure is reproducible. Rank deficiency does not imply a zero singular/eigenvector. For example, the cited GEJSV path completes the null-space basis before normalization; GESVJ normalizes only the selected nonzero left singular vectors and constructs right vectors from rotations. All 160 ordinary/zero/rank-deficient test calls across the 20 named routines passed. Direct subnormal *STEIN calls do fail in all four precisions, as detailed below, but the first invalid operation is in the earlier RHS scaling, not the final reciprocal norm. GEJSV basis completion, DSTEIN scaling.
    7. DSTEDC workspace rounding Valid for ILP64; harmless for ordinary 32-bit integers. Every signed 32-bit integer is exactly representable in binary64. For 64-bit integers above 2^53, conversion can round down. An actual ILP64 workspace query with COMPZ='I', N=100000000 requires 10,000,000,400,000,001 elements but returns 10,000,000,400,000,000. DROUNDUP_LWORK returns 10,000,000,400,000,002. This query needs no huge allocation; an actual workspace of that size would require about 80 PB. DSTEDC.
    8. USE_ISNAN preprocessing The stated -DUSE_ISNAN failure is false for GNU preprocessing. A command-line -DNAME defines NAME to 1. gfortran -E -cpp -DUSE_ISNAN SRC/la_xisnan.F90 succeeds and selects the intrinsic. -DUSE_ISNAN=0 selects the fallback. A literally empty replacement such as #define USE_ISNAN is different and could justify consistency cleanup, but is not the reported command-line case.
    9. Trailing blanks in routine names Cosmetic. Reference XERBLA trims names for output, and Fortran character comparisons pad the shorter operand with blanks. Thus the usual LAPACK error tests also accept these names. XERBLA, test comparison.
    10. Repeated LGN correction False. Each IF evaluates the updated LGN. At N=3, the sequence is 1 → 2 → 2; the second condition is false because 4 < 3 is false. The alleged extra workspace level does not occur. DLAED0.

    The BLAS findings:

    Item Assessment Evidence and scope
    1. SBLAS3 in a double build Required dependencies are being mistaken for a bug. Double builds include the mixed precision drivers DSGESV and DSPOSV, plus single precision LU/Cholesky helpers. Those need SGEMM, STRSM, and SSYRK. Removing ${SBLAS3} wholesale breaks those dependencies. The list could potentially be narrowed, but its presence is not a copy/paste error. Mixed precision helper list, double build selection, SPOTRF dependencies.
    2. DNRM2 condition Redundant term, incorrect explanation, no demonstrated numerical bug. Positive infinity is greater than the largest finite number. amed > maxN is redundant here because it implies amed > 0; it is not an impossible comparison. The NaN test is distinct. Runtime checks confirm Inf > HUGE(...) and that the reference norm of (1, Inf) returns Inf. DNRM2.
    3. ROTMG absolute values False. D1 is kept nonnegative, whereas D2 can legitimately remain negative. For example, D1=2, D2=-1, X1=2, Y1=1 returns D1=16/7, D2=-8/7 on the regular branch. The second scaling loop needs ABS; the first does not need it for the same reason. DROTMG.
    4. SROTMG constants Documented design, no demonstrated defect. These are size-test thresholds; the actual scaling uses GAM**2. The routine explicitly allows inexact thresholds. A slightly different number of scaling steps is not by itself a correctness failure. SROTMG explanation.
    5. skewhemm documentation group False. The group is explicitly defined to include both skew-Hermitian and skew-symmetric matrix multiplication, following the shared {he,sy}mm grouping convention. Group definition.
    6. *SKEWSYR2K comments Confirmed documentation-only mistake. The implementation subtracts the first product correctly. The comments in both transpose branches should have that minus sign and the beta*C term. DSKEWSYR2K.

    For the additional *STEIN case, take T = [[0,t],[t,0]], where t is the smallest positive subnormal, and request the exact eigenvalue -t with IBLOCK(1)=1, ISPLIT(1)=2. All S/D/C/Z variants return NaN eigenvectors with INFO=0. The first RHS scale underflows to zero, wiping out the starting vector; a subsequent iteration evaluates 0/0. Trapping invalid operations stops at DSTEIN/SSTEIN line 374 and CSTEIN/ZSTEIN line 385. Scaling the same problem to t=1 gives the expected unit eigenvector, approximately (0.70710678,-0.70710678). This uses a hand-supplied exact eigenvalue and block description, not DSTEBZ's numerically split output. It demonstrates a direct auxiliary-routine limitation and does not establish the same failure in drivers that scale their input.

    For *LA_WWADDW, use X=(1,2), Y=(0,0), and W=(epsilon/4,epsilon/2), where each pair denotes real and imaginary parts. The tested complex routines leave the high word unchanged and return the entire W in the low word, exactly. Thus the particular claim that componentwise complex arithmetic destroys the low word is directly contradicted by the implementation and this test.

    Validation used GNU Fortran 13.3.0 on x86-64 Linux/WSL2, with an Intel Core i7-13700HX reported by the guest. The tested routines were compiled from the pinned source with -O0 -g -fcheck=bounds; existing reference LAPACK/BLAS Release libraries at f96546fc9759c4ead253950caaaeff99b8e71abb supplied dependencies. Comparing the source snapshots found differences only in the unrelated *TPRFB/*TPMLQT families. Integer-expression tests additionally used -ftrapv; the STEIN diagnostic reruns used -ffpe-trap=invalid,zero. The DSTEDC query was compiled with -fdefault-integer-8 and ILP64-compatible query dependency stubs, with sentinels for routines the query must not call. This was focused validation, not a full test-suite run, full ILP64 build, or proof that the report's broad “no bugs found” observations hold.

    Compact double precision reproducer for GEDMD, SYAMV, and direct STEIN

    Save the following as repro1312.f90. With reference libraries already built, compile it from the LAPACK source root using:

    gfortran -O0 -g -fcheck=bounds repro1312.f90 \
      SRC/dgedmd.f90 SRC/dla_syamv.f SRC/dstein.f \
      /path/to/liblapack.a /path/to/libblas.a -o repro1312
    ./repro1312
    program repro1312
      use, intrinsic :: ieee_arithmetic
      implicit none
      double precision :: x(2,2), y(2,2), z(2,2), b(2,2), v(2,2), s(2,2)
      double precision :: wr(2), wi(2), res(2), work(2000), tol
      double precision :: a(2,2), xs(3), ys(2), d(2), e(1), w(1), t
      integer :: iw(2000), iblock(1), isplit(2), ifail(1), k, info
      logical :: invalid
    
      x=0; x(1,1)=1; x(2,2)=1; y=x
      x(1,1)=ieee_value(0d0,ieee_quiet_nan)
      tol=epsilon(1d0)
      call dgedmd('S','N','N','N',1,2,2,x,2,y,2,-1,tol,k,wr,wi, &
                  z,2,res,b,2,v,2,s,2,work,2000,iw,2000,info)
      print *, 'GEDMD K,INFO:',k,info
    
      a=0; a(2,2)=tiny(1d0)
      xs=0; xs(3)=tiny(1d0); ys=0
      call dla_syamv(121,2,1d0,a,2,xs,2,0d0,ys,1)
      print *, 'SYAMV missing safety term:',ys(2),'expected',3*tiny(1d0)
      xs=[0d0,1d0,0d0]; ys=0
      call dla_syamv(121,2,1d0,a,2,xs,2,0d0,ys,1)
      print *, 'SYAMV spurious safety term:',ys(2),'expected',0d0
    
      t=nearest(0d0,1d0)
      d=0; e=t; w=-t; iblock=1; isplit=[2,0]
      call ieee_set_flag(ieee_all,.false.)
      call dstein(2,d,e,1,w,iblock,isplit,z,2,work,iw,ifail,info)
      call ieee_get_flag(ieee_invalid,invalid)
      print *, 'STEIN INFO,invalid,vector:',info,invalid,z(:,1)
    end program
    
    subroutine xerbla(name,info)
      implicit none
      character(*) :: name
      integer :: info
      print *, 'XERBLA: ',trim(name),info
    end subroutine

    On the pinned source, GEDMD reports the initial argument-8 error, continues through further errors, and returns K=2, INFO=4. SYAMV returns zero where approximately 6.6752215755216041e-308 is required, and that nonzero value where exact zero is required. STEIN returns INFO=0, raises invalid, and returns two NaNs.

  2. jschueller commented on Sep 8, 2026

    @jschueller
    CollaboratorAuthor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions