diff --git a/.github/actions/build-wheel/action.yml b/.github/actions/build-wheel/action.yml index 2e15efd93f..c8f86420ab 100644 --- a/.github/actions/build-wheel/action.yml +++ b/.github/actions/build-wheel/action.yml @@ -89,6 +89,7 @@ runs: --exclude libcuda* \ --exclude libcudnn* \ --exclude libcufft* \ + --exclude libcusolver* \ --exclude libnccl* \ --exclude libnvrtc* fi diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml index 510086390a..ff9f1b3aff 100644 --- a/.github/actions/setup/action.yml +++ b/.github/actions/setup/action.yml @@ -170,9 +170,9 @@ runs: } PACKAGES: | { - "cuda-12.6": ["cudart_12.6", "nvcc_12.6", "cublas_12.6", "cublas_dev_12.6", "cufft_12.6", "cufft_dev_12.6", "nvrtc_12.6", "nvrtc_dev_12.6"], - "cuda-12.9": ["cudart_12.9", "nvcc_12.9", "cublas_12.9", "cublas_dev_12.9", "cufft_12.9", "cufft_dev_12.9", "nvrtc_12.9", "nvrtc_dev_12.9"], - "cuda-13.0": ["cudart_13.0", "nvcc_13.0", "cublas_13.0", "cublas_dev_13.0", "cufft_13.0", "cufft_dev_13.0", "nvrtc_13.0", "nvrtc_dev_13.0", "crt_13.0", "nvvm_13.0", "nvptxcompiler_13.0"], + "cuda-12.6": ["cudart_12.6", "nvcc_12.6", "cublas_12.6", "cublas_dev_12.6", "cufft_12.6", "cufft_dev_12.6", "cusolver_12.6", "cusolver_dev_12.6", "nvrtc_12.6", "nvrtc_dev_12.6"], + "cuda-12.9": ["cudart_12.9", "nvcc_12.9", "cublas_12.9", "cublas_dev_12.9", "cufft_12.9", "cufft_dev_12.9", "cusolver_12.9", "cusolver_dev_12.9", "nvrtc_12.9", "nvrtc_dev_12.9"], + "cuda-13.0": ["cudart_13.0", "nvcc_13.0", "cublas_13.0", "cublas_dev_13.0", "cufft_13.0", "cufft_dev_13.0", "cusolver_13.0", "cusolver_dev_13.0", "nvrtc_13.0", "nvrtc_dev_13.0", "crt_13.0", "nvvm_13.0", "nvptxcompiler_13.0"], } run: | $ErrorActionPreference = "Stop" diff --git a/ACKNOWLEDGMENTS.md b/ACKNOWLEDGMENTS.md index 7005396e71..a97754922e 100644 --- a/ACKNOWLEDGMENTS.md +++ b/ACKNOWLEDGMENTS.md @@ -22,6 +22,7 @@ MLX was developed with contributions from the following individuals: - Gökdeniz Gülmez: Added the `Muon (MomentUm Orthogonalized by Newton-schulz)` optimizer, and the `ReLU²` activation function. - katlun-lgtm: Added `reflect` and `symmetric` padding modes. - Erwin Zhang: Added `searchsorted`. Fixed the ring backend hanging when a peer disconnects. Improved JACCL error reporting. +- Oleksandr Zakharchuk: Added the cuSOLVER `cholesky` for the CUDA backend. diff --git a/mlx/backend/cuda/CMakeLists.txt b/mlx/backend/cuda/CMakeLists.txt index 9c8d3174c1..72b5868004 100644 --- a/mlx/backend/cuda/CMakeLists.txt +++ b/mlx/backend/cuda/CMakeLists.txt @@ -9,6 +9,7 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/arange.cu ${CMAKE_CURRENT_SOURCE_DIR}/arg_reduce.cu ${CMAKE_CURRENT_SOURCE_DIR}/binary_two.cu + ${CMAKE_CURRENT_SOURCE_DIR}/cholesky.cu ${CMAKE_CURRENT_SOURCE_DIR}/compiled.cpp ${CMAKE_CURRENT_SOURCE_DIR}/copy.cu ${CMAKE_CURRENT_SOURCE_DIR}/copy/copy_contiguous.cu @@ -21,6 +22,7 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/cublas_utils.cpp ${CMAKE_CURRENT_SOURCE_DIR}/cross_entropy.cu ${CMAKE_CURRENT_SOURCE_DIR}/cudnn_utils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/cusolver_utils.cpp ${CMAKE_CURRENT_SOURCE_DIR}/device_info.cpp ${CMAKE_CURRENT_SOURCE_DIR}/custom_kernel.cpp ${CMAKE_CURRENT_SOURCE_DIR}/device.cpp @@ -241,6 +243,7 @@ else() "$ORIGIN/../../nvidia/cuda_nvrtc/lib" "$ORIGIN/../../nvidia/cudnn/lib" "$ORIGIN/../../nvidia/cufft/lib" + "$ORIGIN/../../nvidia/cusolver/lib" "$ORIGIN/../../nvidia/nccl/lib") endif() endif() @@ -286,6 +289,9 @@ target_link_libraries(mlx PRIVATE CUDA::cublasLt) # Use cuFFT. target_link_libraries(mlx PRIVATE CUDA::cufft) +# Use cuSOLVER. +target_link_libraries(mlx PRIVATE CUDA::cusolver) + # Use NVRTC and driver APIs. target_link_libraries(mlx PRIVATE CUDA::nvrtc CUDA::cuda_driver) diff --git a/mlx/backend/cuda/cholesky.cu b/mlx/backend/cuda/cholesky.cu new file mode 100644 index 0000000000..47c993fb0e --- /dev/null +++ b/mlx/backend/cuda/cholesky.cu @@ -0,0 +1,141 @@ +// Copyright © 2026 Apple Inc. + +#include "mlx/backend/cuda/cusolver_utils.h" +#include "mlx/backend/cuda/device.h" +#include "mlx/backend/cuda/kernel_utils.cuh" +#include "mlx/backend/cuda/utils.h" +#include "mlx/backend/gpu/copy.h" +#include "mlx/primitives.h" + +#include +#include + +namespace mlx::core { + +namespace cu { + +namespace cg = cooperative_groups; + +// potrf writes only one triangle; zero the other one to match the CPU op. +template +__global__ void zero_triangle(T* out, IdxT size, int32_t n, bool zero_below) { + IdxT index = cg::this_grid().thread_rank(); + if (index >= size) { + return; + } + int32_t row = (index / n) % n; + int32_t col = index % n; + if (zero_below ? (col < row) : (col > row)) { + out[index] = T(0); + } +} + +// potrfBatched wants a device array of per matrix pointers. +__global__ void +fill_matrix_pointers(void** ptrs, float* base, int64_t n2, int64_t batch) { + int64_t i = cg::this_grid().thread_rank(); + if (i < batch) { + ptrs[i] = base + i * n2; + } +} + +} // namespace cu + +void Cholesky::eval_gpu(const std::vector& inputs, array& out) { + nvtx3::scoped_range r("Cholesky::eval_gpu"); + auto& s = stream(); + auto& a = inputs[0]; + + // Copy the input to the output; the factorization runs in place. + copy_gpu( + a, + out, + a.flags().row_contiguous ? CopyType::Vector : CopyType::General, + s); + + if (a.size() == 0) { + return; + } + + auto& encoder = cu::get_command_encoder(s); + + auto handle = get_cusolver_handle(encoder.device()); + CHECK_CUSOLVER_ERROR(cusolverDnSetStream(handle, encoder.stream())); + + // cuSOLVER is column major. The input is symmetric and a column major + // lower triangle is a row major upper one, so pass the opposite of + // upper_, same as the CPU op. + cublasFillMode_t uplo = + upper_ ? CUBLAS_FILL_MODE_LOWER : CUBLAS_FILL_MODE_UPPER; + + // Only float32 reaches eval_gpu: float64 is rejected on GPU streams at + // array construction. + auto type = CUDA_R_32F; + auto* out_ptr = gpu_ptr(out); + + int64_t n = a.shape(-1); + int64_t batch = a.size() / (n * n); + + // Matching the CPU op, info is never read back: a non positive definite + // input gives an undefined factor rather than an error. + auto* info = static_cast( + allocate_workspace(encoder, batch * sizeof(int))); + + // TODO: For some consumer cards serialized loop might be faster. + if (batch > 1) { + array ptrs( + cu::malloc_async(batch * sizeof(void*), encoder), + {static_cast(batch)}, + uint64); + encoder.add_temporary(ptrs); + encoder.set_output_array(ptrs); + encoder.add_kernel_node( + &cu::fill_matrix_pointers, + cuda::ceil_div(batch, 256), + 256, + gpu_ptr(ptrs), + out_ptr, + n * n, + batch); + + encoder.set_input_array(ptrs); + encoder.set_output_array(out); + auto capture = encoder.capture_context(); + CHECK_CUSOLVER_ERROR(cusolverDnSpotrfBatched( + handle, + uplo, + n, + gpu_ptr(ptrs), + /* lda */ n, + info, + batch)); + } else { + int lwork = 0; + CHECK_CUSOLVER_ERROR(cusolverDnSpotrf_bufferSize( + handle, uplo, n, out_ptr, n, &lwork)); + auto* workspace = static_cast( + allocate_workspace(encoder, lwork * sizeof(float))); + + encoder.set_input_array(out); + encoder.set_output_array(out); + auto capture = encoder.capture_context(); + CHECK_CUSOLVER_ERROR(cusolverDnSpotrf( + handle, uplo, n, out_ptr, n, workspace, lwork, info)); + } + + encoder.set_output_array(out); + dispatch_bool(out.size() > INT32_MAX, [&](auto large) { + using IdxT = std::conditional_t; + auto [num_blocks, block_dims] = get_launch_args(out, large()); + encoder.add_kernel_node( + cu::zero_triangle, + num_blocks, + block_dims, + out_ptr, + static_cast(out.size()), + static_cast(n), + upper_); + }); +} + +} // namespace mlx::core diff --git a/mlx/backend/cuda/cusolver_utils.cpp b/mlx/backend/cuda/cusolver_utils.cpp new file mode 100644 index 0000000000..b4366d8d74 --- /dev/null +++ b/mlx/backend/cuda/cusolver_utils.cpp @@ -0,0 +1,47 @@ +// Copyright © 2026 Apple Inc. +#include "mlx/backend/cuda/cusolver_utils.h" +#include "mlx/backend/gpu/device_info.h" + +#include + +namespace mlx::core { + +namespace { + +auto& cusolver_handles_cache() { + struct CusolverHandle { + ~CusolverHandle() { + if (handle) { + // Not checked: runs at thread exit where a throw would terminate. + cusolverDnDestroy(handle); + } + } + cusolverDnHandle_t handle{nullptr}; + }; + static thread_local std::vector cache(gpu::device_count()); + return cache; +} + +} // namespace + +cusolverDnHandle_t get_cusolver_handle(cu::Device& device) { + auto& storage = cusolver_handles_cache().at(device.cuda_device()); + if (!storage.handle) { + device.make_current(); + CHECK_CUSOLVER_ERROR(cusolverDnCreate(&storage.handle)); + } + return storage.handle; +} + +void init_cusolver_handles_cache() { + cusolver_handles_cache(); +} + +void check_cusolver_error(const char* name, cusolverStatus_t err) { + if (err != CUSOLVER_STATUS_SUCCESS) { + throw std::runtime_error( + fmt::format("{} failed with code: {}.", name, static_cast(err))); + } +} + +} // namespace mlx::core diff --git a/mlx/backend/cuda/cusolver_utils.h b/mlx/backend/cuda/cusolver_utils.h new file mode 100644 index 0000000000..ad457a9824 --- /dev/null +++ b/mlx/backend/cuda/cusolver_utils.h @@ -0,0 +1,18 @@ +// Copyright © 2026 Apple Inc. +#pragma once + +#include "mlx/backend/cuda/device.h" + +#include + +namespace mlx::core { + +void check_cusolver_error(const char* name, cusolverStatus_t err); + +#define CHECK_CUSOLVER_ERROR(cmd) check_cusolver_error(#cmd, (cmd)) + +void init_cusolver_handles_cache(); + +cusolverDnHandle_t get_cusolver_handle(cu::Device& device); + +} // namespace mlx::core diff --git a/mlx/backend/cuda/delayload.cpp b/mlx/backend/cuda/delayload.cpp index 7092d4497c..44f6d163c6 100644 --- a/mlx/backend/cuda/delayload.cpp +++ b/mlx/backend/cuda/delayload.cpp @@ -61,6 +61,22 @@ fs::path load_cudnn() { return cudnn_dir; } +fs::path load_cusolver() { + fs::path cusolver_dir; + if (const char* dir = cuda_bin_dir()) { + cusolver_dir = dir; + } else { + cusolver_dir = relative_to_current_binary("../nvidia/cusolver/bin"); + ::AddDllDirectory(cublas_dir().c_str()); + ::AddDllDirectory( + relative_to_current_binary("../nvidia/cusparse/bin").c_str()); + ::AddDllDirectory( + relative_to_current_binary("../nvidia/nvjitlink/bin").c_str()); + } + ::AddDllDirectory(cusolver_dir.c_str()); + return cusolver_dir; +} + // Called by system when failed to locate a lazy-loaded DLL. FARPROC WINAPI delayload_helper(unsigned dliNotify, PDelayLoadInfo pdli) { HMODULE mod = NULL; @@ -71,6 +87,9 @@ FARPROC WINAPI delayload_helper(unsigned dliNotify, PDelayLoadInfo pdli) { mod = ::LoadLibraryW((cudnn_dir / dll).c_str()); } else if (dll.starts_with("cublas")) { mod = ::LoadLibraryW((cublas_dir() / dll).c_str()); + } else if (dll.starts_with("cusolver")) { + static auto cusolver_dir = load_cusolver(); + mod = ::LoadLibraryW((cusolver_dir / dll).c_str()); } else if (dll.starts_with("nvrtc")) { static auto nvrtc_dir = load_nvrtc(); mod = ::LoadLibraryW((nvrtc_dir / dll).c_str()); diff --git a/mlx/backend/cuda/eval.cpp b/mlx/backend/cuda/eval.cpp index f8a71d71bc..2862f38223 100644 --- a/mlx/backend/cuda/eval.cpp +++ b/mlx/backend/cuda/eval.cpp @@ -4,6 +4,7 @@ #include "mlx/backend/cuda/allocator.h" #include "mlx/backend/cuda/cublas_utils.h" #include "mlx/backend/cuda/cudnn_utils.h" +#include "mlx/backend/cuda/cusolver_utils.h" #include "mlx/backend/cuda/event.h" #include "mlx/primitives.h" #include "mlx/scheduler.h" @@ -20,6 +21,7 @@ void init() { mlx::core::cu::CudaEvent::init_pool(); init_cublas_handles_cache(); init_cudnn_handles_cache(); + init_cusolver_handles_cache(); init_cudnn_conv_cache(); init_cudnn_sdpa_cache(); } diff --git a/mlx/backend/cuda/primitives.cpp b/mlx/backend/cuda/primitives.cpp index 94f260767f..f23da9bf21 100644 --- a/mlx/backend/cuda/primitives.cpp +++ b/mlx/backend/cuda/primitives.cpp @@ -28,7 +28,6 @@ NO_GPU_MULTI(LUF) NO_GPU_MULTI(QRF) NO_GPU_MULTI(SVD) NO_GPU(Inverse) -NO_GPU(Cholesky) NO_GPU_MULTI(Eig) NO_GPU_MULTI(Eigh) diff --git a/mlx/linalg.cpp b/mlx/linalg.cpp index 0d06b56469..c4213c93bc 100644 --- a/mlx/linalg.cpp +++ b/mlx/linalg.cpp @@ -4,6 +4,7 @@ #include #include +#include "mlx/backend/cuda/cuda.h" #include "mlx/linalg.h" #include "mlx/primitives.h" #include "mlx/utils.h" @@ -18,6 +19,18 @@ void check_cpu_stream(const StreamOrDevice& s, const std::string& prefix) { "Explicitly pass a CPU stream to run it."); } } + +// For ops that have a CUDA implementation but no Metal one yet. +void check_cpu_or_cuda_stream( + const StreamOrDevice& s, + const std::string& prefix) { + if (to_stream(s).device == Device::gpu && !cu::is_available()) { + throw std::invalid_argument( + prefix + + " This op is not yet supported on the GPU. " + "Explicitly pass a CPU stream to run it."); + } +} void check_float(Dtype dtype, const std::string& prefix) { if (dtype != float32 && dtype != float64) { std::ostringstream msg; @@ -336,7 +349,7 @@ array cholesky( const array& a, bool upper /* = false */, StreamOrDevice s /* = {} */) { - check_cpu_stream(s, "[linalg::cholesky]"); + check_cpu_or_cuda_stream(s, "[linalg::cholesky]"); check_float(a.dtype(), "[linalg::cholesky]"); if (a.ndim() < 2) { std::ostringstream msg; diff --git a/python/tests/test_linalg.py b/python/tests/test_linalg.py index 52e02e4d9a..2da3781b4e 100644 --- a/python/tests/test_linalg.py +++ b/python/tests/test_linalg.py @@ -306,6 +306,35 @@ def test_cholesky(self): for M, L in zip(AB, Ls): self.assertTrue(mx.allclose(L @ L.T, M, rtol=1e-5, atol=1e-7)) + if mx.cuda.is_available(): + # The matrix above is singular, so its factor is undefined past the + # rank boundary and the GPU need not match the CPU there. Use + # positive definite inputs, sized to hit both cuSOLVER paths. + mx.random.seed(7) + for batch, n in [((), 3), ((2,), 2048), ((16,), 8)]: + x = mx.random.normal(batch + (n, n)) + A = x @ mx.swapaxes(x, -1, -2) + n * mx.eye(n) + for upper in [False, True]: + G = mx.linalg.cholesky(A, upper=upper, stream=mx.gpu) + C = mx.linalg.cholesky(A, upper=upper, stream=mx.cpu) + self.assertTrue(mx.allclose(G, C, rtol=1e-4, atol=1e-5)) + tri = mx.tril(G, k=-1) if upper else mx.triu(G, k=1) + self.assertTrue(mx.all(tri == 0)) + + # Empty and non contiguous inputs + self.assertEqual( + mx.linalg.cholesky(mx.zeros((0, 0)), stream=mx.gpu).shape, (0, 0) + ) + At = mx.swapaxes(A, -1, -2) + self.assertTrue( + mx.allclose( + mx.linalg.cholesky(At, stream=mx.gpu), + mx.linalg.cholesky(At, stream=mx.cpu), + rtol=1e-4, + atol=1e-5, + ) + ) + def test_pseudo_inverse(self): A = mx.array([[1, 2, 3], [6, -5, 4], [-9, 8, 7]], dtype=mx.float32) A_plus = mx.linalg.pinv(A, stream=mx.cpu) diff --git a/setup.py b/setup.py index 52cc4f7492..ad258d8af5 100644 --- a/setup.py +++ b/setup.py @@ -339,6 +339,7 @@ def is_backend_file(file): "nvidia-cublas-cu12==12.9.*", "nvidia-cufft-cu12==11.4.*", "nvidia-cuda-nvrtc-cu12==12.9.*", + "nvidia-cusolver-cu12==11.7.*", ] elif toolkit == 13: install_requires += [ @@ -346,6 +347,7 @@ def is_backend_file(file): "nvidia-cufft==12.*", "nvidia-cuda-nvrtc==13.*", "nvidia-cuda-runtime==13.*", + "nvidia-cusolver==12.*", ] else: raise ValueError(f"Unknown toolkit {toolkit}")