Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/actions/build-wheel/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ runs:
--exclude libcuda* \
--exclude libcudnn* \
--exclude libcufft* \
--exclude libcusolver* \
--exclude libcusparse* \
--exclude libnccl* \
--exclude libnvrtc*
fi
Expand Down
100 changes: 100 additions & 0 deletions benchmarks/python/cholesky_bench.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Copyright © 2025 Apple Inc.

import argparse

from time_utils import measure_runtime

# Imports are deferred so this script can run in an environment that has only
# one of the two frameworks installed. That matters in practice: MLX depends on
# nvidia-nccl-cu12 while recent torch wheels want a newer nccl, so the two can
# be awkward to co-install. `--only mlx` / `--only torch` lets each half be
# timed with its own interpreter and the numbers compared afterwards.

SHAPES = [
# Single matrix, small to large.
(32, 32),
(128, 128),
(512, 512),
(2048, 2048),
(4096, 4096),
# Batched.
(64, 32, 32),
(256, 32, 32),
(64, 128, 128),
(16, 512, 512),
]


def bench_mlx(shape, upper):
import mlx.core as mx

n = shape[-1]
a = mx.random.uniform(shape=shape)
# Scaled to O(1) entries and diagonally dominant, so the factorization is
# well conditioned and the timing is not dominated by denormals.
A = a @ mx.swapaxes(a, -1, -2) / n + mx.eye(n)
mx.eval(A)

def run(A):
mx.eval(mx.linalg.cholesky(A, upper=upper))

return measure_runtime(run, A=A)


def bench_torch(shape, upper, device):
import torch

n = shape[-1]
a = torch.rand(shape, dtype=torch.float32, device=device)
A = a @ a.transpose(-1, -2) / n + torch.eye(n, device=device)

def run(A):
torch.linalg.cholesky(A, upper=upper)
if device.type == "mps":
torch.mps.synchronize()
elif device.type == "cuda":
torch.cuda.synchronize()

return measure_runtime(run, A=A)


if __name__ == "__main__":
parser = argparse.ArgumentParser("Cholesky benchmarks.")
parser.add_argument("--cpu", action="store_true", help="Use the CPU.")
parser.add_argument(
"--only",
choices=["mlx", "torch", "both"],
default="both",
help="Benchmark only one framework (useful when they cannot co-install).",
)
args = parser.parse_args()

device = None
if args.only in ("mlx", "both"):
import mlx.core as mx

mx.set_default_device(mx.cpu if args.cpu else mx.gpu)

if args.only in ("torch", "both"):
import torch

if args.cpu:
device = torch.device("cpu")
elif torch.cuda.is_available():
device = torch.device("cuda")
else:
device = torch.device("mps")

