Skip to content

Fix GPU MatrixSolve singular matrix detection for all shapes - #112658

Merged
copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
ayushozha:fix/gpu-matrix-solve-singular-detection
Aug 11, 2026
Merged

copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
ayushozha:fix/gpu-matrix-solve-singular-detection

Conversation

@ayushozha

@ayushozha ayushozha commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Fixes tf.linalg.solve behaves inconsistently on GPU for singular matrices depending on shape #94657: tf.linalg.solve on GPU silently returns incorrect results for certain singular matrices (e.g., 3x3) while correctly raising InvalidArgumentError for others (e.g., 2x2).
  • Root cause: cuBLAS getrfBatched does not always report singularity via its info output for all matrix sizes.
  • Fix: Added a GPU kernel (CheckLUDiagonalForZerosFunctor) that explicitly checks the diagonal of the LU factorization for exact zero pivots after the factorization step, ensuring the existing info_checker callback consistently detects singular matrices regardless of matrix shape.

Test plan

  • Existing testNotInvertible in matrix_solve_op_test.py should continue to pass on CPU
  • On GPU, singular matrices of all sizes (2x2, 3x3, etc.) should now consistently raise InvalidArgumentError: Input matrix is not invertible.
  • Non-singular matrices should be unaffected (the kernel only flags exact zero pivots)

🤖 Generated with Claude Code

Testing

  • PASS: git diff --check HEAD^..HEAD
  • NOT RUN locally: TensorFlow Bazel unit/build targets (Bazel/buildifier and a built TensorFlow runtime are unavailable in this checkout environment).

@google-ml-butler google-ml-butler Bot added the size:M CL Change Size: Medium label Mar 18, 2026
@google-cla

google-cla Bot commented Mar 18, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@ayushozha
ayushozha force-pushed the fix/gpu-matrix-solve-singular-detection branch from 23a0931 to 598b3d9 Compare March 18, 2026 09:47
cuBLAS getrfBatched may not always report singularity via its info
output for all matrix sizes. Add an explicit GPU kernel that checks
the diagonal of the LU factorization for exact zero pivots after
the factorization step, ensuring consistent InvalidArgumentError
behavior between CPU and GPU backends.

Fixes tensorflow#94657
@ayushozha
ayushozha force-pushed the fix/gpu-matrix-solve-singular-detection branch from 598b3d9 to 6d376ad Compare March 18, 2026 22:31
@keerthanakadiri keerthanakadiri added the comp:core issues related to core part of tensorflow label Mar 20, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Mar 20, 2026
@keerthanakadiri keerthanakadiri added the awaiting review Pull request awaiting review label Mar 20, 2026
@ayushozha

Copy link
Copy Markdown
Contributor Author

@rohan100jain @keerthanakadiri This fixes GPU MatrixSolve silently returning wrong results for singular matrices instead of raising an error. The CPU path correctly detects singularity but the GPU path skips the check for batched inputs. This is a silent correctness bug — users get garbage output with no warning.

@ayushozha

Copy link
Copy Markdown
Contributor Author

Friendly ping @rohan100jain @keerthanakadiri — this fixes GPU MatrixSolve silently returning incorrect results for singular matrices instead of raising an error (the CPU path handles this correctly). This is a correctness issue that can cause silent data corruption. Would appreciate a review when you get a chance. Happy to address any feedback.

@keerthanakadiri keerthanakadiri added the stat:awaiting response Status - Awaiting response from author label Jun 5, 2026
@github-actions

Copy link
Copy Markdown

This PR is stale because it has been open for 14 days with no activity. It will be closed if no further activity occurs. Thank you.

@github-actions github-actions Bot added the stale This label marks the issue/pr stale - to be closed automatically if no activity label Jun 20, 2026
@dmiltr3
dmiltr3 self-requested a review June 28, 2026 02:16

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @ayushozha,

