Skip to content
Open
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: 3 additions & 3 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ set(MLX_BUILD_EXAMPLES OFF)
set(MLX_BUILD_BENCHMARKS OFF)
set(MLX_BUILD_PYTHON_BINDINGS OFF)

# mlx: v0.32.3 plus stream fixes for floor_divide, gather_mm/gather_qmm indices,
# layer_norm and SDPA, the same commit as the Source/Cmlx/mlx submodule
# mlx: v0.32.4 plus MLX_RING_SOURCE_IPS, which binds the ring's outgoing
# connections to given IPs, the same commit as the Source/Cmlx/mlx submodule
FetchContent_Declare(
mlx
GIT_REPOSITORY "https://github.com/PicoMLX/mlx.git"
GIT_TAG "f21a95934a3ff26dc1c1d21f132e3e23448ed116")
GIT_TAG "598b041ba7146e830a340a6317476815d42e7ab5")
FetchContent_MakeAvailable(mlx)

# mlx-c: 0.7.0 plus ml-explore/mlx-c#137 (gather_qmm for MLX v0.32.3), the same
Expand Down
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ let cmlx = Target.target(
.headerSearchPath("json/single_include/nlohmann"),
.headerSearchPath("fmt/include"),
// MLX's CMake reads this from mlx/version.h; tools/update-mlx.sh keeps it in sync
.define("MLX_VERSION", to: "\"0.32.3\""),
.define("MLX_VERSION", to: "\"0.32.4\""),
],
linkerSettings: linkerSettings,
plugins: cudaBuildPlugins,
Expand Down
2 changes: 1 addition & 1 deletion Source/Cmlx/include-framework/Metal.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//
// Metal.hpp.in
//
// Autogenerated from commit 8f784840de21cacd0c5c237ea860179e47dcec91.
// Autogenerated from commit d1288278beee1a212c03abac2bd364b5bec19f28.
//
// Copyright 2020-2024 Apple Inc.
//
Expand Down
56 changes: 51 additions & 5 deletions Source/Cmlx/include-framework/mlx-allocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,20 @@
#pragma once

#include <cstdlib>
#include <functional>
#include <utility>

#include <Cmlx/mlx-api.h>

namespace mlx::core::allocator {
class Data;
} // namespace mlx::core::allocator

namespace mlx::core::cu {
class CommandEncoder;
allocator::Data malloc_async(size_t size, CommandEncoder& encoder);
} // namespace mlx::core::cu

