Skip to content
Merged
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
6 changes: 5 additions & 1 deletion mlx/allocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
#include <vector>
#endif

#include "mlx/api.h"
#include "mlx/stream.h"

namespace mlx::core::allocator {
class Data;
Expand Down Expand Up @@ -146,4 +146,8 @@ inline void release(Buffer buffer) {

MLX_API bool can_reuse_alien_buffer(void* ptr);

// Called after the host has written |buffer|. Backends whose GPU reads host
// memory slowly move it to device memory.
MLX_API void move_to_device_memory(Buffer buffer, StreamOrDevice s = {});

} // namespace mlx::core::allocator
7 changes: 5 additions & 2 deletions mlx/array.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,14 @@ array::array(
const std::function<void(void*)>& deleter)
: array_desc_(std::make_shared<ArrayDesc>(std::move(shape), dtype)) {
auto buffer = allocator::make_buffer(data, nbytes());
if (buffer.ptr() == nullptr) {
if (buffer.ptr() == nullptr) { // require copying to managed buffer
set_data(allocator::malloc(nbytes()));
auto ptr = static_cast<char*>(data);
std::copy(ptr, ptr + nbytes(), this->data<char>());
deleter(data);
if (deleter) {
deleter(data);
}
allocator::move_to_device_memory(this->buffer());
} else {
auto wrapped_deleter = [deleter](allocator::Buffer buffer) {
auto ptr = buffer.raw_ptr();
Expand Down
1 change: 1 addition & 0 deletions mlx/array.h
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,7 @@ void array::init(It src) {
std::copy(src, src + size(), data<complex64_t>());
break;
}
allocator::move_to_device_memory(buffer());
}

/* Utilities for determining whether a template parameter is array. */
Expand Down
104 changes: 78 additions & 26 deletions mlx/backend/cuda/allocator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -207,22 +207,7 @@ CudaAllocator::malloc_async(size_t size, int device, cudaStream_t stream) {
}
lock.unlock();
if (!buf) {
void* data = nullptr;
if (device == -1) {
data = unified_malloc(size);
} else {
cu::device(device).make_current();
if (mem_pools_[device]) { // supports memory pools
CHECK_CUDA_ERROR(cudaMallocAsync(&data, size, stream));
} else {
CHECK_CUDA_ERROR(cudaMalloc(&data, size));
}
}
if (!data) {
std::ostringstream msg;
msg << "[malloc] Unable to allocate " << size << " bytes.";
throw std::runtime_error(msg.str());
}
void* data = cuda_malloc_async(size, device, stream);
buf = new CudaBuffer{data, size, device};
}
lock.lock();
Expand Down Expand Up @@ -309,10 +294,10 @@ void CudaAllocator::move_to_unified_memory(
supports_managed_memory() ? cudaMemcpyDefault : cudaMemcpyDeviceToHost;
if (stream && mem_pools_[buf.device]) {
CHECK_CUDA_ERROR(cudaMemcpyAsync(data, buf.data, buf.size, kind, stream));
free_async(buf, stream);
cuda_free_async(buf.data, buf.device, stream);
} else {
CHECK_CUDA_ERROR(cudaMemcpy(data, buf.data, buf.size, kind));
free_async(buf);
cuda_free_async(buf.data, buf.device);
}
#ifndef NDEBUG
swap_allocation(buf.data, data);
Expand All @@ -321,28 +306,77 @@ void CudaAllocator::move_to_unified_memory(
buf.device = -1;
}

void CudaAllocator::move_to_device_memory(
CudaBuffer& buf,
CommandEncoder& encoder) {
// Allocate device buffer and copy to it.
int device = encoder.device().cuda_device();
void* dbuf = cuda_malloc_async(buf.size, device, encoder.stream());
if (mem_pools_[device]) { // async malloc is used
CHECK_CUDA_ERROR(cudaMemcpyAsync(
dbuf, buf.data, buf.size, cudaMemcpyHostToDevice, encoder.stream()));
cuda_free_async(buf.data, buf.device, encoder.stream());
encoder.synchronize();
} else {
CHECK_CUDA_ERROR(
cudaMemcpy(dbuf, buf.data, buf.size, cudaMemcpyHostToDevice));
cuda_free_async(buf.data, buf.device);
}
#ifndef NDEBUG
swap_allocation(buf.data, dbuf);
#endif
buf.data = dbuf;
buf.device = device;
}

// This must be called with mutex_ acquired
void CudaAllocator::free_cuda_buffer(CudaBuffer* buf) {
if (scalar_pool_.in_pool(buf)) {
scalar_pool_.free(buf);
} else {
free_async(*buf);
cuda_free_async(buf->data, buf->device);
delete buf;
}
}

void CudaAllocator::free_async(CudaBuffer& buf, cudaStream_t stream) {
if (buf.device == -1) {
unified_free(buf.data);
void* CudaAllocator::cuda_malloc_async(
size_t size,
int device,
cudaStream_t stream) {
void* data = nullptr;
if (device == -1) {
data = unified_malloc(size);
} else {
cu::device(device).make_current();
if (mem_pools_[device]) { // supports memory pools
CHECK_CUDA_ERROR(cudaMallocAsync(&data, size, stream));
} else {
CHECK_CUDA_ERROR(cudaMalloc(&data, size));
}
}
if (!data) {
std::ostringstream msg;
msg << "[malloc] Unable to allocate " << size << " bytes.";
throw std::runtime_error(msg.str());
}
return data;
}

void CudaAllocator::cuda_free_async(
void* data,
int device,
cudaStream_t stream) {
if (device == -1) {
unified_free(data);
} else {
// Free asynchronously when memory pools is supported.
if (mem_pools_[buf.device]) {
if (mem_pools_[device]) {
if (!stream) {
stream = free_streams_[buf.device];
stream = free_streams_[device];
}
cudaFreeAsync(buf.data, stream);
cudaFreeAsync(data, stream);
} else {
cudaFree(buf.data);
cudaFree(data);
}
}
}
Expand Down Expand Up @@ -456,6 +490,24 @@ bool over_memory_limit() {
return cu::allocator().over_memory_limit();
}

void move_to_device_memory(Buffer buffer, StreamOrDevice s_) {
if (!buffer.ptr()) {
return;
}
cu::CudaBuffer& buf = *static_cast<cu::CudaBuffer*>(buffer.ptr());
if (buf.device != -1) { // already on device memory
return;
}
if (buf.size < cu::page_size) { // small buffers are cheap to read over PCIe
return;
}
Stream s = to_stream(s_);
if (s.device.type != Device::gpu) {
return;
}
cu::allocator().move_to_device_memory(buf, cu::get_command_encoder(s));
}

} // namespace allocator

size_t get_active_memory() {
Expand Down
8 changes: 7 additions & 1 deletion mlx/backend/cuda/allocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ class CudaAllocator : public allocator::Allocator {
// host memory), and copy the data over. Pass |stream| to copy asynchronously.
void move_to_unified_memory(CudaBuffer& buf, cudaStream_t stream = nullptr);

// Replace the memory of |buf| with memory on |device| and copy the data
// over synchronously.
void move_to_device_memory(CudaBuffer& buf, CommandEncoder& encoder);

size_t get_active_memory() const;
size_t get_peak_memory() const;
void reset_peak_memory();
Expand All @@ -71,7 +75,9 @@ class CudaAllocator : public allocator::Allocator {
private:
size_t memory_limit_locked();
void free_cuda_buffer(CudaBuffer* buf);
void free_async(CudaBuffer& buf, cudaStream_t stream = nullptr);
void* cuda_malloc_async(size_t size, int device, cudaStream_t stream);
void
cuda_free_async(void* data, int device = -1, cudaStream_t stream = nullptr);

CudaAllocator();
friend CudaAllocator& allocator();
Expand Down
2 changes: 2 additions & 0 deletions mlx/backend/metal/allocator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ bool can_reuse_alien_buffer(void* ptr) {
return buf->storageMode() != MTL::StorageModePrivate;
}

void move_to_device_memory(Buffer, StreamOrDevice s) {}

} // namespace allocator

namespace metal {
Expand Down
2 changes: 2 additions & 0 deletions mlx/backend/no_gpu/allocator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,8 @@ bool can_reuse_alien_buffer(void*) {
return true;
}

void move_to_device_memory(Buffer, StreamOrDevice s) {}

} // namespace allocator

size_t get_active_memory() {
Expand Down
14 changes: 9 additions & 5 deletions mlx/io/gguf.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,9 @@ Shape get_shape(const gguf_tensor& tensor) {
return shape;
}

std::tuple<allocator::Data, Dtype> extract_tensor_data(gguf_tensor* tensor) {
std::tuple<allocator::Data, Dtype> extract_tensor_data(
gguf_tensor* tensor,
Stream s) {
if (tensor == nullptr) {
throw std::invalid_argument(
"[extract_tensor_data] Input tensor pointer is null.");
Expand All @@ -140,6 +142,7 @@ std::tuple<allocator::Data, Dtype> extract_tensor_data(gguf_tensor* tensor) {
out.buffer().raw_ptr(),
tensor->weights_data,
tensor->num_weights * equivalent_dtype.value().size());
allocator::move_to_device_memory(out.buffer(), s);
return {std::move(out), equivalent_dtype.value()};
}
// Otherwise, we convert to float16.
Expand All @@ -156,6 +159,7 @@ std::tuple<allocator::Data, Dtype> extract_tensor_data(gguf_tensor* tensor) {
auto out = allocator::malloc(new_size);
memcpy(out.buffer().raw_ptr(), data, new_size);
free(data);
allocator::move_to_device_memory(out.buffer(), s);
return {std::move(out), float16};
}

Expand Down Expand Up @@ -391,7 +395,7 @@ void check_tensor_in_file(const gguf_ctx* ctx, const gguf_tensor& tensor) {
}
}

std::unordered_map<std::string, array> load_arrays(gguf_ctx* ctx) {
std::unordered_map<std::string, array> load_arrays(gguf_ctx* ctx, Stream s) {
std::unordered_map<std::string, array> array_map;
gguf_tensor tensor;

Expand All @@ -408,10 +412,10 @@ std::unordered_map<std::string, array> load_arrays(gguf_ctx* ctx) {
check_tensor_in_file(ctx, tensor);
if (tensor.type == GGUF_TYPE_Q4_0 || tensor.type == GGUF_TYPE_Q4_1 ||
tensor.type == GGUF_TYPE_Q8_0) {
gguf_load_quantized(array_map, tensor);
gguf_load_quantized(array_map, tensor, s);
} else {
std::string name(tensor.name, tensor.namelen);
auto [data, dtype] = extract_tensor_data(&tensor);
auto [data, dtype] = extract_tensor_data(&tensor, s);
array loaded_array = array(std::move(data), get_shape(tensor), dtype);
check_insert(array_map.insert({name, loaded_array}));
}
Expand All @@ -435,7 +439,7 @@ GGUFLoad load_gguf(const std::string& file, StreamOrDevice s) {
throw std::runtime_error("[load_gguf] gguf_init failed");
}
auto metadata = load_metadata(ctx.get());
auto arrays = load_arrays(ctx.get());
auto arrays = load_arrays(ctx.get(), to_stream(s));
return {arrays, metadata};
}

Expand Down
3 changes: 2 additions & 1 deletion mlx/io/gguf.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ namespace mlx::core {
Shape get_shape(const gguf_tensor& tensor);
void gguf_load_quantized(
std::unordered_map<std::string, array>& a,
const gguf_tensor& tensor);
const gguf_tensor& tensor,
Stream s);

} // namespace mlx::core
6 changes: 5 additions & 1 deletion mlx/io/gguf_quants.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ void extract_q8_0_data(

void gguf_load_quantized(
std::unordered_map<std::string, array>& a,
const gguf_tensor& tensor) {
const gguf_tensor& tensor,
Stream s) {
uint64_t weights_per_byte;
if (tensor.type == GGUF_TYPE_Q4_0 || tensor.type == GGUF_TYPE_Q4_1) {
weights_per_byte = 2;
Expand Down Expand Up @@ -151,6 +152,9 @@ void gguf_load_quantized(
} else if (tensor.type == GGUF_TYPE_Q8_0) {
extract_q8_0_data(tensor, weights, scales, biases);
}
allocator::move_to_device_memory(weights.buffer(), s);
allocator::move_to_device_memory(scales.buffer(), s);
allocator::move_to_device_memory(biases.buffer(), s);

a.emplace(name, std::move(weights));

Expand Down
7 changes: 7 additions & 0 deletions mlx/stream.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ struct MLX_API ThreadLocalStream : public Stream {
using Stream::Stream;
};

using StreamOrDevice = std::variant<
std::monostate,
Stream,
ThreadLocalStream,
Device,
Device::DeviceType>;

/** Get the default stream of current thread for the given device. */
MLX_API Stream default_stream(Device d);

Expand Down
6 changes: 0 additions & 6 deletions mlx/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,6 @@

namespace mlx::core {

using StreamOrDevice = std::variant<
std::monostate,
Stream,
ThreadLocalStream,
Device,
Device::DeviceType>;
MLX_API Stream to_stream(StreamOrDevice s);
MLX_API Stream to_stream(StreamOrDevice s, Device default_);

Expand Down
1 change: 1 addition & 0 deletions python/src/convert.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ mx::array cpu_nd_array_to_mlx(
auto dst = out.data<DstT>();
std::copy(src, src + storage_size, dst);
});
mx::allocator::move_to_device_memory(out.buffer());
}
out.set_status(mx::array::Status::available);
return out;
Expand Down
24 changes: 24 additions & 0 deletions tests/cuda_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
#include "doctest/doctest.h"
#include "mlx/mlx.h"

#include "mlx/backend/cuda/allocator.h"

#ifdef _WIN32
#include "mlx/backend/cuda/wddm.h"
#endif
Expand All @@ -26,6 +28,12 @@ bool memory_pools_supported() {
return supported;
}

cudaMemoryType residency(void* ptr) {
cudaPointerAttributes attr{};
REQUIRE_EQ(cudaPointerGetAttributes(&attr, ptr), cudaSuccess);
return attr.type;
}

struct CacheLimitGuard {
~CacheLimitGuard() {
set_cache_limit(previous);
Expand Down Expand Up @@ -112,6 +120,22 @@ TEST_CASE("test clear cache trims CUDA pool") {
CHECK_LT(final_reserved, allocated_reserved);
}

TEST_CASE("test host data is moved to device memory") {
auto data = [](const array& a) {
return static_cast<cu::CudaBuffer*>(a.buffer().ptr())->data;
};
std::vector<float> v(1 << 20, 2.0f);
array a(v.begin(), {1 << 20});
CHECK_NE(residency(data(a)), cudaMemoryTypeHost);
CHECK_EQ(sum(a).item<float>(), 2.0f * (1 << 20));

// Arrays for a CPU default device stay on the host.
set_default_device(Device::cpu);
array b(v.begin(), {1 << 20});
set_default_device(Device::gpu);
CHECK_NE(residency(data(b)), cudaMemoryTypeDevice);
}

TEST_CASE("test eval after cuda error") {
auto s = default_stream(Device::gpu);
// A failed allocation sets a CUDA error on the calling thread.
Expand Down
Loading