Thank you for this contribution to fix the GPU MatrixSolve singular matrix detection! This is a great fix for a correctness issue where singular matrices were producing silent errors / garbage output for certain shapes.

Before we can merge this pull request, please address the following:

  1. Add GPU Unit Tests: The existing testNotInvertible test runs on CPU by default. We want to ensure this GPU fix is fully tested and verified against regressions. Please add a GPU-enabled Python unit test in tensorflow/python/kernel_tests/linalg/matrix_solve_op_test.py. Here is a suggested test implementation you can add to the test class:
    @test_util.run_in_graph_and_eager_modes(use_gpu=True)
    def testNotInvertibleGpu(self):
      # Singular 2x2 matrix
      with self.assertRaisesOpError("Input matrix is not invertible."):
        matrix = constant_op.constant([[1., 2.], [2., 4.]])
        self.evaluate(linalg_ops.matrix_solve(matrix, matrix))
      # Singular 3x3 matrix
      with self.assertRaisesOpError("Input matrix is not invertible."):
        matrix = constant_op.constant([[1., 0., -1.], [-1., 1., 0.],
                                       [0., -1., 1.]])
        self.evaluate(linalg_ops.matrix_solve(matrix, matrix))

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Jun 28, 2026
@github-actions github-actions Bot removed stale This label marks the issue/pr stale - to be closed automatically if no activity stat:awaiting response Status - Awaiting response from author labels Jun 28, 2026
@keerthanakadiri keerthanakadiri added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review labels Jun 30, 2026
@ayushozha

Copy link
Copy Markdown
Contributor Author

@dmiltr3 I pushed the requested GPU regression coverage in commit 466c7e2. The new test adds singular 2x2, singular 3x3, and batched singular 3x3 cases under @test_util.run_in_graph_and_eager_modes(use_gpu=True)\ in \ ensorflow/python/kernel_tests/linalg/matrix_solve_op_test.py.

Validation:

  • \python -m py_compile tensorflow\python\kernel_tests\linalg\matrix_solve_op_test.py\
  • \git diff --check\

I could not run the Bazel target locally because \�azel\ is not installed on this machine's PATH, but the focused TensorFlow/Bazel test to run in CI is //tensorflow/python/kernel_tests/linalg:matrix_solve_op_test\ filtered to \MatrixSolveOpTest.testNotInvertibleGpu.

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Jul 5, 2026
@nithyak0204
nithyak0204 requested a review from dmiltr3 July 10, 2026 16:53
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Jul 10, 2026
@google-ml-butler google-ml-butler Bot added the kokoro:force-run Tests on submitted change label Jul 13, 2026
@google-ml-butler google-ml-butler Bot added the ready to pull PR ready for merge process label Jul 13, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Jul 13, 2026
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Jul 13, 2026
@dmiltr3
dmiltr3 self-requested a review July 13, 2026 18:09

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please fix the following problem:

Integer Overflow in CheckLUDiagonalForZerosKernel Leading to GPU Out-of-Bounds Read
In CheckLUDiagonalForZerosKernel, the index computations const int matrix_size = n * n; and int base = matrix_size * batch; use 32-bit signed integers. Because n and batch are derived from user-controlled tensor dimensions, these calculations can easily exceed the 32-bit signed integer maximum (2,147,483,647). For example:

  1. With n \>= 46341, n * n overflows the maximum 32-bit signed integer value, resulting in a negative value for matrix_size and subsequently base.
  2. With n = 33000 and batch_size = 3 (requiring ~13 GB of GPU memory), matrix_size = 1,089,000,000. During the iteration where batch = 2, base evaluates to 2,178,000,000, overflowing into a negative number.
  3. If a user provides a batched tensor with dimensions num_matrices = 220000 and n = 100, the calculation matrix_size * batch for the later batches will evaluate to 10000 * 220000 = 2,200,000,000.

When base is negative, the subsequent read lu_factor[base + i * stride] performs an out-of-bounds memory access on the GPU. Additionally, i * stride can also overflow if n is large enough.