namespace mlx::core::allocator {

// Simple wrapper around buffer pointers
Expand Down Expand Up @@ -52,12 +63,47 @@ class MLX_API Allocator {

MLX_API Allocator& allocator();

inline Buffer malloc(size_t size) {
return allocator().malloc(size);
}
using Deleter = std::function<void(Buffer)>;

// The allocator owns data from malloc
class Data {
public:
Data(Buffer buffer, Deleter d) : buffer_(buffer), deleter_(std::move(d)) {}
Data(const Data& other) = delete;
Data& operator=(const Data& other) = delete;
Data(Data&& other) noexcept
: buffer_(std::exchange(other.buffer_, Buffer(nullptr))),
deleter_(std::exchange(other.deleter_, nullptr)),
owned_(std::exchange(other.owned_, false)) {}
~Data() {
if (owned_) {
allocator().free(buffer_);
} else if (deleter_) {
deleter_(buffer_);
}
}

Buffer buffer() const& {
return buffer_;
}
Buffer buffer() const&& = delete;

bool is_owned() const {
return owned_;
}

private:
Buffer buffer_;
Deleter deleter_;
bool owned_{false};

explicit Data(Buffer buffer) : buffer_(buffer), owned_(true) {}
friend Data malloc(size_t size);
friend Data cu::malloc_async(size_t size, cu::CommandEncoder& encoder);
};

inline void free(Buffer buffer) {
allocator().free(buffer);
inline Data malloc(size_t size) {
return Data(allocator().malloc(size));
}

// Make a Buffer from a raw pointer of the given size without a copy. If a
Expand Down
52 changes: 10 additions & 42 deletions Source/Cmlx/include-framework/mlx-array.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ namespace mlx::core {
// Forward declaration
class Primitive;

using Deleter = std::function<void(allocator::Buffer)>;
using ShapeElem = int32_t;
using Shape = SmallVector<ShapeElem>;
using Strides = SmallVector<int64_t>;
Expand Down Expand Up @@ -70,12 +69,8 @@ class MLX_API array {
Dtype dtype,
const std::function<void(void*)>& deleter);

/* Build an array from a buffer */
explicit array(
allocator::Buffer data,
Shape shape,
Dtype dtype,
Deleter deleter = allocator::free);
/* Build an array from data */
explicit array(allocator::Data data, Shape shape, Dtype dtype);

/** Assignment to rvalue does not compile. */
array& operator=(const array& other) && = delete;
Expand Down Expand Up @@ -239,22 +234,7 @@ class MLX_API array {
return reinterpret_cast<std::uintptr_t>(array_desc_->primitive.get());
}

struct Data {
allocator::Buffer buffer;
Deleter d;
Data(allocator::Buffer buffer, Deleter d = allocator::free)
: buffer(buffer), d(d) {}
// Not copyable
Data(const Data& d) = delete;
Data& operator=(const Data& d) = delete;
Data(Data&& o) : buffer(o.buffer), d(o.d) {
o.buffer = allocator::Buffer(nullptr);
o.d = [](allocator::Buffer) {};
}
~Data() {
d(buffer);
}
};
using Data = allocator::Data;

struct Flags {
// True iff there are no gaps in the underlying data. Each item
Expand Down Expand Up @@ -303,7 +283,8 @@ class MLX_API array {

/** True indicates the arrays buffer is safe to reuse */
bool is_donatable() const {
return array_desc_.use_count() == 1 && (array_desc_->data.use_count() == 1);
return array_desc_.use_count() == 1 &&
(array_desc_->data.use_count() == 1) && array_desc_->data->is_owned();
}

/** The array's siblings. */
Expand Down Expand Up @@ -360,11 +341,8 @@ class MLX_API array {
return array_desc_->data_size;
}

allocator::Buffer& buffer() {
return array_desc_->data->buffer;
}
const allocator::Buffer& buffer() const {
return array_desc_->data->buffer;
allocator::Buffer buffer() const {
return array_desc_->data->buffer();
}

size_t buffer_size() const {
Expand Down Expand Up @@ -448,24 +426,14 @@ class MLX_API array {
// Check if the array is a tracer array
bool is_tracer() const;

void set_data(allocator::Buffer buffer, Deleter d = allocator::free);
void set_data(allocator::Data data);

void set_data(
allocator::Buffer buffer,
allocator::Data data,
size_t data_size,
Strides strides,
Flags flags,
Deleter d) {
set_data(buffer, data_size, std::move(strides), flags, 0, std::move(d));
}

void set_data(
allocator::Buffer buffer,
size_t data_size,
Strides strides,
Flags flags,
int64_t offset = 0,
Deleter d = allocator::free);
int64_t offset = 0);

void copy_shared_buffer(
const array& other,
Expand Down
11 changes: 8 additions & 3 deletions Source/Cmlx/include-framework/mlx-backend-metal-device.h
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,13 @@ class MLX_API CommandEncoder {

template <typename Vec, typename = std::enable_if_t<is_vector_v<Vec>>>
void set_vector_bytes(const Vec& vec, size_t nelems, int idx) {
get_command_encoder()->setBytes(
vec.data(), nelems * sizeof(typename Vec::value_type), idx);
using T = typename Vec::value_type;
if (nelems > 0) {
get_command_encoder()->setBytes(vec.data(), nelems * sizeof(T), idx);
} else {
T val{};
get_command_encoder()->setBytes(&val, sizeof(T), idx);
}
}
template <typename Vec, typename = std::enable_if_t<is_vector_v<Vec>>>
void set_vector_bytes(const Vec& vec, int idx) {
Expand All @@ -90,7 +95,7 @@ class MLX_API CommandEncoder {
}

void barrier();
void end_encoding();
void end_encoding(bool wait_in_flight = false);
void wait_event(Event event, uint64_t value);
void signal_event(Event event, uint64_t value);
bool needs_commit() const;
Expand Down
10 changes: 8 additions & 2 deletions Source/Cmlx/include-framework/mlx-backend-metal-resident.h
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
#ifdef __cplusplus
// Copyright © 2024 Apple Inc.
// Copyright © 2024-2026 Apple Inc.

#pragma once

#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>

Expand Down Expand Up @@ -97,7 +100,7 @@ class ResidencySets {
// gave us a set; the new set is the last one. add_to_set_locked returns the
// set it used. Neither it nor remove_from_set_locked commits, so a bulk
// resize costs one commit per set instead of one per allocation.
bool add_set_locked(NS::Error** error = nullptr);
bool add_set_locked(std::string* error = nullptr);
uint32_t choose_set_locked(size_t bytes);
uint32_t add_to_set_locked(const MTL::Allocation* buf, Placement& at);
void remove_from_set_locked(const MTL::Allocation* buf, Placement& at);
Expand All @@ -119,6 +122,9 @@ class ResidencySets {
// taking the lock.
std::atomic<uint64_t> num_sets_{0};
mutable std::mutex mtx_;
std::condition_variable refresh_cv_;
bool stop_refresh_{false};
std::thread refresh_thread_;
};

} // namespace mlx::core::metal
Expand Down
28 changes: 28 additions & 0 deletions Source/Cmlx/include-framework/mlx-fft.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#pragma once

#include <cstdint>
#include <optional>
#include <variant>

#include <Cmlx/mlx-array.h>
Expand Down Expand Up @@ -213,6 +214,7 @@ inline array irfft2(
StreamOrDevice s = {}) {
return irfftn(a, axes, norm, s);
}

/** Compute the discrete Fourier Transform sample frequencies. */
MLX_API array fftfreq(int n, double d = 1.0, StreamOrDevice s = {});

Expand All @@ -235,5 +237,31 @@ MLX_API array ifftshift(const array& a, StreamOrDevice s = {});
MLX_API array
ifftshift(const array& a, const std::vector<int>& axes, StreamOrDevice s = {});

/** Compute the Short-Time Fourier Transform of the last axis of `x`. */
MLX_API array stft(
const array& x,
int n_fft = 2048,
const std::optional<int>& hop_length = std::nullopt,
const std::optional<int>& win_length = std::nullopt,
const std::optional<array>& window = std::nullopt,
bool center = true,
const std::string& pad_mode = "reflect",
FFTNorm norm = FFTNorm::Backward,
const std::optional<bool>& onesided = std::nullopt,
StreamOrDevice s = {});

/** Compute the inverse Short-Time Fourier Transform. */
MLX_API array istft(
const array& stft_matrix,
const std::optional<int>& n_fft = std::nullopt,
const std::optional<int>& hop_length = std::nullopt,
const std::optional<int>& win_length = std::nullopt,
const std::optional<array>& window = std::nullopt,
bool center = true,
FFTNorm norm = FFTNorm::Backward,
const std::optional<bool>& onesided = std::nullopt,
const std::optional<int>& length = std::nullopt,
StreamOrDevice s = {});

} // namespace mlx::core::fft
#endif
38 changes: 38 additions & 0 deletions Source/Cmlx/include-framework/mlx-ops.h
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,23 @@ min(const array& a,
MLX_API array
min(const array& a, int axis, bool keepdims = false, StreamOrDevice s = {});

MLX_API std::tuple<array, array>
minmax(const array& a, bool keepdims, StreamOrDevice s = {});
inline std::tuple<array, array> minmax(const array& a, StreamOrDevice s = {}) {
return minmax(a, false, to_stream(s));
}

/** The minimum and maximum of the elements of an array along the given axes. */
MLX_API std::tuple<array, array> minmax(
const array& a,
const std::vector<int>& axes,
bool keepdims = false,
StreamOrDevice s = {});

/** The minimum and maximum of the elements of an array along the given axis. */
MLX_API std::tuple<array, array>
minmax(const array& a, int axis, bool keepdims = false, StreamOrDevice s = {});

/** Returns the Hanning window of size M. */
MLX_API array hanning(int M, StreamOrDevice s = {});

Expand Down Expand Up @@ -882,6 +899,27 @@ MLX_API array topk(const array& a, int k, StreamOrDevice s = {});
/** Returns topk elements of the array along a given axis. */
MLX_API array topk(const array& a, int k, int axis, StreamOrDevice s = {});

/**
* Returns the sorted unique elements of the flattened array, and optionally
* the index of the first occurrence of each, the inverse indices and the
* counts. The output has the given size, and
* is truncated if ``size`` is smaller than the number of unique values.
* If ``size`` is larger, the result is padded with ``fill_value``, or the
* first of the sorted unique values if no fill value is provided. An empty
* input has none, so it throws unless ``size`` is zero or a fill value is
* given.
* A truncated output loses the counts of the values it drops, and its inverse
* indices are clamped to the last entry.
*/
MLX_API std::vector<array> unique(
const array& a,
int size,
bool return_index = false,
bool return_inverse = false,
bool return_counts = false,
const std::optional<array>& fill_value = std::nullopt,
StreamOrDevice s = {});

/** Cumulative logsumexp of an array. */
MLX_API array logcumsumexp(
const array& a,
Expand Down
Loading