for shape in SHAPES:
for upper in (False, True):
print("=" * 20)
print(f"Shape: {shape}, upper={upper}")
mlx_ms = torch_ms = None
if args.only in ("mlx", "both"):
mlx_ms = bench_mlx(shape, upper)
print(f"MLX: {mlx_ms:.3f}ms")
if args.only in ("torch", "both"):
torch_ms = bench_torch(shape, upper, device)
print(f"PyTorch: {torch_ms:.3f}ms")
if mlx_ms is not None and torch_ms is not None:
print(f"MLX / PyTorch: {mlx_ms / torch_ms:.2f}x")
6 changes: 6 additions & 0 deletions mlx/backend/cuda/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -20,6 +21,7 @@ target_sources(
${CMAKE_CURRENT_SOURCE_DIR}/conv/gemm_grouped_conv.cu
${CMAKE_CURRENT_SOURCE_DIR}/cublas_utils.cpp
${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
Expand Down Expand Up @@ -217,6 +219,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()
Expand Down Expand Up @@ -262,6 +265,9 @@ target_link_libraries(mlx PRIVATE CUDA::cublasLt)
# Use cuFFT.
target_link_libraries(mlx PRIVATE CUDA::cufft)

# Use cuSOLVER for dense linear algebra.
target_link_libraries(mlx PRIVATE CUDA::cusolver)

# Use NVRTC and driver APIs.
target_link_libraries(mlx PRIVATE CUDA::nvrtc CUDA::cuda_driver)

Expand Down
175 changes: 175 additions & 0 deletions mlx/backend/cuda/cholesky.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
// Copyright © 2025 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/dtype_utils.h"
#include "mlx/primitives.h"

#include <cooperative_groups.h>
#include <nvtx3/nvtx3.hpp>
#include <cuda/cmath>

#include <cassert>

namespace mlx::core {

namespace cg = cooperative_groups;

namespace cu {

template <typename T>
__global__ void set_batch_pointers(T** ptrs, T* base, int64_t n2, int batch) {
auto i = cg::this_grid().thread_rank();
if (i < batch) {
ptrs[i] = base + i * n2;
}
}

// potrf only writes the requested triangle, so zero the other one.
template <typename T>
__global__ void zero_triangle(T* matrices, int n, bool upper, int64_t total) {
auto i = cg::this_grid().thread_rank();
if (i >= total) {
return;
}
int64_t offset = i % (static_cast<int64_t>(n) * n);
int row = offset / n;
int col = offset % n;
if (upper ? (col < row) : (col > row)) {
matrices[i] = T(0);
}
}

} // namespace cu

namespace {

template <typename T>
struct Potrf;

template <>
struct Potrf<float> {
static constexpr auto buffer_size = cusolverDnSpotrf_bufferSize;
static constexpr auto factor = cusolverDnSpotrf;
static constexpr auto factor_batched = cusolverDnSpotrfBatched;
};

// Unreachable while array.cpp rejects float64 for any GPU primitive.
template <>
struct Potrf<double> {
static constexpr auto buffer_size = cusolverDnDpotrf_bufferSize;
static constexpr auto factor = cusolverDnDpotrf;
static constexpr auto factor_batched = cusolverDnDpotrfBatched;
};

template <typename T>
void cholesky_impl(
cu::CommandEncoder& encoder,
const array& a,
array& out,
bool upper,
Stream s) {
// The factorization is in place, so work on a copy of the input.
copy_gpu(
a,
out,
a.flags().row_contiguous ? CopyType::Vector : CopyType::General,
s);

if (out.size() == 0) {
return;
}

int n = a.shape(-1);
int batch = static_cast<int>(cusolver_utils::batch_count(a));
auto uplo = cusolver_utils::uplo_for(upper);
auto handle = get_cusolver_handle(encoder);

// `info` is never read back: that needs a stream synchronize, and the CPU
// backend also declines to raise on a non positive-definite input.
//
// Allocate before the captures below, which allocate_workspace asserts.
auto* info =
static_cast<int*>(allocate_workspace(encoder, batch * sizeof(int)));

// insert_graph_dependencies() clears active_deps_ after each node, so every
// node below has to register the arrays it touches. Registering once leaves
// later nodes without predecessors, free to run before their inputs are
// ready.
if (batch > 1) {
// A raw workspace pointer has no array identity, so no dependency edge
// could be expressed between the fill kernel and potrfBatched reading it.
static_assert(sizeof(T*) == sizeof(uint64_t));
array ptrs_arr(
cu::malloc_async(batch * sizeof(T*), encoder), {batch}, uint64);
encoder.add_temporary(ptrs_arr);
auto** ptrs = gpu_ptr<T*>(ptrs_arr);

encoder.set_output_array(ptrs_arr);
encoder.add_kernel_node(
cu::set_batch_pointers<T>,
static_cast<uint32_t>(cuda::ceil_div(batch, 256)),
256,
ptrs,
gpu_ptr<T>(out),
static_cast<int64_t>(n) * n,
batch);

encoder.set_input_array(ptrs_arr);
encoder.set_input_array(out);
encoder.set_output_array(out);
auto capture = encoder.capture_context();
CHECK_CUSOLVER_ERROR(
Potrf<T>::factor_batched(handle, uplo, n, ptrs, n, info, batch));
} else {
int lwork = 0;
CHECK_CUSOLVER_ERROR(
Potrf<T>::buffer_size(handle, uplo, n, gpu_ptr<T>(out), n, &lwork));
auto* workspace =
static_cast<T*>(allocate_workspace(encoder, lwork * sizeof(T)));

encoder.set_input_array(out);
encoder.set_output_array(out);
auto capture = encoder.capture_context();
CHECK_CUSOLVER_ERROR(
Potrf<T>::factor(
handle, uplo, n, gpu_ptr<T>(out), n, workspace, lwork, info));
}

int64_t total = out.size();
encoder.set_input_array(out);
encoder.set_output_array(out);
encoder.add_kernel_node(
cu::zero_triangle<T>,
static_cast<uint32_t>(cuda::ceil_div(total, static_cast<int64_t>(256))),
256,
gpu_ptr<T>(out),
n,
upper,
total);
}

} // namespace

void Cholesky::eval_gpu(const std::vector<array>& inputs, array& out) {
nvtx3::scoped_range r("Cholesky::eval_gpu");
assert(inputs.size() == 1);
auto& encoder = cu::get_command_encoder(stream());

switch (inputs[0].dtype()) {
case float32:
cholesky_impl<float>(encoder, inputs[0], out, upper_, stream());
break;
case float64:
cholesky_impl<double>(encoder, inputs[0], out, upper_, stream());
break;
default:
throw std::runtime_error(
"[Cholesky::eval_gpu] only supports float32 or float64.");
}
}

} // namespace mlx::core
50 changes: 50 additions & 0 deletions mlx/backend/cuda/cusolver_utils.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright © 2025 Apple Inc.

#include "mlx/backend/cuda/cusolver_utils.h"
#include "mlx/backend/cuda/cuda.h"
#include "mlx/backend/gpu/device_info.h"
#include "mlx/utils.h"

namespace mlx::core {

namespace {

auto& cusolver_handles_cache() {
struct CusolverHandle {
~CusolverHandle() {
if (handle) {
CHECK_CUSOLVER_ERROR(cusolverDnDestroy(handle));
}
}
cusolverDnHandle_t handle{nullptr};
};
static thread_local std::vector<CusolverHandle> cache(gpu::device_count());
return cache;
}

} // namespace

void check_cusolver_error(const char* name, cusolverStatus_t err) {
if (err != CUSOLVER_STATUS_SUCCESS) {
// cuSOLVER has no status-to-string helper, so report the raw code.
throw std::runtime_error(
fmt::format("{} failed with code: {}.", name, static_cast<int>(err)));
}
}

void init_cusolver_handles_cache() {
cusolver_handles_cache();
}

cusolverDnHandle_t get_cusolver_handle(cu::CommandEncoder& encoder) {
auto& device = encoder.device();
auto& storage = cusolver_handles_cache().at(device.cuda_device());
if (!storage.handle) {
device.make_current();
CHECK_CUSOLVER_ERROR(cusolverDnCreate(&storage.handle));
}
CHECK_CUSOLVER_ERROR(cusolverDnSetStream(storage.handle, encoder.stream()));
return storage.handle;
}

} // namespace mlx::core
Loading