Impact: An attacker controlling the tensor shapes supplied to MatrixSolve or BatchMatrixSolve can trigger this integer overflow, resulting in a GPU out-of-bounds read. This can cause a GPU page fault, crashing the system and causing a Denial of Service (DoS), or potentially expose data from adjacent GPU memory regions.

Mitigation: Change the types used for size and offset calculations within the kernel to int64_t to prevent overflow. Ensure proper casting is applied before multiplication. Change the types of n, matrix_size, stride, base, and i to int64_t in the kernel definition and signature. Furthermore, ensure variables such as nthreads passed into the kernel from the host are properly handled as int64_t.

Example fix for the kernel:

template <typename Scalar>
__global__ void CheckLUDiagonalForZerosKernel(
    int64_t nthreads, int64_t n, const Scalar* __restrict__ lu_factor,
    int* __restrict__ info) {
  typedef typename Eigen::NumTraits<Scalar>::Real RealScalar;
  const int64_t matrix_size = n * n;
  const int64_t stride = n + 1;
  GPU_1D_KERNEL_LOOP(batch_idx, nthreads) {
    int64_t batch = batch_idx;
    if (info[batch] == 0) {
      int64_t base = matrix_size * batch;
      for (int64_t i = 0; i < n; ++i) {
        if (Eigen::numext::abs(lu_factor[base + i * stride]) == RealScalar(0)) {
          info[batch] = i + 1;
          break;
        }
      }
    }
  }
}

Evidence: In matrix_solve_op_gpu.cu.cc:

template <typename Scalar>
__global__ void CheckLUDiagonalForZerosKernel(
    int nthreads, int n, const Scalar* __restrict__ lu_factor,
    int* __restrict__ info) {
  // ...
  const int matrix_size = n * n; // OVERFLOW
  const int stride = n + 1;
  GPU_1D_KERNEL_LOOP(batch, nthreads) {
    if (info[batch] == 0) {
      int base = matrix_size * batch; // OVERFLOW
      for (int i = 0; i < n; ++i) {
        if (Eigen::numext::abs(lu_factor[base + i * stride]) == RealScalar(0)) { // OOB READ
  // ...

@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Reviewer Requested Changes in PR Queue Jul 13, 2026
@nithyak0204 nithyak0204 added stat:awaiting response Status - Awaiting response from author and removed awaiting review Pull request awaiting review ready to pull PR ready for merge process labels Jul 14, 2026
@ayushozha

Copy link
Copy Markdown
Contributor Author

Addressed the latest review in commit a28fab1. Promoted GPU LU diagonal kernel sizes and offsets to int64_t to prevent overflow and out-of-bounds reads. Validation: git diff --check passed; full Bazel targets were not run locally because the required toolchain/runtime is unavailable.

@google-ml-butler google-ml-butler Bot removed the stat:awaiting response Status - Awaiting response from author label Jul 17, 2026
@nithyak0204 nithyak0204 added the awaiting review Pull request awaiting review label Jul 20, 2026
@nithyak0204
nithyak0204 requested a review from dmiltr3 July 22, 2026 06:48

@dmiltr3 dmiltr3 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The promotion of kernel signature parameters (nthreads, n) and internal offset calculations (matrix_size, stride, base, i) to int64_t in CheckLUDiagonalForZerosKernel cleanly resolves the potential 32-bit integer overflow and GPU out-of-bounds memory access. The additions to testNotInvertibleGpu cover singular matrix detection on GPU. All required review feedback has been addressed and verified. Ready for approval.

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Aug 6, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Aug 6, 2026
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Aug 6, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Aug 7, 2026
@copybara-service
copybara-service Bot merged commit 9ad83ed into tensorflow:master Aug 11, 2026
16 of 17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:core issues related to core part of tensorflow ready to pull PR ready for merge process size:M CL Change Size: Medium

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

tf.linalg.solve behaves inconsistently on GPU for singular matrices depending on shape

6 participants