Reuse cuDSS analysis after numeric failure

Previously, CudaSparseCholeskyImpl recreated CudssContext and re-ran
CUDSS_PHASE_ANALYSIS after any failed factorization because cuDSS
0.3.0 kept the stale error in CUDSS_DATA_INFO across subsequent calls.

Now that Ceres requires cuDSS 1.0, reset CUDSS_DATA_INFO to zero with
cudssDataSet after a numerical failure and only re-run symbolic
analysis on initial setup or fatal errors.

Add a SparseCholeskyTest.FactorizeAfterNumericalFailure test that
factorizes a singular matrix and then factorizes and solves an SPD
matrix with the same sparsity pattern on the same SparseCholesky
instance.

Fixes https://github.com/ceres-solver/ceres-solver/issues/1079

Change-Id: I4924f6672f04fa7b22e2c827b3379a89d415b408
diff --git a/internal/ceres/cuda_sparse_cholesky.cc b/internal/ceres/cuda_sparse_cholesky.cc
index 75f1c6e..4cba51b 100644
--- a/internal/ceres/cuda_sparse_cholesky.cc
+++ b/internal/ceres/cuda_sparse_cholesky.cc
@@ -221,15 +221,12 @@
       return factorize_result_ = LinearSolverTerminationType::FATAL_ERROR;
     }
 
-    // If, after previous attempt to factorize, cudssDataGet(CUDSS_DATA_INFO)
-    // returned a numerical error, such error will be preserved by cuDSS 0.3.0
-    // and returned by cudssDataGet(CUDSS_DATA_INFO) even after correctly
-    // factorizeable matrix is provided. Such behaviour forces us to reset a
-    // cudssData_t object (managed by CudssContext) and to loose a result of
-    // anylyze stage, thus we have to perform analyze one more time.
-    // TODO: do not re-perform analyze in case of failed factorization numerics
+    // Re-run symbolic analysis only if it has not succeeded yet or if a
+    // previous factorization hit a fatal error. Numerical failures
+    // (non-positive minors) reset CUDSS_DATA_INFO below so cudssData_t and the
+    // symbolic analysis can be reused on the next attempt.
     if (analyze_result_ != LinearSolverTerminationType::SUCCESS ||
-        factorize_result_ != LinearSolverTerminationType::SUCCESS) {
+        factorize_result_ == LinearSolverTerminationType::FATAL_ERROR) {
       analyze_result_ = Analyze(lhs, message);
       if (analyze_result_ != LinearSolverTerminationType::SUCCESS) {
         return analyze_result_;
@@ -249,7 +246,7 @@
                      cudss_rhs_.Get()),
         "cudssExecute with CUDSS_PHASE_FACTORIZATION failed");
 
-    int cudss_data_info;
+    int cudss_data_info = 0;
     CUDSS_STATUS_OK_OR_RETURN_FATAL_ERROR(
         GetCudssDataInfo(cudss_data_info),
         "cudssDataGet with CUDSS_DATA_INFO failed");
@@ -261,6 +258,12 @@
     }
 
     if (cudss_data_info > 0) {
+      CUDSS_STATUS_OK_OR_RETURN_FATAL_ERROR(
+          ResetCudssDataInfo(), "cudssDataSet with CUDSS_DATA_INFO failed");
+      *message =
+          "cuDSS factorization failed: matrix is not positive definite "
+          "(non-positive minor at reordered index " +
+          std::to_string(cudss_data_info) + ").";
       return factorize_result_ = LinearSolverTerminationType::FAILURE;
     }
 
@@ -291,13 +294,15 @@
 
     ConvertAndCopyToHost(x_d_, x_h_.data(), solution);
 
-    int cudss_data_info;
+    int cudss_data_info = 0;
     CUDSS_STATUS_OK_OR_RETURN_FATAL_ERROR(
         GetCudssDataInfo(cudss_data_info),
         "cudssDataGet with CUDSS_DATA_INFO failed");
     const auto solve_status = static_cast<cudssStatus_t>(cudss_data_info);
 
     if (solve_status != CUDSS_STATUS_SUCCESS) {
+      CUDSS_STATUS_OK_OR_RETURN_FATAL_ERROR(
+          ResetCudssDataInfo(), "cudssDataSet with CUDSS_DATA_INFO failed");
       return LinearSolverTerminationType::FAILURE;
     }
 
@@ -321,6 +326,16 @@
     return CUDSS_STATUS_SUCCESS;
   }
 
