Core: Limit AVX-512 TRSM to initialized right-hand sides

libeigen/eigen!3632

Co-authored-by: Rasmus Munk Larsen <rmlarsen@gmail.com>
Co-authored-by: failed33 <125191796+failed33@users.noreply.github.com>
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c1d92c2..e2395d3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -53,6 +53,7 @@
 - Copying from an empty `Tensor`, as when one is assigned to an empty slice, passed a null pointer to `memcpy`, which is undefined behavior [#3411, !3643]
 - `AMDOrdering` with 32-bit indices, and so the `Simplicial*` Cholesky solvers and `IncompleteCholesky`, which use it by default, and `IncompleteLUT`, could stall for minutes and then crash on matrices with a few hundred thousand columns or more: on a node with fewer than 10*sqrt(n) neighbours, most of them at high indices, the signed supervariable hash overflowed and indexed the workspace out of bounds. The hash is now unsigned, as in SuiteSparse AMD, and orderings that did not overflow are unchanged
 - In Eigen's LAPACK library, `xLARFB` with `DIRECT = 'B'` applied the reflectors at the wrong rows when the implicit unit diagonal of `V` was stored as zero [!3502]
+- The AVX-512 triangular solve with a matrix right-hand side read uninitialized scratch memory when the number of right-hand sides was not a multiple of the packet size, which could raise spurious floating-point exceptions [!3632]
 - In Eigen's LAPACK library, `xLADIV` returned NaN or zero for operands near the overflow threshold; `xLAPY2` returned infinity for an infinite and a NaN argument; `xPOTRF` reported success for a NaN pivot; `xGESDD` returned `INFO = 0` for a matrix containing NaN, where reference LAPACK returns `-4`; `xGESDD` returned uninitialized outputs for a matrix containing Inf, and `xGESVD` zero singular values for one containing Inf or NaN, where reference LAPACK returns NaN singular values for Inf (both routines now return NaN outputs with `INFO = 0`); and `ILAVER` reported 3.4.1 instead of 3.12.1, the reference release the routines follow [!3502]
 - Eigen's BLAS library departed from Reference BLAS on special values and zero increments: `?axpy` and `?gemmtr` read their operands when `alpha` is zero, so an infinite or NaN operand made the result NaN; `?copy` with `incy = 0`, and `?swap` and `?axpby` with a zero increment, did nothing; `?trsm` applied `alpha` after the solve and could overflow where the result does not; real `i?amax` returned an ISA-dependent index for vectors holding NaN; `crotg` and `zrotg` returned NaN for large representable inputs and used the conventions of Reference BLAS before 3.10; `csrot`, `zdrot`, `?herk` and `?her2k` applied their real factor through a complex multiplication, producing NaN from infinite components; and `?rotmg` could loop forever on infinite input [!3505]
 - Tensor freed memory twice or used it after it was freed when an allocation or a user functor threw: in `TensorBlockScratchAllocator`, `TensorStorage::resize()`, `TensorRef`, a full reduction on `ThreadPoolDevice` and the `DefaultDevice` executors. Scan, `customOp` and block evaluation assigned scalars that require initialization into memory that was never constructed; such scalars now take the coefficient path. A `Tensor` assignment that changes the dimensions evaluated into the destination it had just resized, which the expression could still read; it now builds the new tensor first, also when the total size is unchanged. Slicing an FFT whose result type differs from its input copied the wrong number of bytes, an FFT nested in `argmax` referred to a temporary, the ternary select loaded an unaligned condition with aligned loads, and `loadPacketPartial` of the contraction mapper read a full packet. The `Tensor` constructors now check the product of their dimensions for overflow as `resize()` does. Concatenating two empty tensors, `convolve()` with a rank-0 kernel and `TensorIOFormat` with `DontAlignCols` no longer fail [#3245, #3256, #3258, #3272, #3273, #3274, #3276, #3303, #3314, #3315, #3320, #3324, #3349, #3405, #3406, #3408, !3636]
diff --git a/Eigen/src/Core/arch/AVX512/TrsmKernel.h b/Eigen/src/Core/arch/AVX512/TrsmKernel.h
index 7adcec9..6c6ab6f 100644
--- a/Eigen/src/Core/arch/AVX512/TrsmKernel.h
+++ b/Eigen/src/Core/arch/AVX512/TrsmKernel.h
@@ -982,8 +982,7 @@
     int64_t bK = numRHS - k > kB ? kB : numRHS - k;
     int64_t M_ = (M / EIGEN_AVX_MAX_NUM_ROW) * EIGEN_AVX_MAX_NUM_ROW, gemmOff = 0;
 
-    // bK rounded up to next multiple of L=EIGEN_AVX_MAX_NUM_ROW. When B_temp is used, we solve for bkL RHS
-    // instead of bK RHS in triSolveKernelLxK.
+    // Round up the row stride. Only the bK right-hand sides are initialized.
     int64_t bkL = ((bK + (EIGEN_AVX_MAX_NUM_ROW - 1)) / EIGEN_AVX_MAX_NUM_ROW) * EIGEN_AVX_MAX_NUM_ROW;
     const int64_t numScalarPerCache = 64 / sizeof(Scalar);
     // Leading dimension of B_temp, will be a multiple of the cache line size.
@@ -999,7 +998,7 @@
         copyBToRowMajor<Scalar, true, false>(B_arr + indB_i + k * LDB, LDB, bK, B_temp + offB_1, LDT);
         // Triangular solve with a small block of A and long horizontal blocks of B (or B_temp if B col-major)
         triSolveKernelLxK<Scalar, isARowMajor, isFWDSolve, isUnitDiag>(
-            &A_arr[idA<isARowMajor>(indA_i, indA_i, LDA)], B_temp + offB_2, EIGEN_AVX_MAX_NUM_ROW, bkL, LDA, LDT);
+            &A_arr[idA<isARowMajor>(indA_i, indA_i, LDA)], B_temp + offB_2, EIGEN_AVX_MAX_NUM_ROW, bK, LDA, LDT);
         // Copy values from B_temp back to B. B_temp will be reused in gemm call below.
         copyBToRowMajor<Scalar, false, false>(B_arr + indB_i + k * LDB, LDB, bK, B_temp + offB_1, LDT);
 
@@ -1092,7 +1091,7 @@
         int64_t offB_1 = isFWDSolve ? 0 : (bM - 1) * bkL;
         copyBToRowMajor<Scalar, true, true>(B_arr + indB_i + k * LDB, LDB, bK, B_temp, bkL, bM);
         triSolveKernelLxK<Scalar, isARowMajor, isFWDSolve, isUnitDiag>(&A_arr[idA<isARowMajor>(indA_i, indA_i, LDA)],
-                                                                       B_temp + offB_1, bM, bkL, LDA, bkL);
+                                                                       B_temp + offB_1, bM, bK, LDA, bkL);
         copyBToRowMajor<Scalar, false, true>(B_arr + indB_i + k * LDB, LDB, bK, B_temp, bkL, bM);
       } else {
         int64_t ind = isFWDSolve ? M_ : M - 1 - M_;
diff --git a/test/product_trsolve.cpp b/test/product_trsolve.cpp
index 31ba9a3..5b772a0 100644
--- a/test/product_trsolve.cpp
+++ b/test/product_trsolve.cpp
@@ -13,6 +13,9 @@
 #define EIGEN_RUNTIME_NO_MALLOC
 
 #include "main.h"
+#include "fp_control.h"
+
+#include <cfenv>
 
 // Coefficients of a Mode triangle that flag every read outside the stored triangle, including the diagonal of a
 // unit triangle.
@@ -529,6 +532,39 @@
   internal::manage_caching_sizes(SetAction, &l1, &l2, &l3, &l3_per_cpu);
 }
 
