Repository navigation
Fix GPU MatrixSolve singular matrix detection for all shapes - #112658
copybara-service[bot] merged 3 commits into
Conversation
|
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. |
23a0931 to
598b3d9
Compare
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
598b3d9 to
6d376ad
Compare
|
@rohan100jain @keerthanakadiri This fixes GPU |
|
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. |
|
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. |
dmiltr3
left a comment
There was a problem hiding this comment.
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:
- Add GPU Unit Tests: The existing
testNotInvertibletest 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 intensorflow/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))|
@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:
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. |
dmiltr3
left a comment
There was a problem hiding this comment.
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:
- With
n \>= 46341,n * noverflows the maximum 32-bit signed integer value, resulting in a negative value formatrix_sizeand subsequentlybase. - With
n = 33000andbatch_size = 3(requiring ~13 GB of GPU memory),matrix_size = 1,089,000,000. During the iteration wherebatch = 2,baseevaluates to2,178,000,000, overflowing into a negative number. - If a user provides a batched tensor with dimensions
num_matrices = 220000andn = 100, the calculationmatrix_size * batchfor the later batches will evaluate to10000 * 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
// ...|
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. |
dmiltr3
left a comment
There was a problem hiding this comment.
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.
9ad83ed
into
tensorflow:master
Summary
tf.linalg.solvebehaves inconsistently on GPU for singular matrices depending on shape #94657:tf.linalg.solveon GPU silently returns incorrect results for certain singular matrices (e.g., 3x3) while correctly raisingInvalidArgumentErrorfor others (e.g., 2x2).getrfBatcheddoes not always report singularity via its info output for all matrix sizes.CheckLUDiagonalForZerosFunctor) that explicitly checks the diagonal of the LU factorization for exact zero pivots after the factorization step, ensuring the existinginfo_checkercallback consistently detects singular matrices regardless of matrix shape.Test plan
testNotInvertibleinmatrix_solve_op_test.pyshould continue to pass on CPUInvalidArgumentError: Input matrix is not invertible.🤖 Generated with Claude Code
Testing