+  cudssStatus_t ResetCudssDataInfo() {
+    CHECK_NE(cudss_context_.get(), nullptr);
+    int zero = 0;
+    return cudssDataSet(context_->cudss_handle_,
+                        cudss_context_->solver_data_,
+                        CUDSS_DATA_INFO,
+                        &zero,
+                        sizeof(zero));
+  }
+
   LinearSolverTerminationType Analyze(const CompressedRowSparseMatrix* lhs,
                                       std::string* message) {
     if (auto status = SetupCudssMatrices(lhs, message);
@@ -331,12 +346,6 @@
     lhs_rows_d_.CopyFromCpu(lhs->rows(), lhs->num_rows() + 1);
     lhs_cols_d_.CopyFromCpu(lhs->cols(), lhs->num_nonzeros());
 
-    // Analyze and factorization results are stored in cudssData_t (managed by
-    // CudssContext). Given that cuDSS 0.3.0 does not reset it's error state in
-    // case of failed numerics at factorization stage, we have to reset
-    // cudssData_t and to recompute an analyze stage while trying to factorize a
-    // rescaled matrix with the same structure.
-    // TODO: move creation of CudssContext to ctor of CudaSparseCholeskyImpl
     cudss_context_ = std::make_unique<CudssContext>(context_->cudss_handle_);
 
     CUDSS_STATUS_OK_OR_RETURN_FATAL_ERROR(
diff --git a/internal/ceres/sparse_cholesky_test.cc b/internal/ceres/sparse_cholesky_test.cc
index 429ed17..76cbb4b 100644
--- a/internal/ceres/sparse_cholesky_test.cc
+++ b/internal/ceres/sparse_cholesky_test.cc
@@ -30,6 +30,7 @@
 
 #include "ceres/sparse_cholesky.h"
 
+#include <algorithm>
 #include <limits>
 #include <memory>
 #include <random>
@@ -195,6 +196,72 @@
   }
 }
 
+TEST_P(SparseCholeskyTest, FactorizeAfterNumericalFailure) {
+  const Param param = GetParam();
+  const SparseLinearAlgebraLibraryType sparse_linear_algebra_library_type =
+      std::get<0>(param);
+  const bool use_single_precision = std::get<1>(param);
+  const OrderingType ordering_type = std::get<2>(param);
+  const bool use_block_structure = std::get<3>(param);
+
+  LinearSolver::Options sparse_cholesky_options;
+#ifndef CERES_NO_CUDSS
+  ContextImpl context;
+  sparse_cholesky_options.context = &context;
+  std::string error;
+  ASSERT_TRUE(context.InitCuda(&error)) << error;
+#endif  // CERES_NO_CUDSS
+
+  sparse_cholesky_options.sparse_linear_algebra_library_type =
+      sparse_linear_algebra_library_type;
+  sparse_cholesky_options.ordering_type = ordering_type;
+  sparse_cholesky_options.max_num_refinement_iterations = 0;
+  sparse_cholesky_options.use_mixed_precision_solves = use_single_precision;
+
+  auto sparse_cholesky = SparseCholesky::Create(sparse_cholesky_options);
+  const CompressedRowSparseMatrix::StorageType storage_type =
+      sparse_cholesky->StorageType();
+
+  std::mt19937 prng;
+  auto m = CreateRandomFullRankMatrix(5, 1, 5, 0.5, prng);
+  auto inner_product_computer = InnerProductComputer::Create(*m, storage_type);
+  inner_product_computer->Compute();
+  CompressedRowSparseMatrix* lhs = inner_product_computer->mutable_result();
+  if (!use_block_structure) {
+    lhs->mutable_row_blocks()->clear();
+    lhs->mutable_col_blocks()->clear();
+  }
+
+  const std::vector<double> spd_values(lhs->values(),
+                                       lhs->values() + lhs->num_nonzeros());
+  Vector rhs = Vector::Random(lhs->num_rows());
+  Vector expected(lhs->num_rows());
+  ASSERT_TRUE(SolveUsingDenseCholesky(*lhs, rhs, &expected));
+
+  // Zero out all entries so the matrix has the same sparsity pattern but is
+  // singular, forcing a numerical factorization failure across both LL^T and
+  // LDL^T backends.
+  std::fill_n(lhs->mutable_values(), lhs->num_nonzeros(), 0.0);
+  std::string message;
+  EXPECT_EQ(sparse_cholesky->Factorize(lhs, &message),
+            LinearSolverTerminationType::FAILURE);
+
+  // Restore the SPD values and verify that the same SparseCholesky instance
+  // can factorize and solve without error.
+  std::copy(spd_values.begin(), spd_values.end(), lhs->mutable_values());
+  Vector actual(lhs->num_rows());
+  ASSERT_EQ(
+      sparse_cholesky->FactorAndSolve(lhs, rhs.data(), actual.data(), &message),
+      LinearSolverTerminationType::SUCCESS)
+      << message;
+
+  const double kTolerance =
+      (use_single_precision ? std::numeric_limits<float>::epsilon()
+                            : std::numeric_limits<double>::epsilon()) *
+      20;
+  EXPECT_THAT(actual, RelativeNormNear(expected, kTolerance));
+}
+
 namespace {
 
 #ifndef CERES_NO_SUITESPARSE