+// The AVX-512 kernel solves a column-major right-hand side in a row-major scratch panel whose width is rounded up.
+// The padding is uninitialized and must not be solved for: here it would overflow when scaled by the inverse of the
+// diagonal. The check relies on the allocator handing the freed block of huge values back to the kernel, so with
+// another allocator it can pass without reaching the padding; it cannot fail spuriously. The block's size is that of
+// the kernel's panel, sizeBTemp in triSolve().
+template <typename Scalar>
+void trsolve_ignores_scratch_padding() {
+#if defined(FE_OVERFLOW) && defined(FE_INVALID)
+  using MatrixX = Matrix<Scalar, Dynamic, Dynamic>;
+  for (int rows : {6, 9, 17}) {
+    for (int cols : {5, 13, 29}) {
+      MatrixX tri = MatrixX::Random(rows, rows) / Scalar(512 * rows);
+      tri.diagonal().setConstant(Scalar(1) / Scalar(256));
+      const MatrixX rhs = MatrixX::Random(rows, cols);
+      MatrixX x = rhs;
+      {
+        const Index psize = internal::packet_traits<Scalar>::size;
+        const Index size = ((numext::mini<Index>(15 * psize, cols) + psize - 1) / psize + 4) * psize * 64;
+        Scalar* block = static_cast<Scalar*>(internal::handmade_aligned_malloc(sizeof(Scalar) * size, 64));
+        std::fill(block, block + size, NumTraits<Scalar>::highest());
+        internal::handmade_aligned_free(block);
+      }
+      const int raised = fp_exceptions_raised_by(FE_OVERFLOW | FE_INVALID,
+                                                 [&]() { tri.template triangularView<Upper>().solveInPlace(x); });
+      if (raised >= 0) VERIFY_IS_EQUAL(raised, 0);
+      VERIFY_IS_APPROX(tri.template triangularView<Upper>() * x, rhs);
+    }
+  }
+#else
+  std::cout << "SKIP: scratch padding check: FE_OVERFLOW or FE_INVALID is unavailable.\n";
+#endif
+}
+
 EIGEN_DECLARE_TEST(product_trsolve) {
   for (int i = 0; i < g_repeat; i++) {
     // matrices
@@ -568,4 +604,6 @@
   CALL_SUBTEST_19(trsolve_panels_restoring_caches<std::complex<double> >(193, 1100, true));
   CALL_SUBTEST_20(trsolve_panels_restoring_caches<float>(391, 1100, false));
   CALL_SUBTEST_20(trsolve_panels_restoring_caches<double>(391, 1100, false));
+  CALL_SUBTEST_21(trsolve_ignores_scratch_padding<float>());
+  CALL_SUBTEST_21(trsolve_ignores_scratch_padding<double>());
 }